1. Basic Programs (Input, Output, Loops)
Q1. Write a program to check if a number is even or odd.
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // For input
System.out.print("Enter a number: ");
int num = sc.nextInt(); // Read number from user
if(num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}
Flow:
Input a number → Check num % 2 → Print result.
Output:
Enter a number: 5
5 is odd
2. OOPS Concepts – Classes, Objects, Methods
Q2. Program to demonstrate Class & Object
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving");
}
void displayColor() {
System.out.println("Color is: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.drive(); // Method call
myCar.displayColor(); // Method call
}
}
Output:
Car is driving
Color is: Red
Flow:
Create class Car → Create object in main → Call methods
3. Constructor Overloading
Q3. Program to demonstrate constructor overloading
class Student {
String name;
int age;
Student() {
name = "Default";
age = 18;
}
Student(String n, int a) {
name = n;
age = a;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Calls default constructor
Student s2 = new Student("Raj", 20); // Calls parameterized constructor
s1.show();
s2.show();
}
}
Output:
Name: Default, Age: 18
Name: Raj, Age: 20
4. Inheritance and Polymorphism
Q4. Program to demonstrate method overriding
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog's sound() method
}
}
Output:
Dog barks
Flow:
Dog overrides sound() → Object is of Dog → Dog's method is called
5. Encapsulation
Q5. Program with getter and setter
class Employee {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Ajay");
System.out.println("Name: " + e.getName());
}
}
Output:
Name: Ajay
6. Abstraction
Q6. Abstract class example
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
public class Test {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}
Output:
Drawing Circle
7. Interface
Q7. Interface implementation
interface Bank {
double rateOfInterest();
}
class SBI implements Bank {
public double rateOfInterest() {
return 7.0;
}
}
public class Test {
public static void main(String[] args) {
Bank b = new SBI();
System.out.println("ROI: " + b.rateOfInterest());
}
}
Output:
ROI: 7.0
8. Exception Handling
Q8. Try-catch-finally example
public class Test {
public static void main(String[] args) {
try {
int a = 10 / 0; // Throws exception
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
Output:
Error: / by zero
Finally block executed
9. String Programs
Q9. Reverse a string
public class ReverseString {
public static void main(String[] args) {
String s = "Java";
String rev = "";
for(int i = s.length() - 1; i >= 0; i--) {
rev += s.charAt(i);
}
System.out.println("Reversed: " + rev);
}
}
Output:
Reversed: avaJ
10. Collections (ArrayList)
Q10. Add elements to ArrayList
import java.util.*;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Mango");
for(String fruit : list) {
System.out.println(fruit);
}
}
}
Output:
Apple
Banana
Mango
11. Multithreading (Thread)
Q11. Thread example using Runnable
class MyThread implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}
public class Test {
public static void main(String[] args) {
MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start();
}
}
Output:
Thread is running...
12. File Handling
Q12. Write to file
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("test.txt");
writer.write("Hello Java!");
writer.close();
System.out.println("File written successfully");
} catch(IOException e) {
e.printStackTrace();
}
}
}
13. Swapping Two Numbers Without Temporary Variable
public class SwapNumbers {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swap: a = " + a + ", b = " + b);
a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Flow:
Add both → Store in one variable → Subtract step-by-step.
Output:
Before Swap: a = 10, b = 20
After Swap: a = 20, b = 10
14. Check if a String is Palindrome
public class PalindromeCheck {
public static void main(String[] args) {
String original = "madam";
String reverse = "";
for(int i = original.length()-1; i >= 0; i--) {
reverse += original.charAt(i);
}
if(original.equals(reverse)) {
System.out.println(original + " is a Palindrome");
} else {
System.out.println(original + " is not a Palindrome");
}
}
}
Flow:
Reverse the string → Compare with original.
Output:
madam is a Palindrome
15. Factorial using Recursion
public class FactorialRec {
static int factorial(int n) {
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args) {
int num = 5;
System.out.println("Factorial of " + num + " is " + factorial(num));
}
}
Flow:
Recursive call until n == 1.
Output:
Factorial of 5 is 120
16. Armstrong Number (3-digit)
public class Armstrong {
public static void main(String[] args) {
int num = 153, sum = 0, temp = num;
while(num != 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if(sum == temp) {
System.out.println(temp + " is an Armstrong number");
} else {
System.out.println(temp + " is not an Armstrong number");
}
}
}
Flow:
Extract each digit → Cube it → Add → Compare with original.
Output:
153 is an Armstrong number
---
17. Check Prime Number
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Flow:
Divide by all numbers from 2 to n/2.
Output:
29 is a Prime Number
18. Find Duplicate Characters in a String
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
char[] chars = str.toCharArray();
System.out.println("Duplicate characters:");
for(int i = 0; i < chars.length; i++) {
for(int j = i+1; j < chars.length; j++) {
if(chars[i] == chars[j]) {
System.out.println(chars[i]);
break;
}
}
}
}
}
Flow:
Compare every char with the rest.
Output:
Duplicate characters:
r
g
m
19. Java 8 – Stream API Filter Example
import java.util.*;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 10, 15, 20, 25, 30);
List<Integer> result = numbers.stream()
.filter(n -> n > 15)
.collect(Collectors.toList());
System.out.println(result);
}
}
Flow:
Stream → Filter → Collect → Print.
Output:
[20, 25, 30]
20. Lambda Expression Example
interface Operation {
int operate(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
Operation add = (a, b) -> a + b;
Operation mul = (a, b) -> a * b;
System.out.println("Add: " + add.operate(10, 20));
System.out.println("Multiply: " + mul.operate(10, 20));
}
}
Flow:
Use lambda instead of anonymous class.
Output:
Add: 30
Multiply: 200
21. Sorting Array in Ascending Order
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
Arrays.sort(arr);
System.out.print("Sorted Array: ");
for(int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
Sorted Array: 1 2 3 5 8
22. Count Vowels and Consonants in a String
public class VowelConsonant {
public static void main(String[] args) {
String str = "Hello World";
int vowels = 0, consonants = 0;
str = str.toLowerCase();
for(char ch : str.toCharArray()) {
if(ch >= 'a' && ch <= 'z') {
if("aeiou".indexOf(ch) != -1)
vowels++;
else
consonants++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Output:
Vowels: 3
Consonants: 7
Output:
File written successfully
23. Reverse a String (Using StringBuilder)
public class ReverseStringBuilder {
public static void main(String[] args) {
String str = "JavaDeveloper";
StringBuilder sb = new StringBuilder(str);
sb.reverse(); // Reverses in-place
System.out.println("Reversed: " + sb);
}
}
Flow:
StringBuilder is mutable → use reverse() method
Output:
Reversed: repoleveDavaJ
24. Reverse a Number
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234, rev = 0;
while(num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + rev);
}
}
Output:
Reversed Number: 4321
25. Java Collections – ArrayList Example
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out.println("Languages: " + list);
}
}
Output:
Languages: [Java, Python, C++]
26. Java Collections – HashSet (No duplicates)
import java.util.*;
public class HashSetExample {
public static void main(String[] args) {
Set<String> names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Duplicate
System.out.println("Names: " + names);
}
}
Output:
Names: [Bob, Alice] // order may vary (no duplicates)
27. Java Collections – HashMap Example (Key-Value Pairs)
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(101, "John");
map.put(102, "Alice");
map.put(103, "Bob");
for(Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Output:
ID: 101, Name: John
ID: 102, Name: Alice
ID: 103, Name: Bob
28. Stream API – Print Even Numbers
import java.util.*;
import java.util.stream.*;
public class StreamEven {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}
Output:
2
4
6
8
29. Stream API – Sum of List Elements
import java.util.*;
import java.util.stream.*;
public class StreamSum {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().mapToInt(i -> i).sum();
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 15
30. Stream API – Convert List of Strings to Uppercase
import java.util.*;
import java.util.stream.*;
public class StreamUpperCase {
public static void main(String[] args) {
List<String> names = Arrays.asList("java", "python", "spring");
List<String> upper = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper);
}
}
Output:
[JAVA, PYTHON, SPRING]
31. Lambda Expression – Comparator to Sort by Length
import java.util.*;
public class LambdaSort {
public static void main(String[] args) {
List<String> list = Arrays.asList("Banana", "Apple", "Cherry");
// Sort by length using lambda
list.sort((a, b) -> a.length() - b.length());
System.out.println("Sorted by length: " + list);
}
}
Output:
Sorted by length: [Apple, Banana, Cherry]
32. Functional Interface Example
@FunctionalInterface
interface Greetable {
void greet(String name);
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
Greetable g = (name) -> System.out.println("Hello, " + name + "!");
g.greet("Ravi");
}
}
Output:
Hello, Ravi!
1. Check if Two Strings Are Anagrams
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
if(Arrays.equals(a1, a2)) {
System.out.println("Anagram");
} else {
System.out.println("Not Anagram");
}
}
}
Output:
Anagram
2. Left Rotate an Array by 1
public class LeftRotate {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int first = arr[0];
for(int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = first;
for(int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
2 3 4 5 1
3. Print Pascal’s Triangle
public class PascalsTriangle {
public static void main(String[] args) {
int rows = 5;
for(int i = 0; i < rows; i++) {
int num = 1;
for(int j = 0; j <= i; j++) {
System.out.print(num + " ");
num = num * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
4. Find First Non-Repeated Character in a String
public class FirstUniqueChar {
public static void main(String[] args) {
String str = "aabbcde";
for (char c : str.toCharArray()) {
if (str.indexOf(c) == str.lastIndexOf(c)) {
System.out.println("First non-repeating: " + c);
break;
}
}
}
}
Output:
First non-repeating: c
5. Reverse Each Word in a Sentence
public class ReverseWords {
public static void main(String[] args) {
String str = "Java is fun";
String[] words = str.split(" ");
for(String word : words) {
StringBuilder rev = new StringBuilder(word);
System.out.print(rev.reverse() + " ");
}
}
}
Output:
avaJ si nuf
6. Count Words in a Sentence
public class WordCount {
public static void main(String[] args) {
String sentence = "Java is a popular language";
String[] words = sentence.trim().split("\\s+");
System.out.println("Word count: " + words.length);
}
}
Output:
Word count: 5
7. Static Block Execution Before Main
public class StaticDemo {
static {
System.out.println("Static block called before main");
}
public static void main(String[] args) {
System.out.println("Main method");
}
}
Output:
Static block called before main
Main method
8. Count Set Bits (1s) in a Binary Number
public class CountSetBits {
public static void main(String[] args) {
int num = 13; // Binary = 1101
int count = 0;
while(num > 0) {
count += num & 1;
num >>= 1;
}
System.out.println("Set Bits: " + count);
}
}
Output:
Set Bits: 3
9. Compare Two Objects Using .equals() and ==
public class ObjectCompare {
public static void main(String[] args) {
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false (reference)
System.out.println(a.equals(b)); // true (content)
}
}
Output:
false
true
10. Find Missing Number in Array 1 to N
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6}; // Missing 3
int n = 6;
int total = n * (n + 1) / 2;
int sum = 0;
for(int num : arr) sum += num;
System.out.println("Missing number: " + (total - sum));
}
}
Output:
Missing number: 3
11. Find Duplicate Elements in Array
import java.util.*;
public class DuplicateElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 1};
Set<Integer> seen = new HashSet<>();
Set<Integer> dup = new HashSet<>();
for(int num : arr) {
if(!seen.add(num)) {
dup.add(num);
}
}
System.out.println("Duplicates: " + dup);
}
}
Output:
Duplicates: [1, 2]
1. Check if a Number is a Power of Two
public class PowerOfTwo {
public static void main(String[] args) {
int num = 16;
if ((num & (num - 1)) == 0 && num != 0)
System.out.println(num + " is a power of 2");
else
System.out.println(num + " is not a power of 2");
}
}
Output:
16 is a power of 2
Logic: A power of 2 has only one set bit in binary.
2. Check Armstrong Number for Any Digits
public class ArmstrongAnyDigit {
public static void main(String[] args) {
int num = 9474, temp = num, sum = 0;
int digits = String.valueOf(num).length();
while(temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
}
System.out.println(num + (sum == num ? " is " : " is not ") + "an Armstrong number");
}
}
Output:
9474 is an Armstrong number
3. Swap Two Strings Without Using Third Variable
public class SwapStrings {
public static void main(String[] args) {
String a = "Hello";
String b = "World";
System.out.println("Before Swap: a = " + a + ", b = " + b);
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length());
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Output:
Before Swap: a = Hello, b = World
After Swap: a = World, b = Hello
4. Find the Second Largest Number in an Array
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {10, 25, 60, 12, 45};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
System.out.println("Second Largest: " + second);
}
}
Output:
Second Largest: 45
5. Sum of Digits Until a Single Digit (Digital Root)
public class DigitalRoot {
public static void main(String[] args) {
int num = 9875;
while(num > 9) {
int sum = 0;
while(num != 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
System.out.println("Digital Root: " + num);
}
}
Output:
Digital Root: 2
6. Check if All Characters in a String Are Unique
public class UniqueCharacters {
public static void main(String[] args) {
String str = "abcdef";
boolean[] seen = new boolean[128]; // ASCII chars
boolean unique = true;
for (char ch : str.toCharArray()) {
if (seen[ch]) {
unique = false;
break;
}
seen[ch] = true;
}
System.out.println(unique ? "All characters are unique" : "Duplicates found");
}
}
Output:
All characters are unique
7. Count Vowels, Consonants, Digits and Special Characters
public class CharTypesCounter {
public static void main(String[] args) {
String str = "Java@123#";
int vowels = 0, consonants = 0, digits = 0, specials = 0;
for(char ch : str.toCharArray()) {
if(Character.isDigit(ch)) digits++;
else if(Character.isLetter(ch)) {
ch = Character.toLowerCase(ch);
if("aeiou".indexOf(ch) != -1) vowels++;
else consonants++;
} else specials++;
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("Special characters: " + specials);
}
}
Output:
Vowels: 2
Consonants: 2
Digits: 3
Special characters: 2
8. Check Whether a String Contains Only Digits
public class OnlyDigits {
public static void main(String[] args) {
String s = "12345a";
if (s.matches("\\d+")) {
System.out.println("Only digits");
} else {
System.out.println("Contains non-digit characters");
}
}
}
Output:
Contains non-digit characters
9. Create Pyramid Pattern
public class PyramidPattern {
public static void main(String[] args) {
int n = 5;
for(int i = 1; i <= n; i++) {
for(int space = 1; space <= n-i; space++)
System.out.print(" ");
for(int j = 1; j <= 2*i-1; j++)
System.out.print("*");
System.out.println();
}
}
}
Output:
*
***
*****
*******
*********
10. Check Whether a String is a Pangram (All 26 Letters Present)
public class PangramCheck {
public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
str = str.toLowerCase();
boolean[] alphabet = new boolean[26];
for(char ch : str.toCharArray()) {
if(ch >= 'a' && ch <= 'z') {
alphabet[ch - 'a'] = true;
}
}
boolean isPangram = true;
for(boolean present : alphabet) {
if(!present) {
isPangram = false;
break;
}
}
System.out.println(isPangram ? "Pangram" : "Not a Pangram");
}
}
Output:
Pangram
1. Check if a Number is Palindrome (Reverse Integer)
public class PalindromeNumber {
public static void main(String[] args) {
int num = 121;
int temp = num, rev = 0;
while (temp != 0) {
int digit = temp % 10;
rev = rev * 10 + digit;
temp /= 10;
}
System.out.println((rev == num) ? "Palindrome" : "Not Palindrome");
}
}
Output:
Palindrome
2. Count Occurrence of Each Word in a Sentence
import java.util.*;
public class WordFrequency {
public static void main(String[] args) {
String sentence = "this is java and java is powerful";
String[] words = sentence.split(" ");
Map<String, Integer> freq = new HashMap<>();
for(String word : words) {
freq.put(word, freq.getOrDefault(word, 0) + 1);
}
System.out.println(freq);
}
}
Output:
{this=1, is=2, java=2, and=1, powerful=1}
3. Check if a String is a Rotation of Another
public class StringRotation {
public static void main(String[] args) {
String s1 = "abcde";
String s2 = "deabc";
if(s1.length() == s2.length() && (s1 + s1).contains(s2))
System.out.println("Rotation");
else
System.out.println("Not Rotation");
}
}
Output:
Rotation
4. Reverse an Integer Without String Conversion
public class ReverseInt {
public static void main(String[] args) {
int num = 1234, rev = 0;
while(num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed: " + rev);
}
}
Output:
Reversed: 4321
5. Print All Permutations of a String (Recursion)
public class Permutations {
public static void permute(String s, String answer) {
if(s.length() == 0) {
System.out.println(answer);
return;
}
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
String rest = s.substring(0, i) + s.substring(i+1);
permute(rest, answer + ch);
}
}
public static void main(String[] args) {
String str = "abc";
permute(str, "");
}
}
Output:
abc
acb
bac
bca
cab
cba
6. Find All Pairs in Array with Sum = K
public class PairSum {
public static void main(String[] args) {
int[] arr = {2, 4, 3, 5, 7};
int target = 7;
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
if(arr[i] + arr[j] == target) {
System.out.println(arr[i] + " + " + arr[j] + " = " + target);
}
}
}
}
}
Output:
2 + 5 = 7
4 + 3 = 7
7. Remove Duplicate Characters from a String
public class RemoveDuplicateChars {
public static void main(String[] args) {
String str = "programming";
StringBuilder result = new StringBuilder();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(result.indexOf(String.valueOf(ch)) == -1) {
result.append(ch);
}
}
System.out.println("Without duplicates: " + result);
}
}
Output:
Without duplicates: progamin
8. Convert Roman Numerals to Integer
import java.util.*;
public class RomanToInteger {
public static int romanToInt(String s) {
Map<Character, Integer> map = Map.of(
'I', 1, 'V', 5, 'X', 10, 'L', 50,
'C', 100, 'D', 500, 'M', 1000
);
int total = 0;
for(int i = 0; i < s.length(); i++) {
int val = map.get(s.charAt(i));
if(i + 1 < s.length() && val < map.get(s.charAt(i+1))) {
total -= val;
} else {
total += val;
}
}
return total;
}
public static void main(String[] args) {
System.out.println("Result: " + romanToInt("MCMIV")); // 1904
}
}
Output:
Result: 1904
9. Reverse Words in a Sentence (Not Characters)
public class ReverseSentenceWords {
public static void main(String[] args) {
String sentence = "Java is easy";
String[] words = sentence.split(" ");
for(int i = words.length - 1; i >= 0; i--) {
System.out.print(words[i] + " ");
}
}
}
Output:
easy is Java
10. Sort Characters in a String Alphabetically
import java.util.Arrays;
public class SortChars {
public static void main(String[] args) {
String s = "developer";
char[] arr = s.toCharArray();
Arrays.sort(arr);
System.out.println("Sorted: " + new String(arr));
}
}
Output:
Sorted: deeloperv
1. Count Number of Digits in an Integer
public class CountDigits {
public static void main(String[] args) {
int num = 12345;
int count = 0;
while (num != 0) {
num = num / 10;
count++;
}
System.out.println("Total digits: " + count);
}
}
Output:
Total digits: 5
2. Find GCD of Two Numbers
public class GCD {
public static void main(String[] args) {
int a = 24, b = 36;
int gcd = 1;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0)
gcd = i;
}
System.out.println("GCD: " + gcd);
}
}
Output:
GCD: 12
3. Find LCM of Two Numbers
public class LCM {
public static void main(String[] args) {
int a = 12, b = 18;
int max = Math.max(a, b);
while (true) {
if (max % a == 0 && max % b == 0) {
System.out.println("LCM: " + max);
break;
}
max++;
}
}
}
Output:
LCM: 36
4. Linear Search in Array
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
int key = 30;
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
found = true;
System.out.println("Found at index: " + i);
break;
}
}
if (!found)
System.out.println("Not found");
}
}
Output:
Found at index: 2
5. Binary Search (Sorted Array)
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {5, 10, 20, 30, 50};
int key = 30;
int low = 0, high = arr.length - 1;
boolean found = false;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) {
found = true;
System.out.println("Found at index: " + mid);
break;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (!found)
System.out.println("Not found");
}
}
Output:
Found at index: 3
6. Check Whether a Number is Perfect Number
> A perfect number = sum of its proper divisors (excluding itself)
public class PerfectNumber {
public static void main(String[] args) {
int num = 28, sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0)
sum += i;
}
if (sum == num)
System.out.println(num + " is Perfect Number");
else
System.out.println(num + " is Not Perfect");
}
}
Output:
28 is Perfect Number
7. Constructor Overloading Example
public class Student {
String name;
int age;
Student() {
name = "Default";
age = 18;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + " - " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Rahul", 21);
s1.display();
s2.display();
}
}
Output:
Default - 18
Rahul - 21
8. Check Armstrong Number (3 digits)
public class Armstrong {
public static void main(String[] args) {
int num = 153, temp = num, sum = 0;
while (temp != 0) {
int d = temp % 10;
sum += d * d * d;
temp /= 10;
}
System.out.println((sum == num) ? "Armstrong" : "Not Armstrong");
}
}
Output:
Armstrong
9. Reverse a Number Using Recursion
public class ReverseRecursion {
static int rev = 0;
public static void reverse(int num) {
if (num == 0)
return;
rev = rev * 10 + num % 10;
reverse(num / 10);
}
public static void main(String[] args) {
int num = 1234;
reverse(num);
System.out.println("Reversed: " + rev);
}
}
Output:
Reversed: 4321
10. Print Floyd's Triangle
public class FloydTriangle {
public static void main(String[] args) {
int n = 5, num = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num++ + " ");
}
System.out.println();
}
}
}
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
11. Check Whether a String Is Palindrome (Ignoring Case & Space)
public class PalindromeClean {
public static void main(String[] args) {
String str = "A man a plan a canal Panama";
str = str.replaceAll("\\s+", "").toLowerCase();
String rev = new StringBuilder(str).reverse().toString();
System.out.println(str.equals(rev) ? "Palindrome" : "Not Palindrome");
}
}
Output:
Palindrome
12. Check Leap Year
public class LeapYearCheck {
public static void main(String[] args) {
int year = 2024;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(year + " is a Leap Year");
else
System.out.println(year + " is not a Leap Year");
}
}
Output:
2024 is a Leap Year
// 1. Inheritance Example
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// 2. Interface Implementation
interface Vehicle {
void run();
}
class Bike implements Vehicle {
public void run() {
System.out.println("Bike is running");
}
}
// 3. File Handling - Write to File
import java.io.*;
class WriteFile {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello, this is file handling example in Java.");
fw.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
// 4. File Handling - Read from File
import java.io.*;
class ReadFile {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("File not found.");
}
}
}
// 5. Collections - ArrayList Example
import java.util.*;
class ListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
for (String item : list) {
System.out.println(item);
}
}
}
// 6. Collections - HashMap Example
import java.util.*;
class MapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}
1. Basic Programs (Input, Output, Loops)
Q1. Write a program to check if a number is even or odd.
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // For input
System.out.print("Enter a number: ");
int num = sc.nextInt(); // Read number from user
if(num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
}
}
Flow:
Input a number → Check num % 2 → Print result.
Output:
Enter a number: 5
5 is odd
2. OOPS Concepts – Classes, Objects, Methods
Q2. Program to demonstrate Class & Object
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving");
}
void displayColor() {
System.out.println("Color is: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.drive(); // Method call
myCar.displayColor(); // Method call
}
}
Output:
Car is driving
Color is: Red
Flow:
Create class Car → Create object in main → Call methods
3. Constructor Overloading
Q3. Program to demonstrate constructor overloading
class Student {
String name;
int age;
Student() {
name = "Default";
age = 18;
}
Student(String n, int a) {
name = n;
age = a;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Calls default constructor
Student s2 = new Student("Raj", 20); // Calls parameterized constructor
s1.show();
s2.show();
}
}
Output:
Name: Default, Age: 18
Name: Raj, Age: 20
4. Inheritance and Polymorphism
Q4. Program to demonstrate method overriding
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog's sound() method
}
}
Output:
Dog barks
Flow:
Dog overrides sound() → Object is of Dog → Dog's method is called
5. Encapsulation
Q5. Program with getter and setter
class Employee {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Ajay");
System.out.println("Name: " + e.getName());
}
}
Output:
Name: Ajay
6. Abstraction
Q6. Abstract class example
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
public class Test {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}
Output:
Drawing Circle
7. Interface
Q7. Interface implementation
interface Bank {
double rateOfInterest();
}
class SBI implements Bank {
public double rateOfInterest() {
return 7.0;
}
}
public class Test {
public static void main(String[] args) {
Bank b = new SBI();
System.out.println("ROI: " + b.rateOfInterest());
}
}
Output:
ROI: 7.0
8. Exception Handling
Q8. Try-catch-finally example
public class Test {
public static void main(String[] args) {
try {
int a = 10 / 0; // Throws exception
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
Output:
Error: / by zero
Finally block executed
9. String Programs
Q9. Reverse a string
public class ReverseString {
public static void main(String[] args) {
String s = "Java";
String rev = "";
for(int i = s.length() - 1; i >= 0; i--) {
rev += s.charAt(i);
}
System.out.println("Reversed: " + rev);
}
}
Output:
Reversed: avaJ
10. Collections (ArrayList)
Q10. Add elements to ArrayList
import java.util.*;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Mango");
for(String fruit : list) {
System.out.println(fruit);
}
}
}
Output:
Apple
Banana
Mango
11. Multithreading (Thread)
Q11. Thread example using Runnable
class MyThread implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}
public class Test {
public static void main(String[] args) {
MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start();
}
}
Output:
Thread is running...
12. File Handling
Q12. Write to file
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("test.txt");
writer.write("Hello Java!");
writer.close();
System.out.println("File written successfully");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output:
File written successfully
No comments:
Post a Comment