0% found this document useful (0 votes)
2 views73 pages

100-java-programs

The document is a collection of 100 Java programs designed for beginners, covering fundamental concepts to advanced topics. Each program includes a problem description, complete code, and output examples, organized into sections such as Basic Fundamentals, Control Flow, and Data Structures. The content aims to provide hands-on practice for learning Java programming.

Uploaded by

moolsinghmsimsi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views73 pages

100-java-programs

The document is a collection of 100 Java programs designed for beginners, covering fundamental concepts to advanced topics. Each program includes a problem description, complete code, and output examples, organized into sections such as Basic Fundamentals, Control Flow, and Data Structures. The content aims to provide hands-on practice for learning Java programming.

Uploaded by

moolsinghmsimsi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

100 Java Beginner Practice Programs with Solu-

tions
A comprehensive collection of Java programs for beginners covering fundamental
concepts through advanced topics. Each program includes complete working
code, problem description, and output examples.

Table of Contents
1. Basic Fundamentals (Programs 1-15)
2. Control Flow (Programs 16-30)
3. Number System Conversions (Programs 31-40)
4. String Manipulation (Programs 41-50)
5. Mathematical Programs (Programs 51-65)
6. Arrays (Programs 66-80)
7. Recursion (Programs 81-90)
8. Data Structures Basics (Programs 91-100)

Section 1: Basic Fundamentals


Program 1: Hello World
Description: Print “Hello World” to the console.
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Output:
Hello, World!

Program 2: Sum of Two Numbers


Description: Calculate and display the sum of two integers.
import [Link];

public class SumTwoNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");

1
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();

int sum = num1 + num2;


[Link]("Sum = " + sum);
[Link]();
}
}
Output:
Enter first number: 25
Enter second number: 35
Sum = 60

Program 3: Product of Two Numbers


Description: Multiply two numbers and display the result.
import [Link];

public class ProductTwoNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

int product = a * b;
[Link](a + " x " + b + " = " + product);
[Link]();
}
}
Output:
Enter first number: 12
Enter second number: 8
12 x 8 = 96

Program 4: Basic Arithmetic Operations


Description: Perform addition, subtraction, multiplication, division, and mod-
ulus operations.

2
import [Link];

public class ArithmeticOperations {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();

[Link](num1 + " + " + num2 + " = " + (num1 + num2));


[Link](num1 + " - " + num2 + " = " + (num1 - num2));
[Link](num1 + " * " + num2 + " = " + (num1 * num2));
[Link](num1 + " / " + num2 + " = " + (num1 / num2));
[Link](num1 + " % " + num2 + " = " + (num1 % num2));
[Link]();
}
}
Output:
Enter first number: 125
Enter second number: 24
125 + 24 = 149
125 - 24 = 101
125 * 24 = 3000
125 / 24 = 5
125 % 24 = 5

Program 5: Swap Two Numbers


Description: Swap values of two variables without using a third variable.
import [Link];

public class SwapNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

[Link]("Before swap: a = " + a + ", b = " + b);

a = a + b;

3
b = a - b;
a = a - b;

[Link]("After swap: a = " + a + ", b = " + b);


[Link]();
}
}
Output:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10

Program 6: Area of Circle


Description: Calculate the area and perimeter of a circle.
import [Link];

public class CircleArea {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter radius: ");
double radius = [Link]();

double area = [Link] * radius * radius;


double perimeter = 2 * [Link] * radius;

[Link]("Area = " + area);


[Link]("Perimeter = " + perimeter);
[Link]();
}
}
Output:
Enter radius: 7.5
Area = 176.71458676442586
Perimeter = 47.12388980384689

Program 7: Area of Rectangle


Description: Calculate area and perimeter of a rectangle.
import [Link];

4
public class RectangleArea {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter width: ");
double width = [Link]();
[Link]("Enter height: ");
double height = [Link]();

double area = width * height;


double perimeter = 2 * (width + height);

[Link]("Area = " + area);


[Link]("Perimeter = " + perimeter);
[Link]();
}
}
Output:
Enter width: 5.5
Enter height: 8.5
Area = 46.75
Perimeter = 28.0

Program 8: Temperature Conversion (Celsius to Fahrenheit)


Description: Convert temperature from Celsius to Fahrenheit.
import [Link];

public class TempConversion {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter temperature in Celsius: ");
double celsius = [Link]();

double fahrenheit = (celsius * 9/5) + 32;


[Link](celsius + "°C = " + fahrenheit + "°F");
[Link]();
}
}
Output:
Enter temperature in Celsius: 25
25.0°C = 77.0°F

5
Program 9: Average of Three Numbers
Description: Calculate the average of three numbers.
import [Link];

public class AverageThree {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter second number: ");
double num2 = [Link]();
[Link]("Enter third number: ");
double num3 = [Link]();

double average = (num1 + num2 + num3) / 3;


[Link]("Average = " + average);
[Link]();
}
}
Output:
Enter first number: 10
Enter second number: 20
Enter third number: 30
Average = 20.0

Program 10: Simple Interest Calculator


Description: Calculate simple interest given principal, rate, and time.
import [Link];

public class SimpleInterest {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter principal amount: ");
double principal = [Link]();
[Link]("Enter rate of interest: ");
double rate = [Link]();
[Link]("Enter time (years): ");
double time = [Link]();

6
double interest = (principal * rate * time) / 100;
[Link]("Simple Interest = " + interest);
[Link]();
}
}
Output:
Enter principal amount: 10000
Enter rate of interest: 5
Enter time (years): 2
Simple Interest = 1000.0

Program 11: Sum of Digits


Description: Calculate the sum of digits of an integer.
import [Link];

public class SumOfDigits {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
[Link]("Sum of digits = " + sum);
[Link]();
}
}
Output:
Enter a number: 1234
Sum of digits = 10

Program 12: Reverse a Number


Description: Reverse the digits of an integer.
import [Link];

7
public class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
[Link]("Reversed number = " + reversed);
[Link]();
}
}
Output:
Enter a number: 12345
Reversed number = 54321

Program 13: ASCII Value of Character


Description: Print the ASCII value of a character.
public class AsciiValue {
public static void main(String[] args) {
char ch = 'A';
int ascii = ch;
[Link]("ASCII value of " + ch + " is " + ascii);
}
}
Output:
ASCII value of A is 65

Program 14: Multiplication Table


Description: Print multiplication table of a number.
import [Link];

public class MultiplicationTable {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

8
[Link]("Enter a number: ");
int num = [Link]();

for (int i = 1; i <= 10; i++) {


[Link](num + " x " + i + " = " + (num * i));
}
[Link]();
}
}
Output:
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50

Program 15: Compare Two Numbers


Description: Compare two integers and display relationship.
import [Link];

public class CompareNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();

if (num1 == num2) {
[Link](num1 + " == " + num2);
} else if (num1 > num2) {
[Link](num1 + " > " + num2);
} else {
[Link](num1 + " < " + num2);
}
[Link]();
}
}
Output:
Enter first number: 25
Enter second number: 30

9
25 < 30

Section 2: Control Flow


Program 16: Check Even or Odd
Description: Check if a number is even or odd.
import [Link];

public class EvenOdd {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

if (num % 2 == 0) {
[Link](num + " is even");
} else {
[Link](num + " is odd");
}
[Link]();
}
}
Output:
Enter a number: 17
17 is odd

Program 17: Check Positive, Negative, or Zero


Description: Determine if a number is positive, negative, or zero.
import [Link];

public class CheckSign {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

if (num > 0) {
[Link](num + " is positive");
} else if (num < 0) {

10
[Link](num + " is negative");
} else {
[Link]("Number is zero");
}
[Link]();
}
}
Output:
Enter a number: -5
-5 is negative

Program 18: Largest of Three Numbers


Description: Find the largest among three numbers.
import [Link];

public class LargestOfThree {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
[Link]("Enter third number: ");
int c = [Link]();

int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;

[Link]("Largest = " + largest);


[Link]();
}
}
Output:
Enter first number: 10
Enter second number: 25
Enter third number: 15
Largest = 25

11
Program 19: Leap Year Check
Description: Check if a given year is a leap year.
import [Link];

public class LeapYear {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter year: ");
int year = [Link]();

if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {


[Link](year + " is a leap year");
} else {
[Link](year + " is not a leap year");
}
[Link]();
}
}
Output:
Enter year: 2024
2024 is a leap year

Program 20: Grade Calculator


Description: Calculate grade based on marks.
import [Link];

public class GradeCalculator {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter marks (0-100): ");
int marks = [Link]();

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 80) {
[Link]("Grade: A");
} else if (marks >= 70) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else if (marks >= 50) {

12
[Link]("Grade: D");
} else {
[Link]("Grade: F");
}
[Link]();
}
}
Output:
Enter marks (0-100): 85
Grade: A

Program 21: Vowel or Consonant


Description: Check if a character is a vowel or consonant.
import [Link];

public class VowelConsonant {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a character: ");
char ch = [Link]().charAt(0);

ch = [Link](ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
[Link](ch + " is a vowel");
} else if (ch >= 'a' && ch <= 'z') {
[Link](ch + " is a consonant");
} else {
[Link](ch + " is not a letter");
}
[Link]();
}
}
Output:
Enter a character: e
e is a vowel

Program 22: Calculator Using Switch


Description: Simple calculator using switch statement.

13
import [Link];

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter operator (+, -, *, /): ");
char op = [Link]().charAt(0);
[Link]("Enter second number: ");
double num2 = [Link]();

double result;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
[Link]("Invalid operator");
[Link]();
return;
}
[Link]("Result = " + result);
[Link]();
}
}
Output:
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
Result = 50.0

14
Program 23: Print Numbers 1 to N
Description: Print numbers from 1 to N using for loop.
import [Link];

public class PrintNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int n = [Link]();

for (int i = 1; i <= n; i++) {


[Link](i + " ");
}
[Link]();
}
}
Output:
Enter N: 10
1 2 3 4 5 6 7 8 9 10

Program 24: Print Odd Numbers from 1 to 100


Description: Print all odd numbers between 1 and 100.
public class OddNumbers {
public static void main(String[] args) {
[Link]("Odd numbers from 1 to 100:");
for (int i = 1; i <= 100; i += 2) {
[Link](i + " ");
}
}
}
Output:
Odd numbers from 1 to 100:
1 3 5 7 9 ... 97 99

Program 25: Print Even Numbers from 1 to 100


Description: Print all even numbers between 1 and 100.

15
public class EvenNumbers {
public static void main(String[] args) {
[Link]("Even numbers from 1 to 100:");
for (int i = 2; i <= 100; i += 2) {
[Link](i + " ");
}
}
}
Output:
Even numbers from 1 to 100:
2 4 6 8 10 ... 98 100

Program 26: Sum of Natural Numbers


Description: Calculate sum of first N natural numbers.
import [Link];

public class SumNatural {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int n = [Link]();

int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
[Link]("Sum = " + sum);
[Link]();
}
}
Output:
Enter N: 10
Sum = 55

Program 27: Count Digits in a Number


Description: Count the number of digits in an integer.
import [Link];

16
public class CountDigits {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int count = 0;
while (num != 0) {
num /= 10;
count++;
}
[Link]("Number of digits = " + count);
[Link]();
}
}
Output:
Enter a number: 12345
Number of digits = 5

Program 28: FizzBuzz Program


Description: Print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz
for both.
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
[Link]("FizzBuzz");
} else if (i % 3 == 0) {
[Link]("Fizz");
} else if (i % 5 == 0) {
[Link]("Buzz");
} else {
[Link](i);
}
}
}
}
Output:
1
2
Fizz

17
4
Buzz
...

Program 29: Number Pattern (Triangle)


Description: Print number pattern in triangle shape.
import [Link];

public class NumberPattern {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of rows: ");
int n = [Link]();

for (int i = 1; i <= n; i++) {


for (int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link]();
}
[Link]();
}
}
Output:
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Program 30: Star Pattern (Pyramid)


Description: Print star pattern in pyramid shape.
import [Link];

public class StarPattern {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of rows: ");

18
int n = [Link]();

for (int i = 1; i <= n; i++) {


for (int j = i; j < n; j++) {
[Link](" ");
}
for (int k = 1; k <= (2 * i - 1); k++) {
[Link]("*");
}
[Link]();
}
[Link]();
}
}
Output:
Enter number of rows: 5
*
***
*****
*******
*********

Section 3: Number System Conversions


Program 31: Decimal to Binary
Description: Convert decimal number to binary.
import [Link];

public class DecimalToBinary {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter decimal number: ");
int decimal = [Link]();

String binary = [Link](decimal);


[Link]("Binary = " + binary);
[Link]();
}
}
Output:
Enter decimal number: 10

19
Binary = 1010

Program 32: Binary to Decimal


Description: Convert binary number to decimal.
import [Link];

public class BinaryToDecimal {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter binary number: ");
String binary = [Link]();

int decimal = [Link](binary, 2);


[Link]("Decimal = " + decimal);
[Link]();
}
}
Output:
Enter binary number: 1010
Decimal = 10

Program 33: Decimal to Octal


Description: Convert decimal number to octal.
import [Link];

public class DecimalToOctal {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter decimal number: ");
int decimal = [Link]();

String octal = [Link](decimal);


[Link]("Octal = " + octal);
[Link]();
}
}
Output:
Enter decimal number: 64

20
Octal = 100

Program 34: Octal to Decimal


Description: Convert octal number to decimal.
import [Link];

public class OctalToDecimal {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter octal number: ");
String octal = [Link]();

int decimal = [Link](octal, 8);


[Link]("Decimal = " + decimal);
[Link]();
}
}
Output:
Enter octal number: 100
Decimal = 64

Program 35: Decimal to Hexadecimal


Description: Convert decimal number to hexadecimal.
import [Link];

public class DecimalToHex {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter decimal number: ");
int decimal = [Link]();

String hex = [Link](decimal);


[Link]("Hexadecimal = " + [Link]());
[Link]();
}
}
Output:
Enter decimal number: 255

21
Hexadecimal = FF

Program 36: Hexadecimal to Decimal


Description: Convert hexadecimal number to decimal.
import [Link];

public class HexToDecimal {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter hexadecimal number: ");
String hex = [Link]();

int decimal = [Link](hex, 16);


[Link]("Decimal = " + decimal);
[Link]();
}
}
Output:
Enter hexadecimal number: FF
Decimal = 255

Program 37: Binary to Octal


Description: Convert binary number to octal.
import [Link];

public class BinaryToOctal {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter binary number: ");
String binary = [Link]();

int decimal = [Link](binary, 2);


String octal = [Link](decimal);
[Link]("Octal = " + octal);
[Link]();
}
}
Output:

22
Enter binary number: 111
Octal = 7

Program 38: Binary to Hexadecimal


Description: Convert binary number to hexadecimal.
import [Link];

public class BinaryToHex {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter binary number: ");
String binary = [Link]();

int decimal = [Link](binary, 2);


String hex = [Link](decimal);
[Link]("Hexadecimal = " + [Link]());
[Link]();
}
}
Output:
Enter binary number: 11111111
Hexadecimal = FF

Program 39: Octal to Binary


Description: Convert octal number to binary.
import [Link];

public class OctalToBinary {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter octal number: ");
String octal = [Link]();

int decimal = [Link](octal, 8);


String binary = [Link](decimal);
[Link]("Binary = " + binary);
[Link]();
}
}

23
Output:
Enter octal number: 7
Binary = 111

Program 40: Hexadecimal to Binary


Description: Convert hexadecimal number to binary.
import [Link];

public class HexToBinary {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter hexadecimal number: ");
String hex = [Link]();

int decimal = [Link](hex, 16);


String binary = [Link](decimal);
[Link]("Binary = " + binary);
[Link]();
}
}
Output:
Enter hexadecimal number: FF
Binary = 11111111

Section 4: String Manipulation


Program 41: Reverse a String
Description: Reverse a given string.
import [Link];

public class ReverseString {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

String reversed = "";


for (int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);

24
}
[Link]("Reversed string: " + reversed);
[Link]();
}
}
Output:
Enter a string: Hello
Reversed string: olleH

Program 42: Check Palindrome String


Description: Check if a string is a palindrome.
import [Link];

public class PalindromeString {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

String reversed = "";


for (int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);
}

if ([Link](reversed)) {
[Link](str + " is a palindrome");
} else {
[Link](str + " is not a palindrome");
}
[Link]();
}
}
Output:
Enter a string: radar
radar is a palindrome

Program 43: Count Vowels and Consonants


Description: Count vowels and consonants in a string.

25
import [Link];

public class CountVowelsConsonants {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]().toLowerCase();

int vowels = 0, consonants = 0;


for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
[Link]();
}
}
Output:
Enter a string: Hello World
Vowels: 3
Consonants: 7

Program 44: String Length Without Using length()


Description: Find string length without using built-in method.
import [Link];

public class StringLength {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

int length = 0;
for (char c : [Link]()) {
length++;

26
}
[Link]("Length = " + length);
[Link]();
}
}
Output:
Enter a string: Programming
Length = 11

Program 45: Convert to Uppercase


Description: Convert a string to uppercase.
import [Link];

public class ToUpperCase {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

String upper = [Link]();


[Link]("Uppercase: " + upper);
[Link]();
}
}
Output:
Enter a string: hello world
Uppercase: HELLO WORLD

Program 46: Convert to Lowercase


Description: Convert a string to lowercase.
import [Link];

public class ToLowerCase {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

27
String lower = [Link]();
[Link]("Lowercase: " + lower);
[Link]();
}
}
Output:
Enter a string: HELLO WORLD
Lowercase: hello world

Program 47: Compare Two Strings


Description: Compare two strings for equality.
import [Link];

public class CompareStrings {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();

if ([Link](str2)) {
[Link]("Strings are equal");
} else {
[Link]("Strings are not equal");
}
[Link]();
}
}
Output:
Enter first string: Java
Enter second string: Java
Strings are equal

Program 48: Concatenate Strings


Description: Concatenate two strings.
import [Link];

28
public class ConcatenateStrings {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();

String result = str1 + str2;


[Link]("Concatenated: " + result);
[Link]();
}
}
Output:
Enter first string: Hello
Enter second string: World
Concatenated: HelloWorld

Program 49: Remove Spaces from String


Description: Remove all spaces from a string.
import [Link];

public class RemoveSpaces {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

String result = [Link](" ", "");


[Link]("String without spaces: " + result);
[Link]();
}
}
Output:
Enter a string: Hello World Java
String without spaces: HelloWorldJava

Program 50: Count Words in String


Description: Count the number of words in a string.

29
import [Link];

public class CountWords {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]().trim();

if ([Link]()) {
[Link]("Word count: 0");
} else {
String[] words = [Link]("\\s+");
[Link]("Word count: " + [Link]);
}
[Link]();
}
}
Output:
Enter a string: Java Programming Language
Word count: 3

Section 5: Mathematical Programs


Program 51: Check Prime Number
Description: Check if a number is prime.
import [Link];

public class PrimeNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

boolean isPrime = true;


if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}

30
}
}

if (isPrime) {
[Link](num + " is prime");
} else {
[Link](num + " is not prime");
}
[Link]();
}
}
Output:
Enter a number: 29
29 is prime

Program 52: Factorial (Iterative)


Description: Calculate factorial using iteration.
import [Link];

public class FactorialIterative {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
[Link]("Factorial = " + factorial);
[Link]();
}
}
Output:
Enter a number: 5
Factorial = 120

Program 53: Fibonacci Series (Iterative)


Description: Print Fibonacci series using iteration.

31
import [Link];

public class FibonacciIterative {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of terms: ");
int n = [Link]();

int first = 0, second = 1;


[Link]("Fibonacci Series: " + first + " " + second);

for (int i = 2; i < n; i++) {


int next = first + second;
[Link](" " + next);
first = second;
second = next;
}
[Link]();
}
}
Output:
Enter number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Program 54: Check Palindrome Number


Description: Check if a number is a palindrome.
import [Link];

public class PalindromeNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int original = num, reversed = 0;


while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}

if (original == reversed) {
[Link](original + " is a palindrome");

32
} else {
[Link](original + " is not a palindrome");
}
[Link]();
}
}
Output:
Enter a number: 121
121 is a palindrome

Program 55: Armstrong Number


Description: Check if a number is an Armstrong number.
import [Link];

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int original = num, sum = 0, digits = [Link](num).length();


while (num > 0) {
int digit = num % 10;
sum += [Link](digit, digits);
num /= 10;
}

if (original == sum) {
[Link](original + " is an Armstrong number");
} else {
[Link](original + " is not an Armstrong number");
}
[Link]();
}
}
Output:
Enter a number: 153
153 is an Armstrong number

33
Program 56: GCD (Greatest Common Divisor)
Description: Find GCD of two numbers using Euclidean algorithm.
import [Link];

public class GCD {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
[Link]("GCD = " + a);
[Link]();
}
}
Output:
Enter first number: 48
Enter second number: 18
GCD = 6

Program 57: LCM (Least Common Multiple)


Description: Find LCM of two numbers.
import [Link];

public class LCM {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

int gcd = a, temp = b;


while (temp != 0) {
int r = gcd % temp;

34
gcd = temp;
temp = r;
}

int lcm = (a * b) / gcd;


[Link]("LCM = " + lcm);
[Link]();
}
}
Output:
Enter first number: 12
Enter second number: 18
LCM = 36

Program 58: Power of Number


Description: Calculate power of a number.
import [Link];

public class PowerOfNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter base: ");
int base = [Link]();
[Link]("Enter exponent: ");
int exp = [Link]();

long result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
[Link](base + "^" + exp + " = " + result);
[Link]();
}
}
Output:
Enter base: 2
Enter exponent: 10
2^10 = 1024

35
Program 59: Square Root
Description: Calculate square root of a number.
import [Link];

public class SquareRoot {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
double num = [Link]();

double sqrt = [Link](num);


[Link]("Square root = " + sqrt);
[Link]();
}
}
Output:
Enter a number: 25
Square root = 5.0

Program 60: Perfect Number


Description: Check if a number is a perfect number.
import [Link];

public class PerfectNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) {
sum += i;
}
}

if (sum == num) {
[Link](num + " is a perfect number");
} else {
[Link](num + " is not a perfect number");
}

36
[Link]();
}
}
Output:
Enter a number: 28
28 is a perfect number

Program 61: Strong Number


Description: Check if a number is a strong number.
import [Link];

public class StrongNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int original = num, sum = 0;


while (num > 0) {
int digit = num % 10;
int fact = 1;
for (int i = 1; i <= digit; i++) {
fact *= i;
}
sum += fact;
num /= 10;
}

if (original == sum) {
[Link](original + " is a strong number");
} else {
[Link](original + " is not a strong number");
}
[Link]();
}
}
Output:
Enter a number: 145
145 is a strong number

37
Program 62: Sum of Prime Numbers in Range
Description: Find sum of all prime numbers in a range.
import [Link];

public class SumOfPrimes {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter start: ");
int start = [Link]();
[Link]("Enter end: ");
int end = [Link]();

int sum = 0;
for (int num = start; num <= end; num++) {
boolean isPrime = num > 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) sum += num;
}
[Link]("Sum of primes = " + sum);
[Link]();
}
}
Output:
Enter start: 1
Enter end: 10
Sum of primes = 17

Program 63: Number of Factors


Description: Count the number of factors of a number.
import [Link];

public class CountFactors {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

38
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
[Link]("Number of factors = " + count);
[Link]();
}
}
Output:
Enter a number: 12
Number of factors = 6

Program 64: Sum of Odd Digits


Description: Calculate sum of odd digits in a number.
import [Link];

public class SumOddDigits {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int sum = 0;
while (num > 0) {
int digit = num % 10;
if (digit % 2 != 0) {
sum += digit;
}
num /= 10;
}
[Link]("Sum of odd digits = " + sum);
[Link]();
}
}
Output:
Enter a number: 12345
Sum of odd digits = 9

39
Program 65: Product of Digits
Description: Calculate product of all digits in a number.
import [Link];

public class ProductOfDigits {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int product = 1;
while (num > 0) {
product *= num % 10;
num /= 10;
}
[Link]("Product of digits = " + product);
[Link]();
}
}
Output:
Enter a number: 123
Product of digits = 6

Section 6: Arrays
Program 66: Find Largest Element in Array
Description: Find the largest element in an array.
import [Link];

public class LargestInArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();

40
}

int max = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
[Link]("Largest element = " + max);
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 45 23 67 34
Largest element = 67

Program 67: Find Smallest Element in Array


Description: Find the smallest element in an array.
import [Link];

public class SmallestInArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int min = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
[Link]("Smallest element = " + min);
[Link]();

41
}
}
Output:
Enter array size: 5
Enter array elements:
10 45 23 67 34
Smallest element = 10

Program 68: Sum of Array Elements


Description: Calculate sum of all array elements.
import [Link];

public class SumArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
[Link]("Sum = " + sum);
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 20 30 40 50
Sum = 150

42
Program 69: Average of Array Elements
Description: Calculate average of array elements.
import [Link];

public class AverageArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
sum += arr[i];
}

double average = (double) sum / n;


[Link]("Average = " + average);
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 20 30 40 50
Average = 30.0

Program 70: Linear Search


Description: Search for an element using linear search.
import [Link];

public class LinearSearch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");

43
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

[Link]("Enter element to search: ");


int target = [Link]();

int index = -1;


for (int i = 0; i < n; i++) {
if (arr[i] == target) {
index = i;
break;
}
}

if (index != -1) {
[Link]("Element found at index " + index);
} else {
[Link]("Element not found");
}
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 20 30 40 50
Enter element to search: 30
Element found at index 2

Program 71: Binary Search


Description: Search for an element using binary search (array must be sorted).
import [Link];

public class BinarySearch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter sorted array elements:");

44
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

[Link]("Enter element to search: ");


int target = [Link]();

int low = 0, high = n - 1, index = -1;


while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
index = mid;
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}

if (index != -1) {
[Link]("Element found at index " + index);
} else {
[Link]("Element not found");
}
[Link]();
}
}
Output:
Enter array size: 5
Enter sorted array elements:
10 20 30 40 50
Enter element to search: 30
Element found at index 2

Program 72: Bubble Sort


Description: Sort an array using bubble sort algorithm.
import [Link];
import [Link];

public class BubbleSort {


public static void main(String[] args) {

45
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

for (int i = 0; i < n - 1; i++) {


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

[Link]("Sorted array: " + [Link](arr));


[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
64 34 25 12 22
Sorted array: [12, 22, 25, 34, 64]

Program 73: Selection Sort


Description: Sort an array using selection sort algorithm.
import [Link];
import [Link];

public class SelectionSort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

46
[Link]("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

for (int i = 0; i < n - 1; i++) {


int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}

[Link]("Sorted array: " + [Link](arr));


[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
64 34 25 12 22
Sorted array: [12, 22, 25, 34, 64]

Program 74: Reverse an Array


Description: Reverse the elements of an array.
import [Link];
import [Link];

public class ReverseArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();

47
}

for (int i = 0; i < n / 2; i++) {


int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}

[Link]("Reversed array: " + [Link](arr));


[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 20 30 40 50
Reversed array: [50, 40, 30, 20, 10]

Program 75: Count Even and Odd Numbers in Array


Description: Count even and odd numbers in an array.
import [Link];

public class CountEvenOdd {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int even = 0, odd = 0;


for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
even++;
} else {
odd++;
}
}

48
[Link]("Even numbers: " + even);
[Link]("Odd numbers: " + odd);
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 15 20 25 30
Even numbers: 3
Odd numbers: 2

Program 76: Second Largest Element


Description: Find the second largest element in an array.
import [Link];

public class SecondLargest {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int max = Integer.MIN_VALUE;


int secondMax = Integer.MIN_VALUE;

for (int i = 0; i < n; i++) {


if (arr[i] > max) {
secondMax = max;
max = arr[i];
} else if (arr[i] > secondMax && arr[i] != max) {
secondMax = arr[i];
}
}

[Link]("Second largest = " + secondMax);

49
[Link]();
}
}
Output:
Enter array size: 5
Enter array elements:
10 45 23 67 34
Second largest = 45

Program 77: Merge Two Arrays


Description: Merge two arrays into a third array.
import [Link];
import [Link];

public class MergeArrays {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter first array size: ");


int n1 = [Link]();
int[] arr1 = new int[n1];
[Link]("Enter first array elements:");
for (int i = 0; i < n1; i++) {
arr1[i] = [Link]();
}

[Link]("Enter second array size: ");


int n2 = [Link]();
int[] arr2 = new int[n2];
[Link]("Enter second array elements:");
for (int i = 0; i < n2; i++) {
arr2[i] = [Link]();
}

int[] merged = new int[n1 + n2];


for (int i = 0; i < n1; i++) {
merged[i] = arr1[i];
}
for (int i = 0; i < n2; i++) {
merged[n1 + i] = arr2[i];
}

50
[Link]("Merged array: " + [Link](merged));
[Link]();
}
}
Output:
Enter first array size: 3
Enter first array elements:
10 20 30
Enter second array size: 2
Enter second array elements:
40 50
Merged array: [10, 20, 30, 40, 50]

Program 78: Remove Duplicates from Array


Description: Remove duplicate elements from an array.
import [Link];
import [Link];

public class RemoveDuplicates {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

int[] temp = new int[n];


int j = 0;

for (int i = 0; i < n - 1; i++) {


if (arr[i] != arr[i + 1]) {
temp[j++] = arr[i];
}
}
temp[j++] = arr[n - 1];

[Link]("Array without duplicates: ");


for (int i = 0; i < j; i++) {

51
[Link](temp[i] + " ");
}
[Link]();
}
}
Output:
Enter array size: 7
Enter array elements:
1 1 2 2 3 4 4
Array without duplicates: 1 2 3 4

Program 79: Matrix Addition


Description: Add two matrices.
import [Link];

public class MatrixAddition {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns: ");
int rows = [Link]();
int cols = [Link]();

int[][] mat1 = new int[rows][cols];


int[][] mat2 = new int[rows][cols];
int[][] sum = new int[rows][cols];

[Link]("Enter first matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat1[i][j] = [Link]();
}
}

[Link]("Enter second matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat2[i][j] = [Link]();
}
}

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {

52
sum[i][j] = mat1[i][j] + mat2[i][j];
}
}

[Link]("Sum matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}
[Link]();
}
}
Output:
Enter rows and columns: 2 2
Enter first matrix:
1 2
3 4
Enter second matrix:
5 6
7 8
Sum matrix:
6 8
10 12

Program 80: Matrix Multiplication


Description: Multiply two matrices.
import [Link];

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns of first matrix: ");
int r1 = [Link]();
int c1 = [Link]();

[Link]("Enter rows and columns of second matrix: ");


int r2 = [Link]();
int c2 = [Link]();

if (c1 != r2) {

53
[Link]("Multiplication not possible");
[Link]();
return;
}

int[][] mat1 = new int[r1][c1];


int[][] mat2 = new int[r2][c2];
int[][] result = new int[r1][c2];

[Link]("Enter first matrix:");


for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
mat1[i][j] = [Link]();
}
}

[Link]("Enter second matrix:");


for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
mat2[i][j] = [Link]();
}
}

for (int i = 0; i < r1; i++) {


for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}

[Link]("Product matrix:");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
[Link]();
}
}
Output:
Enter rows and columns of first matrix: 2 2
Enter rows and columns of second matrix: 2 2
Enter first matrix:

54
1 2
3 4
Enter second matrix:
5 6
7 8
Product matrix:
19 22
43 50

Section 7: Recursion
Program 81: Factorial Using Recursion
Description: Calculate factorial using recursion.
import [Link];

public class FactorialRecursive {


public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

long result = factorial(num);


[Link]("Factorial = " + result);
[Link]();
}
}
Output:
Enter a number: 5
Factorial = 120

Program 82: Fibonacci Using Recursion


Description: Generate Fibonacci series using recursion.

55
import [Link];

public class FibonacciRecursive {


public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter number of terms: ");
int n = [Link]();

[Link]("Fibonacci Series: ");


for (int i = 0; i < n; i++) {
[Link](fibonacci(i) + " ");
}
[Link]();
}
}
Output:
Enter number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Program 83: Sum of Natural Numbers Using Recursion


Description: Calculate sum of first N natural numbers using recursion.
import [Link];

public class SumRecursive {


public static int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int n = [Link]();

56
int result = sum(n);
[Link]("Sum = " + result);
[Link]();
}
}
Output:
Enter N: 10
Sum = 55

Program 84: Power Using Recursion


Description: Calculate power of a number using recursion.
import [Link];

public class PowerRecursive {


public static long power(int base, int exp) {
if (exp == 0) {
return 1;
}
return base * power(base, exp - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter base: ");
int base = [Link]();
[Link]("Enter exponent: ");
int exp = [Link]();

long result = power(base, exp);


[Link](base + "^" + exp + " = " + result);
[Link]();
}
}
Output:
Enter base: 2
Enter exponent: 10
2^10 = 1024

57
Program 85: GCD Using Recursion
Description: Find GCD using recursive Euclidean algorithm.
import [Link];

public class GCDRecursive {


public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

int result = gcd(a, b);


[Link]("GCD = " + result);
[Link]();
}
}
Output:
Enter first number: 48
Enter second number: 18
GCD = 6

Program 86: Reverse Number Using Recursion


Description: Reverse a number using recursion.
import [Link];

public class ReverseRecursive {


static int reversed = 0;

public static void reverse(int num) {


if (num == 0) {
return;
}
reversed = reversed * 10 + num % 10;

58
reverse(num / 10);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

reverse(num);
[Link]("Reversed number = " + reversed);
[Link]();
}
}
Output:
Enter a number: 12345
Reversed number = 54321

Program 87: Sum of Digits Using Recursion


Description: Calculate sum of digits using recursion.
import [Link];

public class SumDigitsRecursive {


public static int sumDigits(int num) {
if (num == 0) {
return 0;
}
return num % 10 + sumDigits(num / 10);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

int result = sumDigits(num);


[Link]("Sum of digits = " + result);
[Link]();
}
}
Output:
Enter a number: 1234

59
Sum of digits = 10

Program 88: Binary Search Using Recursion


Description: Implement binary search using recursion.
import [Link];

public class BinarySearchRecursive {


public static int binarySearch(int[] arr, int low, int high, int target) {
if (low > high) {
return -1;
}

int mid = low + (high - low) / 2;


if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearch(arr, mid + 1, high, target);
} else {
return binarySearch(arr, low, mid - 1, target);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter sorted array elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

[Link]("Enter element to search: ");


int target = [Link]();

int index = binarySearch(arr, 0, n - 1, target);


if (index != -1) {
[Link]("Element found at index " + index);
} else {
[Link]("Element not found");
}
[Link]();

60
}
}
Output:
Enter array size: 5
Enter sorted array elements:
10 20 30 40 50
Enter element to search: 30
Element found at index 2

Program 89: Check Palindrome Using Recursion


Description: Check if a string is palindrome using recursion.
import [Link];

public class PalindromeRecursive {


public static boolean isPalindrome(String str, int left, int right) {
if (left >= right) {
return true;
}
if ([Link](left) != [Link](right)) {
return false;
}
return isPalindrome(str, left + 1, right - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

boolean result = isPalindrome(str, 0, [Link]() - 1);


if (result) {
[Link](str + " is a palindrome");
} else {
[Link](str + " is not a palindrome");
}
[Link]();
}
}
Output:
Enter a string: radar
radar is a palindrome

61
Program 90: Tower of Hanoi
Description: Solve Tower of Hanoi problem using recursion.
import [Link];

public class TowerOfHanoi {


public static void solve(int n, char from, char to, char aux) {
if (n == 1) {
[Link]("Move disk 1 from " + from + " to " + to);
return;
}
solve(n - 1, from, aux, to);
[Link]("Move disk " + n + " from " + from + " to " + to);
solve(n - 1, aux, to, from);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter number of disks: ");
int n = [Link]();

[Link]("Tower of Hanoi solution:");


solve(n, 'A', 'C', 'B');
[Link]();
}
}
Output:
Enter number of disks: 3
Tower of Hanoi solution:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Section 8: Data Structures Basics


Program 91: Stack Using Array
Description: Implement basic stack operations.

62
import [Link];

class Stack {
private int[] arr;
private int top;
private int capacity;

public Stack(int size) {


arr = new int[size];
capacity = size;
top = -1;
}

public void push(int x) {


if (top == capacity - 1) {
[Link]("Stack Overflow");
return;
}
arr[++top] = x;
[Link](x + " pushed to stack");
}

public int pop() {


if (top == -1) {
[Link]("Stack Underflow");
return -1;
}
return arr[top--];
}

public void display() {


if (top == -1) {
[Link]("Stack is empty");
return;
}
[Link]("Stack: ");
for (int i = 0; i <= top; i++) {
[Link](arr[i] + " ");
}
[Link]();
}
}

public class StackDemo {


public static void main(String[] args) {
Stack stack = new Stack(5);

63
[Link](10);
[Link](20);
[Link](30);
[Link]();
[Link]("Popped: " + [Link]());
[Link]();
}
}
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
Stack: 10 20 30
Popped: 30
Stack: 10 20

Program 92: Queue Using Array


Description: Implement basic queue operations.
class Queue {
private int[] arr;
private int front, rear, capacity, size;

public Queue(int capacity) {


[Link] = capacity;
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}

public void enqueue(int x) {


if (size == capacity) {
[Link]("Queue is full");
return;
}
rear = (rear + 1) % capacity;
arr[rear] = x;
size++;
[Link](x + " enqueued");
}

public int dequeue() {

64
if (size == 0) {
[Link]("Queue is empty");
return -1;
}
int item = arr[front];
front = (front + 1) % capacity;
size--;
return item;
}

public void display() {


if (size == 0) {
[Link]("Queue is empty");
return;
}
[Link]("Queue: ");
for (int i = 0; i < size; i++) {
[Link](arr[(front + i) % capacity] + " ");
}
[Link]();
}
}

public class QueueDemo {


public static void main(String[] args) {
Queue queue = new Queue(5);
[Link](10);
[Link](20);
[Link](30);
[Link]();
[Link]("Dequeued: " + [Link]());
[Link]();
}
}
Output:
10 enqueued
20 enqueued
30 enqueued
Queue: 10 20 30
Dequeued: 10
Queue: 20 30

65
Program 93: Linked List Basic Operations
Description: Implement basic linked list operations.
class Node {
int data;
Node next;

Node(int data) {
[Link] = data;
[Link] = null;
}
}

class LinkedList {
Node head;

public void insert(int data) {


Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while ([Link] != null) {
temp = [Link];
}
[Link] = newNode;
}
[Link](data + " inserted");
}

public void display() {


if (head == null) {
[Link]("List is empty");
return;
}
Node temp = head;
[Link]("List: ");
while (temp != null) {
[Link]([Link] + " -> ");
temp = [Link];
}
[Link]("null");
}
}

66
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList();
[Link](10);
[Link](20);
[Link](30);
[Link]();
}
}
Output:
10 inserted
20 inserted
30 inserted
List: 10 -> 20 -> 30 -> null

Program 94: Binary Tree Traversals


Description: Implement inorder, preorder, and postorder traversals.
class TreeNode {
int data;
TreeNode left, right;

TreeNode(int data) {
[Link] = data;
left = right = null;
}
}

class BinaryTree {
TreeNode root;

public void inorder(TreeNode node) {


if (node == null) return;
inorder([Link]);
[Link]([Link] + " ");
inorder([Link]);
}

public void preorder(TreeNode node) {


if (node == null) return;
[Link]([Link] + " ");
preorder([Link]);
preorder([Link]);

67
}

public void postorder(TreeNode node) {


if (node == null) return;
postorder([Link]);
postorder([Link]);
[Link]([Link] + " ");
}
}

public class TreeDemo {


public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
[Link] = new TreeNode(1);
[Link] = new TreeNode(2);
[Link] = new TreeNode(3);
[Link] = new TreeNode(4);
[Link] = new TreeNode(5);

[Link]("Inorder: ");
[Link]([Link]);
[Link]();

[Link]("Preorder: ");
[Link]([Link]);
[Link]();

[Link]("Postorder: ");
[Link]([Link]);
}
}
Output:
Inorder: 4 2 5 1 3
Preorder: 1 2 4 5 3
Postorder: 4 5 2 3 1

Program 95: ArrayList Operations


Description: Perform basic ArrayList operations.
import [Link];

public class ArrayListDemo {


public static void main(String[] args) {

68
ArrayList<Integer> list = new ArrayList<>();

// Add elements
[Link](10);
[Link](20);
[Link](30);
[Link]("ArrayList: " + list);

// Get element
[Link]("Element at index 1: " + [Link](1));

// Remove element
[Link](1);
[Link]("After removing index 1: " + list);

// Size
[Link]("Size: " + [Link]());

// Contains
[Link]("Contains 30? " + [Link](30));
}
}
Output:
ArrayList: [10, 20, 30]
Element at index 1: 20
After removing index 1: [10, 30]
Size: 2
Contains 30? true

Program 96: HashMap Operations


Description: Perform basic HashMap operations.
import [Link];

public class HashMapDemo {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();

// Put elements
[Link]("One", 1);
[Link]("Two", 2);
[Link]("Three", 3);
[Link]("HashMap: " + map);

69
// Get value
[Link]("Value for 'Two': " + [Link]("Two"));

// Check key
[Link]("Contains 'One'? " + [Link]("One"));

// Remove
[Link]("Two");
[Link]("After removing 'Two': " + map);

// Size
[Link]("Size: " + [Link]());
}
}
Output:
HashMap: {One=1, Two=2, Three=3}
Value for 'Two': 2
Contains 'One'? true
After removing 'Two': {One=1, Three=3}
Size: 2

Program 97: HashSet Operations


Description: Perform basic HashSet operations.
import [Link];

public class HashSetDemo {


public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();

// Add elements
[Link](10);
[Link](20);
[Link](30);
[Link](20); // Duplicate
[Link]("HashSet: " + set);

// Contains
[Link]("Contains 20? " + [Link](20));

// Remove
[Link](20);

70
[Link]("After removing 20: " + set);

// Size
[Link]("Size: " + [Link]());
}
}
Output:
HashSet: [20, 10, 30]
Contains 20? true
After removing 20: [10, 30]
Size: 2

Program 98: Insertion Sort


Description: Sort an array using insertion sort.
import [Link];

public class InsertionSort {


public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22};

for (int i = 1; i < [Link]; i++) {


int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

[Link]("Sorted array: " + [Link](arr));


}
}
Output:
Sorted array: [12, 22, 25, 34, 64]

Program 99: Count Frequency of Elements


Description: Count frequency of each element in an array.

71
import [Link];

public class FrequencyCount {


public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};

HashMap<Integer, Integer> freq = new HashMap<>();


for (int num : arr) {
[Link](num, [Link](num, 0) + 1);
}

[Link]("Element frequencies:");
for (int key : [Link]()) {
[Link](key + " appears " + [Link](key) + " times");
}
}
}
Output:
Element frequencies:
1 appears 1 times
2 appears 2 times
3 appears 3 times
4 appears 4 times

Program 100: Find Missing Number in Array


Description: Find the missing number in an array containing 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 expectedSum = n * (n + 1) / 2;
int actualSum = 0;

for (int num : arr) {


actualSum += num;
}

int missing = expectedSum - actualSum;


[Link]("Missing number: " + missing);
}
}

72
Output:
Missing number: 3

Conclusion
This collection of 100 Java programs covers essential programming concepts from
basic fundamentals to data structures. Practice these programs to strengthen
your Java programming skills and prepare for interviews or exams.

Key Topics Covered:


• Basic I/O and arithmetic operations
• Control flow statements (if-else, loops, switch)
• Number system conversions
• String manipulation
• Mathematical algorithms (prime, factorial, Fibonacci, GCD, LCM)
• Array operations and sorting algorithms
• Recursion techniques
• Basic data structures (Stack, Queue, Linked List, Tree)
• Java Collections Framework

Tips for Learning:


1. Type the code yourself - Don’t copy-paste; typing helps muscle memory
2. Modify and experiment - Change values and see what happens
3. Understand the logic - Don’t just memorize; understand why it works
4. Practice regularly - Consistency is key to mastery
5. Debug your errors - Learn from mistakes and error messages
Happy Coding! �

73

You might also like