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:
Click Copy input in the sample-input box.
In the compiler, open the STDIN / I/O tab and paste the input there.
Press Run. Your output should match the sample run on this page.
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
Method
Reads
Example input
nextInt()
a whole number (int)
25
nextLong()
a big whole number (long)
10000000000
nextDouble()
a decimal number
7.5
next()
one word, up to the next space
Aman
nextLine()
the rest of the line, spaces included
Aman 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.
1. Add two numbers
The very first Scanner program: read two integers and print their sum. Type both numbers on separate lines (or on one line with a space — Scanner accepts either).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println("Sum = " + (a + b));
}
}
Sample input
5
3
Sample run (what you will see)
Enter first number: 5
Enter second number: 3
Sum = 8
2. Subtract two numbers
Same structure as addition. Notice the brackets around (a - b): without them Java would join the text "Difference = " with a and then try to subtract — a compile error.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println("Difference = " + (a - b));
}
}
Sample input
10
4
Sample run (what you will see)
Enter first number: 10
Enter second number: 4
Difference = 6
3. Multiply two numbers
Uses long instead of int, because the product of two large int values can overflow. Try 100000 × 100000 with int and see the wrong answer for yourself.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
long a = sc.nextLong();
System.out.print("Enter second number: ");
long b = sc.nextLong();
System.out.println("Product = " + (a * b));
}
}
Sample input
100000
100000
Sample run (what you will see)
Enter first number: 100000
Enter second number: 100000
Product = 10000000000
4. Divide two numbers (with zero check)
Two lessons in one: 7 / 2 with int gives 3, so we cast to double to get 3.5; and dividing by zero must be checked before it crashes the program.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter dividend: ");
int a = sc.nextInt();
System.out.print("Enter divisor: ");
int b = sc.nextInt();
if (b == 0) {
System.out.println("Cannot divide by zero");
} else {
System.out.println("Quotient = " + (double) a / b);
}
}
}
Sample input
7
2
Sample run (what you will see)
Enter dividend: 7
Enter divisor: 2
Quotient = 3.5
5. Find the remainder
The % operator gives the remainder. You will meet it again and again in this page — even/odd, digits of a number, prime checks — so get comfortable with it here.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter dividend: ");
int a = sc.nextInt();
System.out.print("Enter divisor: ");
int b = sc.nextInt();
System.out.println(a + " % " + b + " = " + (a % b));
}
}
Sample input
17
5
Sample run (what you will see)
Enter dividend: 17
Enter divisor: 5
17 % 5 = 2
6. Area and perimeter of a rectangle
Lengths are usually decimals, so we read double values. Area = length × breadth, perimeter = 2 × (length + breadth).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter length: ");
double l = sc.nextDouble();
System.out.print("Enter breadth: ");
double b = sc.nextDouble();
System.out.println("Area = " + (l * b));
System.out.println("Perimeter = " + 2 * (l + b));
}
}
Sample input
12.5
4
Sample run (what you will see)
Enter length: 12.5
Enter breadth: 4
Area = 50.0
Perimeter = 33.0
7. Area of a circle
Math.PI is more accurate than typing 3.14. printf("%.2f") rounds the answer to two decimal places, which is how marks-sheet style answers are usually written.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius: ");
double r = sc.nextDouble();
double area = Math.PI * r * r;
System.out.printf("Area = %.2f%n", area);
}
}
Sample input
7
Sample run (what you will see)
Enter radius: 7
Area = 153.94
8. Simple interest
SI = (P × R × T) / 100. Reading all three as double lets the user enter a rate such as 7.5 %.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter principal: ");
double p = sc.nextDouble();
System.out.print("Enter rate (% per year): ");
double r = sc.nextDouble();
System.out.print("Enter time (years): ");
double t = sc.nextDouble();
double si = (p * r * t) / 100;
System.out.printf("Simple Interest = %.2f%n", si);
System.out.printf("Total Amount = %.2f%n", p + si);
}
}
Sample input
20000
7.5
3
Sample run (what you will see)
Enter principal: 20000
Enter rate (% per year): 7.5
Enter time (years): 3
Simple Interest = 4500.00
Total Amount = 24500.00
9. Average of three numbers
A classic trap: (a + b + c) / 3 with int values throws away the decimal part. Dividing by 3.0 keeps it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
double avg = (a + b + c) / 3.0;
System.out.printf("Average = %.2f%n", avg);
}
}
Sample input
10 20 25
Sample run (what you will see)
Enter three numbers: 10 20 25
Average = 18.33
10. Swap two numbers
Think of two glasses of juice: you need a third empty glass to exchange them. The variable temp is that empty glass.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a and b: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Before: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After: a = " + a + ", b = " + b);
}
}
Sample input
15 40
Sample run (what you will see)
Enter a and b: 15 40
Before: a = 15, b = 40
After: a = 40, b = 15
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.
11. Check even or odd
If a number leaves remainder 0 when divided by 2, it is even. This works for negative numbers too, because -4 % 2 is 0.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}
The program also handles the case students usually forget: both numbers equal.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
if (a > b) {
System.out.println("Largest = " + a);
} else if (b > a) {
System.out.println("Largest = " + b);
} else {
System.out.println("Both are equal");
}
}
}
Sample input
48 75
Sample run (what you will see)
Enter two numbers: 48 75
Largest = 75
13. Largest of three numbers
Instead of a long chain of && conditions, assume the first number is the largest and correct the guess twice. This idea grows straight into "largest in an array".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
System.out.println("Largest = " + max);
}
}
Sample input
34 91 57
Sample run (what you will see)
Enter three numbers: 34 91 57
Largest = 91
14. Positive, negative or zero
An if – else if – else ladder: exactly one branch runs, checked from top to bottom.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n > 0) {
System.out.println("Positive");
} else if (n < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}
Sample input
-12
Sample run (what you will see)
Enter a number: -12
Negative
15. Pass or fail (with validation)
Pass marks are 33 out of 100, as in CBSE. A real program must also reject impossible input like 120 or -5 before deciding pass or fail.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter marks (0-100): ");
int m = sc.nextInt();
if (m < 0 || m > 100) {
System.out.println("Invalid marks");
} else if (m >= 33) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Sample input
41
Sample run (what you will see)
Enter marks (0-100): 41
Pass
16. Grade from percentage
Order matters in a ladder: check 90 first, then 75, then 60. If you start with ">= 33", every student gets the same grade.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter percentage: ");
double p = sc.nextDouble();
char grade;
if (p >= 90) {
grade = 'A';
} else if (p >= 75) {
grade = 'B';
} else if (p >= 60) {
grade = 'C';
} else if (p >= 33) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
Sample input
78.5
Sample run (what you will see)
Enter percentage: 78.5
Grade = B
17. Leap year
Divisible by 4 is not enough: 1900 is not a leap year, 2000 is. The full rule is "divisible by 400, or by 4 but not by 100".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter year: ");
int y = sc.nextInt();
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
System.out.println(y + " is a leap year");
} else {
System.out.println(y + " is not a leap year");
}
}
}
Sample input
1900
Sample run (what you will see)
Enter year: 1900
1900 is not a leap year
18. Vowel or consonant
Converts the letter to lower case first, so A and a are treated alike, and rejects digits or symbols instead of calling them consonants.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a letter: ");
char ch = Character.toLowerCase(sc.next().charAt(0));
if (!Character.isLetter(ch)) {
System.out.println("Not a letter");
} else if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println(ch + " is a vowel");
} else {
System.out.println(ch + " is a consonant");
}
}
}
Sample input
E
Sample run (what you will see)
Enter a letter: E
e is a vowel
19. Divisible by 5 and 11
Both conditions must be true, so they are joined with &&. 55, 110 and 165 pass; 50 does not.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n % 5 == 0 && n % 11 == 0) {
System.out.println(n + " is divisible by both 5 and 11");
} else {
System.out.println(n + " is not divisible by both");
}
}
}
Sample input
165
Sample run (what you will see)
Enter a number: 165
165 is divisible by both 5 and 11
20. Electricity bill with slabs
A real-life ladder. Rates in this example: first 100 units at Rs. 5, next 100 at Rs. 7, the rest at Rs. 10. For 250 units: 500 + 700 + 500 = Rs. 1700.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter units consumed: ");
int u = sc.nextInt();
int bill;
if (u <= 100) {
bill = u * 5;
} else if (u <= 200) {
bill = 100 * 5 + (u - 100) * 7;
} else {
bill = 100 * 5 + 100 * 7 + (u - 200) * 10;
}
System.out.println("Bill = Rs. " + bill);
}
}
Sample input
250
Sample run (what you will see)
Enter units consumed: 250
Bill = Rs. 1700
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 drawn on a notebook page: every new term is the sum of the two before it.
21. Print 1 to N
The simplest for loop. print with a space keeps everything on one line; println would put each number on its own line.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
The loop answer is checked against the formula n(n+1)/2. Printing both is a good habit — if they ever differ, your loop has a bug.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum = sum + i;
}
System.out.println("Sum using loop = " + sum);
System.out.println("Sum using formula = " + n * (n + 1) / 2);
}
}
Sample input
100
Sample run (what you will see)
Enter N: 100
Sum using loop = 5050
Sum using formula = 5050
23. Multiplication table
printf with %2d keeps the columns lined up, so the table looks neat like the one in your maths copy.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %d%n", n, i, n * i);
}
}
}
Sample input
17
Sample run (what you will see)
Enter a number: 17
17 x 1 = 17
17 x 2 = 34
17 x 3 = 51
17 x 4 = 68
17 x 5 = 85
17 x 6 = 102
17 x 7 = 119
17 x 8 = 136
17 x 9 = 153
17 x 10 = 170
24. Even numbers up to N
Start at 2 and jump by 2. This does half the work of checking every number with %.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
for (int i = 2; i <= n; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
Sample input
20
Sample run (what you will see)
Enter N: 20
2 4 6 8 10 12 14 16 18 20
25. Factorial of a number
5! = 5 × 4 × 3 × 2 × 1 = 120. The answer grows very fast, so long is used; even long overflows after 20!.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
System.out.println(n + "! = " + fact);
}
}
Each n = n / 10 removes one digit, so we count how many times we can do it. A do-while is used so that 0 is counted as one digit.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = Math.abs(sc.nextInt());
int count = 0;
do {
count++;
n = n / 10;
} while (n > 0);
System.out.println("Digits = " + count);
}
}
Sample input
90817
Sample run (what you will see)
Enter a number: 90817
Digits = 5
27. Sum of digits
n % 10 picks the last digit, n / 10 drops it. These two lines are the heart of almost every number program in the next section.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = 0;
while (n > 0) {
sum = sum + n % 10;
n = n / 10;
}
System.out.println("Sum of digits = " + sum);
}
}
Sample input
4096
Sample run (what you will see)
Enter a number: 4096
Sum of digits = 19
28. Fibonacci series
Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8 … We keep only two variables and slide them forward.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many terms? ");
int n = sc.nextInt();
long a = 0, b = 1;
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
long next = a + b;
a = b;
b = next;
}
System.out.println();
}
}
Sample input
10
Sample run (what you will see)
How many terms? 10
0 1 1 2 3 5 8 13 21 34
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 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.
Notebook page 1: reverse number and palindrome check, written by hand.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.
A palindrome check is just "reverse the number and compare".153 is an Armstrong number because the cubes of its digits add up to 153.28 is perfect: its proper divisors add up to exactly 28.Divisor pairs of 36 mirror after 6 × 6, so a prime check can stop at √n.
A quick reference before you start:
Number
Rule
Example
Palindrome
same as its reverse
121, 1331
Armstrong
sum of digits ^ (number of digits) = number
153, 9474
Perfect
sum of proper divisors = number
6, 28, 496
Prime
exactly two divisors, 1 and itself
2, 13, 97
Strong
sum of factorials of digits = number
145
Neon
sum of digits of its square = number
9 (81 → 8 + 1)
Automorphic
its square ends with the number
25, 76
Harshad (Niven)
divisible by the sum of its digits
18, 156
Spy
sum of digits = product of digits
22, 1124
29. Reverse a number
rev = rev × 10 + last digit. Every pass moves the old digits one place left and drops the new digit into the units place. The dry run for 123 is in the notebook photo above.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int rev = 0;
while (n > 0) {
int r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
System.out.println("Reversed = " + rev);
}
}
Sample input
123
Sample run (what you will see)
Enter a number: 123
Reversed = 321
30. Palindrome number
A palindrome reads the same both ways: 121, 1331, 7. Save a copy of n before the loop (the variable t), because the loop destroys n. If t equals the reverse, it is a palindrome.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int t = n, rev = 0;
while (n > 0) {
int r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
if (t == rev) {
System.out.println(t + " is a palindrome");
} else {
System.out.println(t + " is not a palindrome");
}
}
}
An Armstrong number equals the sum of its digits, each raised to the number of digits. 153 = 1³ + 5³ + 3³, and 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴. The program first counts digits, so it works for any length, not only three-digit numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int digits = String.valueOf(n).length();
int t = n, sum = 0;
while (t > 0) {
int d = t % 10;
int power = 1;
for (int i = 1; i <= digits; i++) {
power = power * d;
}
sum = sum + power;
t = t / 10;
}
if (sum == n) {
System.out.println(n + " is an Armstrong number");
} else {
System.out.println(n + " is not an Armstrong number");
}
}
}
A perfect number equals the sum of its proper divisors (all divisors except itself). 6 = 1 + 2 + 3 and 28 = 1 + 2 + 4 + 7 + 14. Divisors never exceed n / 2, so the loop stops there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n > 0) {
System.out.println(n + " is a perfect number");
} else {
System.out.println(n + " is not a perfect number (sum of divisors = " + sum + ")");
}
}
}
Sample input
28
Sample run (what you will see)
Enter a number: 28
28 is a perfect number
33. Prime number (correct and fast)
Two fixes over the version most notes show: 0 and 1 are not prime, and we only test divisors while i × i ≤ n. For 1,000,003 that is about 1,000 checks instead of a million.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
boolean prime = n >= 2;
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) {
prime = false;
break;
}
}
System.out.println(n + (prime ? " is prime" : " is not prime"));
}
}
Sample input
1000003
Sample run (what you will see)
Enter a number: 1000003
1000003 is prime
34. All prime numbers from 1 to N
A nested loop: the outer loop picks each number, the inner loop tests it. The boolean flag is reset for every new number — forgetting that is the usual bug.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
int count = 0;
for (int num = 2; num <= n; num++) {
boolean prime = true;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
if (prime) {
System.out.print(num + " ");
count++;
}
}
System.out.println();
System.out.println("Total primes = " + count);
}
}
A strong number equals the sum of the factorials of its digits: 145 = 1! + 4! + 5! = 1 + 24 + 120. Only 1, 2, 145 and 40585 are strong.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int t = n, sum = 0;
while (t > 0) {
int d = t % 10;
int f = 1;
for (int i = 2; i <= d; i++) {
f = f * i;
}
sum = sum + f;
t = t / 10;
}
System.out.println(n + (sum == n ? " is a strong number" : " is not a strong number"));
}
}
Sample input
145
Sample run (what you will see)
Enter a number: 145
145 is a strong number
36. Neon number
Square the number, add the digits of the square; if you get the number back, it is neon. 9² = 81 and 8 + 1 = 9. Only 0, 1 and 9 qualify.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sq = n * n, sum = 0;
while (sq > 0) {
sum = sum + sq % 10;
sq = sq / 10;
}
System.out.println(n + (sum == n ? " is a neon number" : " is not a neon number"));
}
}
Sample input
9
Sample run (what you will see)
Enter a number: 9
9 is a neon number
37. Automorphic number
The square of an automorphic number ends with the number itself: 25² = 625, 76² = 5776. We compare the last d digits of the square, where d is the digit count of n.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
long sq = (long) n * n;
long place = 1;
int t = n;
do {
place = place * 10;
t = t / 10;
} while (t > 0);
if (sq % place == n) {
System.out.println(n + " is automorphic (" + n + "^2 = " + sq + ")");
} else {
System.out.println(n + " is not automorphic (" + n + "^2 = " + sq + ")");
}
}
}
Sample input
76
Sample run (what you will see)
Enter a number: 76
76 is automorphic (76^2 = 5776)
38. Harshad (Niven) number
A Harshad number is divisible by the sum of its own digits. 156: 1 + 5 + 6 = 12 and 156 / 12 = 13 exactly. "Harshad" is Sanskrit for "great joy" — the name was given by the Indian mathematician D. R. Kaprekar.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int t = n, sum = 0;
while (t > 0) {
sum = sum + t % 10;
t = t / 10;
}
if (sum > 0 && n % sum == 0) {
System.out.println(n + " is a Harshad number (" + n + " / " + sum + " = " + (n / sum) + ")");
} else {
System.out.println(n + " is not a Harshad number");
}
}
}
Sample input
156
Sample run (what you will see)
Enter a number: 156
156 is a Harshad number (156 / 12 = 13)
39. Spy number
In a spy number the sum of the digits equals their product. 1124: 1 + 1 + 2 + 4 = 8 and 1 × 1 × 2 × 4 = 8.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int t = n, sum = 0, product = 1;
while (t > 0) {
int d = t % 10;
sum = sum + d;
product = product * d;
t = t / 10;
}
System.out.println("Sum = " + sum + ", Product = " + product);
System.out.println(n + (sum == product ? " is a spy number" : " is not a spy number"));
}
}
Sample input
1124
Sample run (what you will see)
Enter a number: 1124
Sum = 8, Product = 8
1124 is a spy number
40. GCD (HCF) and LCM
Euclid’s method: replace (a, b) with (b, a % b) until b becomes 0; then a is the GCD. LCM follows from a × b = GCD × LCM.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int x = a, y = b;
while (y != 0) {
int r = x % y;
x = y;
y = r;
}
int gcd = x;
long lcm = (long) a * b / gcd;
System.out.println("GCD = " + gcd);
System.out.println("LCM = " + lcm);
}
}
Sample input
36 60
Sample run (what you will see)
Enter two numbers: 36 60
GCD = 12
LCM = 180
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.
The pattern recipe: outer loop for rows, inner loop for columns, and one rule for how many columns row i needs.
41. Square of stars
Outer loop = rows, inner loop = columns. Every pattern on this page is just a different rule for "how many columns in row i".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
* * * *
* * * *
* * * *
* * * *
42. Right triangle of stars
Row i has i stars, so the inner loop runs j from 1 to i. See the hand-drawn grid above.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
*
* *
* * *
* * * *
43. Inverted right triangle
Run the outer loop backwards: row i still has i stars, but i starts at n and goes down to 1.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
* * * *
* * *
* *
*
44. Number triangle (1 12 123)
Same shape as the star triangle, but we print j instead of a star.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
1
1 2
1 2 3
1 2 3 4
45. Floyd's triangle
A counter keeps running across rows, so the numbers never restart. The full lesson is linked below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
int k = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%-3d", k);
k++;
}
System.out.println();
}
}
}
Two inner loops per row: first print n − i spaces, then i stars.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
*
* *
* * *
* * * *
47. Pyramid of stars
Like the right-aligned triangle, but each space is a single character, so the stars settle in the middle.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Sample input
5
Sample run (what you will see)
Enter rows: 5
*
* *
* * *
* * * *
* * * * *
48. Alphabet triangle
A char can be added to an int: (char) ('A' + j) gives A, B, C … This is the same trick used to build roll-number prefixes.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print((char) ('A' + j) + " ");
}
System.out.println();
}
}
}
Sample input
5
Sample run (what you will see)
Enter rows: 5
A
A B
A B C
A B C D
A B C D E
49. Diamond pattern
A pyramid followed by an upside-down pyramid with one row fewer. Draw it on paper first and count the spaces in each row.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) System.out.print(" ");
for (int j = 1; j <= i; j++) System.out.print("* ");
System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
for (int s = 1; s <= n - i; s++) System.out.print(" ");
for (int j = 1; j <= i; j++) System.out.print("* ");
System.out.println();
}
}
}
Sample input
4
Sample run (what you will see)
Enter rows: 4
*
* *
* * *
* * * *
* * *
* *
*
50. Hollow square
Print a star only on the border: first row, last row, first column or last column. Everything else is a space.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows: ");
int n = sc.nextInt();
System.out.println();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Sample input
5
Sample run (what you will see)
Enter rows: 5
* * * * *
* *
* *
* *
* * * * *
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.
51. Sum of array elements
Input format for every array program: first the count, then the elements on the next line, separated by spaces.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + a[i];
}
System.out.println("Sum = " + sum);
}
}
Sample input
5
12 7 30 18 3
Sample run (what you will see)
How many elements? 5
Enter 5 elements: 12 7 30 18 3
Sum = 70
Start with max = a[0], never with max = 0 — an array of all negative numbers would otherwise report 0 as the largest.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > max) {
max = a[i];
}
}
System.out.println("Largest = " + max);
}
}
Sample input
5
-8 -3 -15 -1 -9
Sample run (what you will see)
How many elements? 5
Enter 5 elements: -8 -3 -15 -1 -9
Largest = -1
53. Smallest element in an array
The mirror image of the previous program: only the comparison sign flips.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int min = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < min) {
min = a[i];
}
}
System.out.println("Smallest = " + min);
}
}
Sample input
6
45 12 78 9 33 21
Sample run (what you will see)
How many elements? 6
Enter 6 elements: 45 12 78 9 33 21
Smallest = 9
54. Average of array elements
Cast the sum to double before dividing, otherwise the decimal part is lost.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + a[i];
}
System.out.printf("Average = %.2f%n", (double) sum / n);
}
}
Sample input
4
78 85 91 66
Sample run (what you will see)
How many elements? 4
Enter 4 elements: 78 85 91 66
Average = 80.00
55. Reverse an array in place
Swap the first with the last, the second with the second-last, and stop at the middle. No second array is needed.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - 1 - i];
a[n - 1 - i] = temp;
}
System.out.print("Reversed: ");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
Sample input
5
1 2 3 4 5
Sample run (what you will see)
How many elements? 5
Enter 5 elements: 1 2 3 4 5
Reversed: 5 4 3 2 1
56. Count even and odd elements
One loop, two counters. The odd count is simply n minus the even count.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int even = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
even++;
}
}
System.out.println("Even = " + even + ", Odd = " + (n - even));
}
}
Sample input
7
4 9 12 15 22 31 40
Sample run (what you will see)
How many elements? 7
Enter 7 elements: 4 9 12 15 22 31 40
Even = 4, Odd = 3
57. Linear search (first position)
Stops at the first match with break and reports a 1-based position, the way a person would count. Without break, a repeated value would report its last position.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.print("Enter value to search: ");
int key = sc.nextInt();
int pos = -1;
for (int i = 0; i < n; i++) {
if (a[i] == key) {
pos = i + 1;
break;
}
}
if (pos == -1) {
System.out.println(key + " not found");
} else {
System.out.println(key + " found at position " + pos);
}
}
}
Sample input
6
14 8 23 8 51 30
8
Sample run (what you will see)
How many elements? 6
Enter 6 elements: 14 8 23 8 51 30
Enter value to search: 8
8 found at position 2
One pass with two variables. A duplicate of the largest value is ignored, so for 40 40 25 the answer is 25, not 40.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (a[i] > first) {
second = first;
first = a[i];
} else if (a[i] > second && a[i] != first) {
second = a[i];
}
}
if (second == Integer.MIN_VALUE) {
System.out.println("No second largest element");
} else {
System.out.println("Second largest = " + second);
}
}
}
Sample input
6
40 12 40 25 7 19
Sample run (what you will see)
How many elements? 6
Enter 6 elements: 40 12 40 25 7 19
Second largest = 25
Three counters and an if – else if – else ladder inside the loop. Zero is neither positive nor negative, so it gets its own counter.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many elements? ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int pos = 0, neg = 0, zero = 0;
for (int i = 0; i < n; i++) {
if (a[i] > 0) {
pos++;
} else if (a[i] < 0) {
neg++;
} else {
zero++;
}
}
System.out.println("Positive = " + pos + ", Negative = " + neg + ", Zero = " + zero);
}
}
Sample input
8
5 -3 0 12 -7 0 9 -1
Sample run (what you will see)
How many elements? 8
Enter 8 elements: 5 -3 0 12 -7 0 9 -1
Positive = 3, Negative = 3, Zero = 2
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:
Term
Meaning in one line
See program
Class
A blueprint that describes what its objects know and do.
61 — Student
Object
A 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 method
A function inside the class that works on the object's data.
61 — display()
Constructor
Special method with the class name; runs once when new creates the object.
62 — Rectangle(l, b)
Dot operator
Reaches a member of one particular object.
s1.marks, r1.area()
private
Hides a data member from code outside the class.
63 — balance
static member
One copy shared by the whole class, not one per object.
64 — count
this
Means "the current object"; separates a field from a parameter with the same name.
63, 64, 66
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.
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.
b = a makes two arrows to the same object. Only another new gives you a real second object.
61. Class and object: Student
The Student class has three data members (roll, name, marks) and two member methods (display and result). In main we create one object with new and fill its data members through the dot operator. The first OOP diagram above shows exactly this.
import java.util.Scanner;
class Student {
int roll;
String name;
int marks;
void display() {
System.out.println("Roll: " + roll + ", Name: " + name + ", Marks: " + marks);
}
String result() {
return marks >= 33 ? "Pass" : "Fail";
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student s1 = new Student();
System.out.print("Enter roll, name and marks: ");
s1.roll = sc.nextInt();
s1.name = sc.next();
s1.marks = sc.nextInt();
s1.display();
System.out.println("Result: " + s1.result());
}
}
Sample input
101 Aman 78
Sample run (what you will see)
Enter roll, name and marks: 101 Aman 78
Roll: 101, Name: Aman, Marks: 78
Result: Pass
A constructor fills the data members at the moment the object is born, so no object is ever left half-filled. Two objects of the same class keep separate copies of length and breadth, which is why r1.area() and r2.area() give different answers.
import java.util.Scanner;
class Rectangle {
double length;
double breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
}
double area() {
return length * breadth;
}
double perimeter() {
return 2 * (length + breadth);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Rectangle 1 (length breadth): ");
Rectangle r1 = new Rectangle(sc.nextDouble(), sc.nextDouble());
System.out.print("Rectangle 2 (length breadth): ");
Rectangle r2 = new Rectangle(sc.nextDouble(), sc.nextDouble());
System.out.println("r1: area = " + r1.area() + ", perimeter = " + r1.perimeter());
System.out.println("r2: area = " + r2.area() + ", perimeter = " + r2.perimeter());
if (r1.area() > r2.area()) {
System.out.println("r1 is bigger");
} else if (r2.area() > r1.area()) {
System.out.println("r2 is bigger");
} else {
System.out.println("Both have the same area");
}
}
}
Sample input
12 5
8 9
Sample run (what you will see)
Rectangle 1 (length breadth): 12 5
Rectangle 2 (length breadth): 8 9
r1: area = 60.0, perimeter = 34.0
r2: area = 72.0, perimeter = 34.0
r2 is bigger
balance is private, so code outside the class cannot write account.balance = 1000000. The only way in is through deposit and withdraw, and those methods refuse bad requests. That protection is what encapsulation means.
import java.util.Scanner;
class BankAccount {
private String holder;
private int balance;
BankAccount(String holder, int opening) {
this.holder = holder;
this.balance = opening;
}
void deposit(int amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Deposited " + amount);
} else {
System.out.println("Deposit must be positive");
}
}
void withdraw(int amount) {
if (amount > balance) {
System.out.println("Cannot withdraw " + amount + ": insufficient balance");
} else {
balance = balance - amount;
System.out.println("Withdrew " + amount);
}
}
int getBalance() {
return balance;
}
String getHolder() {
return holder;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Account holder: ");
String name = sc.next();
System.out.print("Opening balance: ");
BankAccount acc = new BankAccount(name, sc.nextInt());
System.out.print("Amount to deposit: ");
acc.deposit(sc.nextInt());
System.out.print("Amount to withdraw: ");
acc.withdraw(sc.nextInt());
System.out.println(acc.getHolder() + "'s balance = " + acc.getBalance());
}
}
name and id belong to each object, but count is static, so there is only one copy shared by the whole class. Every constructor call increases that single counter, and each visitor takes the next id from it.
import java.util.Scanner;
class Visitor {
static int count = 0;
int id;
String name;
Visitor(String name) {
this.name = name;
count++;
id = count;
}
void show() {
System.out.println("Visitor #" + id + ": " + name);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many visitors? ");
int n = sc.nextInt();
Visitor[] list = new Visitor[n];
System.out.print("Enter " + n + " names: ");
for (int i = 0; i < n; i++) {
list[i] = new Visitor(sc.next());
}
for (int i = 0; i < n; i++) {
list[i].show();
}
System.out.println("Total objects created = " + Visitor.count);
}
}
Sample input
3
Aman Priya Rahul
Sample run (what you will see)
How many visitors? 3
Enter 3 names: Aman Priya Rahul
Visitor #1: Aman
Visitor #2: Priya
Visitor #3: Rahul
Total objects created = 3
Book[] books = new Book[n] creates n empty references, not n books. Each books[i] = new Book() is what actually builds an object; skipping it gives a NullPointerException.
import java.util.Scanner;
class Book {
String title;
int price;
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many books? ");
int n = sc.nextInt();
Book[] books = new Book[n];
for (int i = 0; i < n; i++) {
System.out.print("Title and price of book " + (i + 1) + ": ");
books[i] = new Book();
books[i].title = sc.next();
books[i].price = sc.nextInt();
}
Book costliest = books[0];
for (int i = 1; i < n; i++) {
if (books[i].price > costliest.price) {
costliest = books[i];
}
}
System.out.println("Costliest book: " + costliest.title + " (Rs. " + costliest.price + ")");
}
}
Sample input
3
Java 450
Python 380
DBMS 520
Sample run (what you will see)
How many books? 3
Title and price of book 1: Java 450
Title and price of book 2: Python 380
Title and price of book 3: DBMS 520
Costliest book: DBMS (Rs. 520)
66. Passing and returning an object: Distance
d1.add(d2) runs add on d1 and receives d2 as a parameter, so inside the method feet means d1.feet and d.feet means d2.feet. The method builds and returns a brand-new Distance, carrying every 12 inches over into a foot.
import java.util.Scanner;
class Distance {
int feet;
int inches;
Distance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
Distance add(Distance d) {
int f = feet + d.feet;
int i = inches + d.inches;
f = f + i / 12;
i = i % 12;
return new Distance(f, i);
}
void show() {
System.out.println(feet + " ft " + inches + " in");
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("First distance (feet inches): ");
Distance d1 = new Distance(sc.nextInt(), sc.nextInt());
System.out.print("Second distance (feet inches): ");
Distance d2 = new Distance(sc.nextInt(), sc.nextInt());
Distance total = d1.add(d2);
System.out.print("Total = ");
total.show();
}
}
Sample input
5 9
3 8
Sample run (what you will see)
First distance (feet inches): 5 9
Second distance (feet inches): 3 8
Total = 9 ft 5 in
67. Reference vs copy of an object
b = a does not copy the object; it copies the address, so a and b now point at the same box and changing b.value changes a.value too. A real copy needs a second new. This is the second OOP diagram above.
import java.util.Scanner;
class Box {
int value;
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a value: ");
Box a = new Box();
a.value = sc.nextInt();
Box b = a;
b.value = 99;
System.out.println("After b = a and b.value = 99 -> a.value = " + a.value);
Box c = new Box();
c.value = a.value;
c.value = 5;
System.out.println("After a real copy c and c.value = 5 -> a.value = " + a.value);
}
}
Sample input
10
Sample run (what you will see)
Enter a value: 10
After b = a and b.value = 99 -> a.value = 99
After a real copy c and c.value = 5 -> a.value = 99
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.