Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
✅ Practice + Quiz  ·  Lesson 26

Java Practice Programs with Output

In this lesson: Java practice programs with code and output — numbers, strings, arrays, patterns — run each in the online compiler.

How to use these 67 Java practice programs

This page is a practice workbook, not a theory lesson. Every one of the 67 programs reads its input with the Scanner class, prints a real answer, and has a Load compiler ↓ button that opens a free online Java compiler right under it with the code already filled in. Nothing to install, nothing to sign up for.

Here is the way I ask students to use it. Read the task, cover the code, and try to write it yourself for ten minutes — in your notebook or in the compiler. Only then compare with the solution. Students who just copy, run and move on usually forget the logic within a week; the ones who struggle for ten minutes remember the trick for years.

✅ Every sample run on this page was produced by actually compiling and running the program, with the exact input shown — not typed by hand.

Run every program online — free, no install

Under each program you will find a Load compiler ↓ button. Click it and a complete Java compiler (OneCompiler) opens directly below that program, with the program already in the editor. Then:

  1. Click Copy input in the sample-input box.
  2. In the compiler, open the STDIN / I/O tab and paste the input there.
  3. Press Run. Your output should match the sample run on this page.
  4. Now break it on purpose — change a number, remove a bracket, swap a condition — and run again. That is where real learning happens.
💡 Why is every class called Main? Online compilers save your code as Main.java, and Java insists that a public class has the same name as its file. On your own computer you can name the class Demo — just save the file as Demo.java.

Reading input with Scanner: a 30-second recap

MethodReadsExample input
nextInt()a whole number (int)25
nextLong()a big whole number (long)10000000000
nextDouble()a decimal number7.5
next()one word, up to the next spaceAman
nextLine()the rest of the line, spaces includedAman Verma

One trap catches almost everyone once: after nextInt(), a nextLine() returns an empty string, because the Enter key you pressed is still waiting in the input. Call sc.nextLine(); once to throw it away. The full story is in the lesson on user input with Scanner.

Basic calculation programs (1–10)

Warm-up programs. They look easy, but each one hides a small lesson — integer division, overflow, rounding, dividing by zero. Read the one-line note above every program before you run it.

If-else and if-else-if programs (11–20)

Decision making. The question to ask yourself every time: in which order should I check the conditions? Half the bugs in this section come from checking them in the wrong order.

Loop programs (21–28)

Loops repeat work. Before writing any loop, answer three questions on paper: where does it start, when does it stop, and what changes each time? The Fibonacci series is the best example of "what changes" — two variables slide forward together.

Fibonacci: each term = the previous two addedThe series 0, 1, 1, 2, 3, 5, 8, 13 with 2 + 3 = 5 and 3 + 5 = 8 marked.Fibonacci: each term = the previous two added0112358132 + 3 = 53 + 5 = 8a, b slide forward: a = b; b = next
Fibonacci drawn on a notebook page: every new term is the sum of the two before it.

Special number programs (29–40)

Reverse, palindrome, Armstrong, perfect, prime, strong, neon, automorphic, Harshad, spy — these are the number programs that appear in school practical files, viva and job interviews. The good news: almost all of them stand on the same two lines of code.

The two-line trick: % 10 and / 10For 1234, % 10 gives the last digit 4 and / 10 drops it to leave 123.The two-line trick: % 10 and / 101234n % 10 → 4gives the last digitn / 10 → 123drops the last digitRepeat until n becomes 01234 → 123 → 12 → 1 → 0
The two lines behind almost every number program: % 10 takes the last digit, / 10 removes it.

From my class notebook

This is the reverse-number and palindrome program exactly as I wrote it in my notebook while preparing for class, with the dry run for n = 123 on the next page. Follow the circled steps: in each pass the last digit moves to rev, and n loses that digit, until n becomes 0 and the loop ends.

Handwritten Java program in a notebook: read a number with Scanner, reverse it and check for palindrome
Notebook page 1: reverse number and palindrome check, written by hand.
Handwritten dry run of reversing n = 123, where rev becomes 3, 32 and then 321 in three passes
Notebook page 2: dry run for n = 123 — three passes, then n = 0 and the loop ends.
✍️ Honest note: the handwritten version has two slips that the compiler would catch — the variable r is never declared, and the class is named Demo, which online compilers will not accept. The typed programs below fix both. Spotting such slips is itself good practice.
Palindrome: compare n with its reverse121 reversed is still 121, so it is a palindrome; 123 reversed is 321, so it is not.Palindrome: compare n with its reverse121rev = 121121 == 121palindrome123rev = 321123 ≠ 321not palindromeTip: save t = n before the loop — the loop turns n into 0.
A palindrome check is just "reverse the number and compare".
Armstrong number: 153Adding the cubes of the digits of 153 gives 1 + 125 + 27 = 153.Armstrong number: 15311³ = 155³ = 12533³ = 271 + 125 + 27 = 153= the number itselfMore Armstrong numbers3 digits: 153, 370, 371, 4074 digits: 1634, 8208, 9474power = number of digits!
153 is an Armstrong number because the cubes of its digits add up to 153.
Perfect number: 28The proper divisors of 28 (1, 2, 4, 7, 14) add up to 28; those of 12 add up to 16.Perfect number: 281+2+4+7+14= 28divisors of 28 (except 28 itself)12 → 1+2+3+4+6 = 16 ≠ 12 (not perfect)Very rare!6, 28, 496, 8128
28 is perfect: its proper divisors add up to exactly 28.
Why we stop at i × i ≤ n (n = 36)Divisor pairs of 36 repeat in reverse after 6 × 6, so checking up to √n is enough.Why we stop at i × i ≤ n (n = 36)i36 / i136218312496694123182361√36 = 6 — mirror linethe same pairs again, flippedCheck only up to 6No divisor up to √n meansno divisor after it either.0 and 1 are NOT prime
Divisor pairs of 36 mirror after 6 × 6, so a prime check can stop at √n.

A quick reference before you start:

NumberRuleExample
Palindromesame as its reverse121, 1331
Armstrongsum of digits ^ (number of digits) = number153, 9474
Perfectsum of proper divisors = number6, 28, 496
Primeexactly two divisors, 1 and itself2, 13, 97
Strongsum of factorials of digits = number145
Neonsum of digits of its square = number9 (81 → 8 + 1)
Automorphicits square ends with the number25, 76
Harshad (Niven)divisible by the sum of its digits18, 156
Spysum of digits = product of digits22, 1124

Pattern programs (41–50)

Pattern programs are pure loop practice. Do not try to memorise them. Draw a small grid, number the rows i and the columns j, and write down how many characters each row needs — the code then writes itself.

Right triangle: row i has i starsA 4-row grid where row i has stars for j = 1 to i.Right triangle: row i has i starsj=1j=2j=3j=4i = 1*i = 2**i = 3***i = 4****Pattern recipe1. outer loop = rows (i)2. inner loop = columns (j)3. decide: how many j in row i?here: j goes 1 → i
The pattern recipe: outer loop for rows, inner loop for columns, and one rule for how many columns row i needs.

Array programs (51–60)

All array programs use the same input format: first the number of elements, then the elements on the next line separated by spaces. Notice that indexes start at 0, but when we tell a human a position we add 1.

Class and object programs (61–67)

Until now everything lived inside main. Real programs keep data together with the code that works on that data — that bundle is a class. Here are the words you need, each linked to a program below:

TermMeaning in one lineSee program
ClassA blueprint that describes what its objects know and do.61 — Student
ObjectA real thing built from the class with new.61 — s1
Data member (field)A variable inside the class; every object gets its own copy.61 — roll, name
Member methodA function inside the class that works on the object's data.61 — display()
ConstructorSpecial method with the class name; runs once when new creates the object.62 — Rectangle(l, b)
Dot operatorReaches a member of one particular object.s1.marks, r1.area()
privateHides a data member from code outside the class.63 — balance
static memberOne copy shared by the whole class, not one per object.64 — count
thisMeans "the current object"; separates a field from a parameter with the same name.63, 64, 66
Parts of a classA Student class with its data members, constructor and member method marked in different colours.Parts of a classclass Student {int roll;String name;Student(int r, String n) {roll = r; name = n;}void display() {System.out.println(name);}}data memberswhat an object knowsconstructorruns once, when new is calledmember methodwhat an object can do
The three parts you will write in almost every class: data members, a constructor and member methods.

The single most useful picture in OOP: a class is a blueprint, and every new builds a separate object from it. Two students, two objects, two separate sets of marks.

Class = blueprint, object = real thingTwo objects, s1 (Aman) and s2 (Priya), created from the Student class with new, each holding its own data members.Class = blueprint, object = real thingclass Studentdata membersint roll;String name;int marks;member methodsvoid display()String result()new Student()new Student()s1(an object)roll = 101name = "Aman"marks = 78s2(an object)roll = 102name = "Priya"marks = 91s1.display() uses only s1's dataOne class, many objects — each object keeps its own copy of the data members.
One Student class, two objects. s1.display() prints Aman's data; s2.display() prints Priya's.

And the mistake that confuses almost every beginner: assigning one object variable to another does not make a copy. It copies the address. Program 67 proves it.

Reference, not copy: b = aVariables a and b point to the same Box object, while c points to a second object made with new.Reference, not copy: b = aStack (variables)Heap (objects)abcBox object #1value = 99Box object #2value = 5a and b point to ONE object!b.value = 99 changes a.value too. Only new makes a second object.
b = a makes two arrows to the same object. Only another new gives you a real second object.

Mistakes I see most often

  • Using the original number after the loop. Reverse-type loops turn n into 0. Save a copy (t = n) before the loop.
  • Integer division by accident. 7 / 2 is 3 in Java. Use 7 / 2.0 or a (double) cast when you need 3.5.
  • Starting max at 0. For an array of negative numbers the answer will be wrong. Start with a[0].
  • Calling 1 a prime. A prime has exactly two divisors; 1 has only one.
  • Forgetting to reset a flag or a sum inside an outer loop (programs 34 and 41–50 are where this bites).
  • Creating an array of objects but no objects. new Book[3] gives three empty slots; each slot still needs new Book().
  • Thinking b = a copies an object. It copies the reference — see program 67.
  • Naming the public class something other than the file. In online compilers, keep it Main.

A 10-day practice plan

DayProgramsFocus
11–10Scanner, data types, integer vs decimal division
211–20Order of conditions, && and ||
321–28Start, stop and change of every loop
429–34The % 10 and / 10 trick
535–40Combining loops with conditions
641–45Row and column thinking
746–50Spaces and two inner loops
851–60Indexes and one-pass algorithms
961–64Class, object, constructor, private, static
1065–67Arrays of objects and references; then redo any five programs without looking

Summary

  • Every program takes input with Scanner and can be run under itself with Load compiler ↓.
  • Most number programs rest on two lines: n % 10 and n / 10.
  • Patterns are rows (i) and columns (j); decide how many columns each row needs.
  • A class bundles data members and member methods; each object made with new keeps its own data.
  • Write first, then compare. Ten minutes of struggle is worth more than ten copied programs.

Next, try the Java practical file programs for school practical exams, or test yourself with the Java interview questions.

Frequently Asked Questions

How can I run these Java programs online for free?
Click the Load compiler button under any program. A free OneCompiler Java editor opens below it with the code already filled in. Paste the sample input into the STDIN box and press Run. Nothing needs to be installed.
Why is the class named Main in every program?
Online compilers save the code as Main.java, and Java requires a public class to have the same name as its file. On your own computer you can use any class name as long as the file name matches it.
How do I give input to a Java program in an online compiler?
Type or paste every value into the STDIN (input) box before pressing Run, one value per line or separated by spaces. Scanner reads them in order, exactly as if you had typed them at the keyboard.
What is an Armstrong number in Java?
A number equal to the sum of its digits, each raised to the power of the number of digits. 153 = 1³ + 5³ + 3³ and 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴. The program counts the digits first so it works for any length.
What is a perfect number?
A number equal to the sum of its proper divisors, that is, all divisors except itself. 6 = 1 + 2 + 3 and 28 = 1 + 2 + 4 + 7 + 14. Only a few are known: 6, 28, 496 and 8128 are the first four.
Why does the prime number program stop at the square root?
Divisors come in pairs, and after the square root the pairs simply repeat in reverse order. If no divisor is found up to the square root of n, none exists after it, so checking i × i ≤ n is enough and far faster.
What is the difference between a class and an object?
A class is a blueprint that describes the data members and member methods. An object is a real thing created from that blueprint with new. One Student class can create many student objects, each holding its own roll number and marks.
What are data members and member methods?
Data members are the variables declared inside a class, such as roll and name; every object gets its own copy. Member methods are the functions inside the class, such as display(), and they work on the data of the object that calls them.
In what order should I practise these programs?
Go section by section: calculations, if-else, loops, number programs, patterns, arrays and finally classes and objects. The 10-day plan on this page splits all 67 programs into daily sets, and the last day is for rewriting programs without looking.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicPractical File Programs (with Compiler) Your progress: 26 / 61 (43%) · Lesson 27 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free