Java Practice Programs and Logic
For final-year students - basic to exam-ready examples
How to use this PDF: First understand the logic, then write the code without looking, then dry-run with sample input. In
exams, neat logic is the backbone; syntax is only the dress.
1. Java exam basics
Basic structure: A Java program usually has a class, a main method, statements inside the main method, and
semicolons after most statements.
public class Main {
public static void main(String[] args) {
// code starts here
}
}
Common data types: int for whole numbers, double for decimal values, char for one character, boolean for true/false,
String for text.
Input class: Use Scanner for reading input. Import it using import [Link];.
Scanner sc = new Scanner([Link]);
int n = [Link]();
String name = [Link]();
2. Logic patterns to remember
Pattern Use it for Core idea
Loop Counting, tables, sums Repeat statements while condition is true
If-else Decision making Choose one path based on condition
Array Many values Store values with index from 0
String Text problems Use length(), charAt(), equals()
Method Reusable logic Write once, call many times
Class/Object OOP questions Class is blueprint, object is real item
3. Basic Java programs
Program 1: Hello World
Logic: Create a class and print a message using [Link]().
public class Main {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
Sample output:
Hello, Java!
Java Practice Programs and Logic Page 1
Program 2: Add two numbers
Logic: Read two integers, add them, and print the result.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int sum = a + b;
[Link]("Sum = " + sum);
}
}
Sample output:
Input: 10 20
Sum = 30
Program 3: Check even or odd
Logic: A number is even when it is exactly divisible by 2. Use n % 2 == 0.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
if (n % 2 == 0)
[Link]("Even");
else
[Link]("Odd");
}
}
Sample output:
Input: 7
Odd
Program 4: Largest of three numbers
Logic: Compare a with b and c. If not, compare b with c. Otherwise c is largest.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a = [Link](), b = [Link](), c = [Link]();
if (a >= b && a >= c)
[Link](a + " is largest");
else if (b >= a && b >= c)
[Link](b + " is largest");
else
[Link](c + " is largest");
}
}
Sample output:
Input: 12 8 25
25 is largest
Java Practice Programs and Logic Page 2
Program 5: Multiplication table
Logic: Use a loop from 1 to 10 and multiply n with the loop variable.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i));
}
}
}
Sample output:
Input: 5
5 x 1 = 5
...
5 x 10 = 50
Program 6: Factorial of a number
Logic: Factorial means n x (n-1) x ... x 1. Start result as 1 and multiply in a loop.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
long fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
[Link]("Factorial = " + fact);
}
}
Sample output:
Input: 5
Factorial = 120
Program 7: Fibonacci series
Logic: First two values are 0 and 1. Next value is the sum of previous two values.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int a = 0, b = 1;
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
Sample output:
Input: 7
0 1 1 2 3 5 8
Java Practice Programs and Logic Page 3
Program 8: Prime number
Logic: A prime number has only two factors: 1 and itself. Check divisibility from 2 to n/2.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
boolean prime = true;
if (n <= 1) prime = false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
prime = false;
break;
}
}
if (prime) [Link]("Prime");
else [Link]("Not Prime");
}
}
Sample output:
Input: 13
Prime
Program 9: Reverse a number
Logic: Take last digit using n % 10, add it to reverse, then remove last digit using n / 10.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int rev = 0;
while (n > 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n = n / 10;
}
[Link]("Reverse = " + rev);
}
}
Sample output:
Input: 1234
Reverse = 4321
Program 10: Palindrome number
Logic: Reverse the number and compare it with original value.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int original = n, rev = 0;
while (n > 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n = n / 10;
}
if (original == rev) [Link]("Palindrome");
else [Link]("Not Palindrome");
}
}
Sample output:
Input: 121
Palindrome
Java Practice Programs and Logic Page 4
Program 11: Armstrong number
Logic: For a 3-digit number, cube each digit and add. If sum equals original, it is Armstrong.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int original = n, sum = 0;
while (n > 0) {
int digit = n % 10;
sum = sum + digit * digit * digit;
n = n / 10;
}
if (sum == original) [Link]("Armstrong");
else [Link]("Not Armstrong");
}
}
Sample output:
Input: 153
Armstrong
Program 12: Swap two numbers without third variable
Logic: Use arithmetic operations: a = a + b, b = a - b, a = a - b.
public class Main {
public static void main(String[] args) {
int a = 10, b = 20;
a = a + b;
b = a - b;
a = a - b;
[Link]("a = " + a + ", b = " + b);
}
}
Sample output:
a = 20, b = 10
4. Array programs
Program 13: Sum of array elements
Logic: Read array size, store elements, and add each element to sum.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
sum = sum + arr[i];
}
[Link]("Sum = " + sum);
}
}
Sample output:
Input: 5
10 20 30 40 50
Sum = 150
Java Practice Programs and Logic Page 5
Program 14: Find maximum in array
Logic: Assume first element is max. Compare all other elements and update max when bigger value is found.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = [Link]();
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
}
[Link]("Maximum = " + max);
}
}
Sample output:
Input: 5
4 9 2 15 7
Maximum = 15
Program 15: Linear search
Logic: Check each element one by one. If key matches, print position and stop.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = [Link]();
int key = [Link]();
int pos = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
pos = i;
break;
}
}
if (pos == -1) [Link]("Not found");
else [Link]("Found at index " + pos);
}
}
Sample output:
Input: 5
3 6 8 10 15
10
Found at index 3
Java Practice Programs and Logic Page 6
Program 16: Bubble sort
Logic: Compare adjacent values. If left value is greater, swap. Repeat passes until array is sorted.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = [Link]();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int x : arr) [Link](x + " ");
}
}
Sample output:
Input: 5
5 1 4 2 8
1 2 4 5 8
5. String programs
Program 17: Reverse a string
Logic: Start from last character and move to first character using charAt().
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev = rev + [Link](i);
}
[Link]("Reverse = " + rev);
}
}
Sample output:
Input: java
Reverse = avaj
Program 18: Palindrome string
Logic: Reverse the string and compare using equalsIgnoreCase().
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev = rev + [Link](i);
}
if ([Link](rev)) [Link]("Palindrome");
else [Link]("Not Palindrome");
}
}
Sample output:
Input: madam
Palindrome
Java Practice Programs and Logic Page 7
Program 19: Count vowels in a string
Logic: Convert character to lowercase and check whether it is a, e, i, o, or u.
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
int count = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link]([Link](i));
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
[Link]("Vowels = " + count);
}
}
Sample output:
Input: Education
Vowels = 5
6. Matrix and methods
Program 20: Add two 2x2 matrices
Logic: Use nested loops. Add elements at the same row and column.
public class Main {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][j] + b[i][j];
[Link](c[i][j] + " ");
}
[Link]();
}
}
}
Sample output:
6 8
10 12
Program 21: Method to find square
Logic: Create a static method. Pass a number and return number multiplied by itself.
public class Main {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int result = square(6);
[Link]("Square = " + result);
}
}
Sample output:
Square = 36
7. OOP programs
Java Practice Programs and Logic Page 8
Program 22: Class and object
Logic: A class is a blueprint. An object uses that blueprint to store real values.
class Student {
int rollNo;
String name;
void display() {
[Link](rollNo + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 101;
[Link] = "Ravi";
[Link]();
}
}
Sample output:
101 Ravi
Program 23: Constructor
Logic: A constructor runs automatically when object is created. It is used to initialize values.
class Student {
int rollNo;
String name;
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
[Link](rollNo + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(102, "Anu");
[Link]();
}
}
Sample output:
102 Anu
Java Practice Programs and Logic Page 9
Program 24: Inheritance
Logic: Child class can use properties and methods of parent class using extends keyword.
class Animal {
void eat() {
[Link]("Eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Sample output:
Eating
Barking
Program 25: Method overriding
Logic: Child class gives its own version of a parent class method.
class Bank {
int rateOfInterest() {
return 5;
}
}
class SBI extends Bank {
int rateOfInterest() {
return 7;
}
}
public class Main {
public static void main(String[] args) {
SBI obj = new SBI();
[Link]("Rate = " + [Link]());
}
}
Sample output:
Rate = 7
Program 26: Interface
Logic: Interface contains abstract behavior. A class implements it and provides method body.
interface Printable {
void print();
}
class Document implements Printable {
public void print() {
[Link]("Printing document");
}
}
public class Main {
public static void main(String[] args) {
Document d = new Document();
[Link]();
}
}
Sample output:
Printing document
Java Practice Programs and Logic Page 10
8. Exception and file handling
Program 27: Exception handling
Logic: Use try-catch to handle runtime errors and keep the program alive.
public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0;
[Link](a);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
Sample output:
Cannot divide by zero
Program 28: Write text to a file
Logic: Use FileWriter to create or write text into a file. Close the file after writing.
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Java practice file");
[Link]();
[Link]("File written successfully");
} catch (IOException e) {
[Link]("File error");
}
}
}
Sample output:
File written successfully
9. Quick exam preparation tips
1. Read the question twice. Identify input, process, and output.
2. For number programs, remember digit extraction: digit = n % 10 and n = n / 10.
3. For array programs, start loops from 0 and use i < n.
4. For string programs, use length(), charAt(), equals(), and equalsIgnoreCase().
5. For OOP questions, write small class names and simple method names. Clean structure earns marks.
6. Practice dry run. A program without dry run is like a road without signboards.
10. Practice questions
1. Check whether a year is leap year
2. Find sum of digits of a number
3. Count digits in a number
4. Print prime numbers from 1 to n
5. Find second largest element in an array
6. Remove duplicate elements from array
7. Count words in a sentence
Java Practice Programs and Logic Page 11
8. Check anagram strings
9. Create Employee class with salary calculation
10. Demonstrate abstract class with one abstract method
Java Practice Programs and Logic Page 12