40 Java Programs For Practice

Here are 40 Java Basic Programs which you can practice to get knowledge :

  1. Hello World
    Title: Print “Hello, World!”
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Output:

Hello, World!
  1. Sum of Two Numbers
    Title: Add Two Numbers
public class AddNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 10;
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 15
  1. Find the Maximum Number
    Title: Maximum Number
public class MaximumNumber {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 10;
        int max = num1 > num2 ? num1 : num2;
        System.out.println("Maximum number: " + max);
    }
}

Output:

Maximum number: 10
  1. Check Even or Odd
    Title: Even or Odd
public class EvenOrOdd {
    public static void main(String[] args) {
        int num = 7;
        if (num % 2 == 0) {
            System.out.println(num + " is even.");
        } else {
            System.out.println(num + " is odd.");
        }
    }
}

Output:

7 is odd.
  1. Calculate Factorial
    Title: Factorial Calculation
public class Factorial {
    public static void main(String[] args) {
        int num = 5;
        int factorial = 1;
        for (int i = 1; i <= num; i++) {
            factorial *= i;
        }
        System.out.println("Factorial of " + num + ": " + factorial);
    }
}

Output:

Factorial of 5: 120
  1. Generate Fibonacci Series
    Title: Fibonacci Series
public class Fibonacci {
    public static void main(String[] args) {
        int count = 10;
        int num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series: " + num1 + ", " + num2);

        for (int i = 2; i < count; i++) {
            int sum = num1 + num2;
            System.out.print(", " + sum);
            num1 = num2;
            num2 = sum;
        }
        System.out.println();
    }
}

Output:

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
  1. Check Prime Number
    Title: Prime Number
public class PrimeNumber {
    public static void main(String[] args) {
        int num = 13;
        boolean isPrime = true;

        if (num <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= Math.sqrt(num); 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.");
        }
    }
}

Output:

13 is a prime number.
  1. Reverse a Number
    Title: Reverse Number
public class ReverseNumber {
    public static void main(String[] args) {
        int num = 12345;
        int reversed = 0;

        while (num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num /= 10;
        }

        System.out.println("Reversed number: " + reversed);
    }
}

Output:

Reversed number: 54321
  1. Calculate Area of a Circle
    Title: Area of a Circle
public class CircleArea {
    public static void main(String[] args) {
        double radius = 5.0;
        double area = Math.PI * radius * radius;
        System.out.println("Area of the circle: " + area);
    }
}

Output:

Area of the circle: 78.53981633974483
  1. Swap Two Numbers
    Title: Swap Numbers
public class SwapNumbers {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;

        System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);

        int temp = num1;
        num1 = num2;
        num2 = temp;

        System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
    }
}

Output:

Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 20, num2 = 10

  1. Check Leap Year
    Title: Leap Year
public class LeapYear {
    public static void main(String[] args) {
        int year = 2020;
        boolean isLeapYear = false;

        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    isLeapYear = true;
                }
            } else {
                isLeapYear = true;
            }
        }

        if (isLeapYear) {
            System.out.println(year + " is a leap year.");
        } else {
            System.out.println(year + " is not a leap year.");
        }
    }
}

Output:

2020 is a leap year.
  1. Calculate Power of a Number
    Title: Power Calculation
public class Power {
    public static void main(String[] args) {
        int base = 2;
        int exponent = 5;
        long result = 1;

        while (exponent != 0) {
            result *= base;
            --exponent;
        }

        System.out.println("Result: " + result);
    }
}

Output:

Result: 32
  1. Check Armstrong Number
    Title: Armstrong Number
public class ArmstrongNumber {
    public static void main(String[] args) {
        int number = 153;
        int originalNumber = number;
        int result = 0;
        int n = 0;

        while (originalNumber != 0) {
            originalNumber /= 10;
            ++n;
        }

        originalNumber = number;

        while (originalNumber != 0) {
            int remainder = originalNumber % 10;
            result += Math.pow(remainder, n);
            originalNumber /= 10;
        }

        if (result == number) {
            System.out.println(number + " is an Armstrong number.");
        } else {
            System.out.println(number + " is not an Armstrong number.");
        }
    }
}

Output:

153 is an Armstrong number.
  1. Check Palindrome Number
    Title: Palindrome Number
public class PalindromeNumber {
    public static void main(String[] args) {
        int number = 12321;
        int reversed = 0;
        int originalNumber = number;

        while (originalNumber != 0) {
            int remainder = originalNumber % 10;
            reversed = reversed * 10 + remainder;
            originalNumber /= 10;
        }

        if (number == reversed) {
            System.out.println(number + " is a palindrome number.");
        } else {
            System.out.println(number + " is not a palindrome number.");
        }
    }
}

Output:

12321 is a palindrome number.
  1. Calculate Average of Numbers
    Title: Average Calculation
public class Average {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 12, 15};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        double average = (double) sum / numbers.length;
        System.out.println("Average: " + average);
    }
}

Output:

Average: 9.8
  1. Find the Largest Element in an Array
    Title: Largest Element
public class LargestElement {
    public static void main(String[] args) {
        int[] numbers =
 {5, 7, 10, 12, 15};
        int largest = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > largest) {
                largest = numbers[i];
            }
        }
        System.out.println("Largest element: " + largest);
    }
}

Output:

Largest element: 15
  1. Find the Smallest Element in an Array
    Title: Smallest Element
public class SmallestElement {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 12, 15};
        int smallest = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < smallest) {
                smallest = numbers[i];
            }
        }
        System.out.println("Smallest element: " + smallest);
    }
}

Output:

Smallest element: 5
  1. Count the Number of Vowels in a String
    Title: Vowel Count
public class VowelCount {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int count = 0;
        str = str.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                count++;
            }
        }
        System.out.println("Number of vowels: " + count);
    }
}

Output:

Number of vowels: 3
  1. Reverse a String
    Title: Reverse String
public class ReverseString {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String reversed = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }

        System.out.println("Reversed string: " + reversed);
    }
}

Output:

Reversed string: !dlroW ,olleH
  1. Check if a String is a Palindrome
    Title: Palindrome String
public class PalindromeString {
    public static void main(String[] args) {
        String str = "madam";
        String reversed = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }

        if (str.equalsIgnoreCase(reversed)) {
            System.out.println(str + " is a palindrome string.");
        } else {
            System.out.println(str + " is not a palindrome string.");
        }
    }
}

Output:

madam is a palindrome string.

  1. Generate a Random Number
    Title: Random Number
import java.util.Random;

public class RandomNumber {
    public static void main(String[] args) {
        Random random = new Random();
        int randomNumber = random.nextInt(100);
        System.out.println("Random number: " + randomNumber);
    }
}

Output:

Random number: (a random number between 0 and 99)
  1. Check if a Number is a Perfect Number
    Title: Perfect Number
public class PerfectNumber {
    public static void main(String[] args) {
        int number = 28;
        int sum = 0;
        for (int i = 1; i <= number / 2; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }
        if (sum == number) {
            System.out.println(number + " is a perfect number.");
        } else {
            System.out.println(number + " is not a perfect number.");
        }
    }
}

Output:

28 is a perfect number.
  1. Find the GCD (Greatest Common Divisor) of Two Numbers
    Title: GCD Calculation
public class GCD {
    public static void main(String[] args) {
        int num1 = 36;
        int num2 = 48;
        int gcd = 1;
        for (int i = 1; i <= num1 && i <= num2; i++) {
            if (num1 % i == 0 && num2 % i == 0) {
                gcd = i;
            }
        }
        System.out.println("GCD of " + num1 + " and " + num2 + ": " + gcd);
    }
}

Output:

GCD of 36 and 48: 12
  1. Convert Decimal to Binary
    Title: Decimal to Binary Conversion
public class DecimalToBinary {
    public static void main(String[] args) {
        int decimalNumber = 25;
        String binary = "";

        while (decimalNumber > 0) {
            binary = (decimalNumber % 2) + binary;
            decimalNumber /= 2;
        }

        System.out.println("Binary representation: " + binary);
    }
}

Output:

Binary representation: 11001
  1. Convert Binary to Decimal
    Title: Binary to Decimal Conversion
public class BinaryToDecimal {
    public static void main(String[] args) {
        String binary = "11001";
        int decimalNumber = 0;
        for (int i = 0; i < binary.length(); i++) {
            int digit = binary.charAt(i) - '0';
            decimalNumber = decimalNumber * 2 + digit;
        }
        System.out.println("Decimal representation: " + decimalNumber);
    }
}

Output:

Decimal representation: 25
  1. Calculate the Area of a Triangle
    Title: Triangle Area
public class TriangleArea {
    public static void main(String[] args) {
        double base = 5.0;
        double height = 8.0;
        double area = 0.5 * base * height;
        System.out.println("Area of the triangle: " + area);
    }
}

Output:

Area of the triangle: 20.0
  1. Check if a Number is a Prime Number using a Function
    Title: Prime Number (Function)
public class PrimeNumber {
    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        int number = 17;
        if (isPrime(number)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }
    }
}

Output:

17 is a prime number.
  1. Calculate the Factorial of a Number using a Function
    Title: Factorial Calculation (Function)
public class Factorial {
    public static int factorial(int num) {
        int result = 1;
        for (int i = 1; i <= num; i++) {
            result *= i;
        }
        return result;
    }
    public static void main(String[] args) {
        int number = 5;
        int factorial = factorial(number);
        System.out.println("Factorial of " + number + ": " + factorial);
    }
}

Output:

Factorial of 5: 120
  1. Generate Fibonacci Series
    Title: Fibonacci Series
public class FibonacciSeries {
    public static void main(String[] args) {
        int count = 10;
        int num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series: " + num1 + ", " + num2);
        for (int i = 2; i < count; i++) {
            int nextNum = num1 + num2;
            System.out.print(", " + nextNum);
            num1 = num2;
            num2 = nextNum;
        }
        System.out.println();
    }
}

Output:

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
  1. Check if Two Strings are Anagrams
    Title: Anagram Strings
import java.util.Arrays;

public class AnagramStrings {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        if (areAnagrams(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

Output:

listen and silent are anagrams.

  1. Find the Sum of Natural Numbers
    Title: Sum of Natural Numbers
public class SumOfNaturalNumbers {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("Sum of natural numbers from 1 to " + n + ": " + sum);
    }
}

Output:

Sum of natural numbers from 1 to 10: 55
  1. Calculate the Average of an Array
    Title: Array Average
public class ArrayAverage {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 12, 15};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        double average = (double) sum / numbers.length;
        System.out.println("Average of the array: " + average);
    }
}

Output:

Average of the array: 9.8
  1. Check if a Number is a Perfect Square
    Title: Perfect Square
public class PerfectSquare {
    public static void main(String[] args) {
        int number = 16;

        if (Math.sqrt(number) % 1 == 0) {
            System.out.println(number + " is a perfect square.");
        } else {
            System.out.println(number + " is not a perfect square.");
        }
    }
}

Output:

16 is a perfect square.
  1. Find the Factorial of a Number using Recursion
    Title: Factorial Calculation (Recursion)
public class Factorial {
    public static int factorial(int num) {
        if (num == 0 || num == 1) {
            return 1;
        }

        return num * factorial(num - 1);
    }

    public static void main(String[] args) {
        int number = 5;
        int factorial = factorial(number);
        System.out.println("Factorial of " + number + ": " + factorial);
    }
}

Output:

Factorial of 5: 120
  1. Reverse an Array
    Title: Reverse Array
import java.util.Arrays;
public class ReverseArray {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 12, 15};
        System.out.println("Original Array: " + Arrays.toString(numbers));
        for (int i = 0; i < numbers.length / 2; i++) {
            int temp = numbers[i];
            numbers[i] = numbers[numbers.length - 1 - i];
            numbers[numbers.length - 1 - i] = temp;
        }
        System.out.println("Reversed Array: " + Arrays.toString(numbers));
    }
}

Output:

Original Array: [5, 7, 10, 12, 15]
Reversed Array: [15, 12, 10, 7, 5]
  1. Count the Frequency of Each Element in an Array
    Title: Element Frequency
import java.util.HashMap;
import java.util.Map;

public class ElementFrequency {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 7, 12, 15, 7};
        Map<Integer, Integer> frequencyMap = new HashMap<>();

        for (int number : numbers) {
            frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            System.out.println("Frequency of " + entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

Frequency of 5: 1
Frequency of 7: 3
Frequency of 10: 1
Frequency of 12: 1
Frequency of 15: 1
  1. Find the Second Largest Element in an Array
    Title: Second Largest Element
public class SecondLargestElement {
    public static void main(String[] args) {
        int[] numbers = {5, 7, 10, 12, 15};
        int largest = numbers[0];
        int secondLargest = Integer.MIN_VALUE;

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > largest) {
                secondLargest = largest;
                largest = numbers[i];
            } else if (numbers[i] > secondLargest && numbers[i] != largest) {
                secondLargest = numbers[i];
            }
        }

        System.out.println("Second largest element: " + secondLargest);
    }
}

Output:

Second largest element: 12
  1. Merge Two Arrays and Sort the Resulting Array
    Title: Merge and Sort Arrays
import java.util.Arrays;

public class MergeAndSortArrays {
    public static void main(String[] args) {
        int[] arr1 = {2, 4, 6, 8};
        int[] arr2 = {1, 3, 5, 7};

        int[] mergedArray = new int[arr1.length + arr2.length];
        System.arraycopy(arr1, 0, mergedArray, 0, arr1.length);
        System.arraycopy(arr2, 0, mergedArray, arr1.length, arr2.length);

        Arrays.sort(mergedArray);

        System.out.println("Merged and Sorted Array: " + Arrays.toString(mergedArray));
    }
}

Output:

Merged and Sorted Array: [1, 2, 3, 4, 5, 6, 7, 8]
  1. Check if a Year is a Leap Year
    Title: Leap Year
public class LeapYear {
    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. Calculate the Power of a Number
    Title: Power Calculation
public class Power {
    public static double power(double base, int exponent) {
        double result = 1;

        for (int i = 1; i <= Math.abs(exponent); i++) {
            result *= base;
        }

        if (exponent < 0) {
            result = 1 / result;
        }

        return result;
    }

    public static void main(String[] args) {
        double base = 2;
        int exponent = 5;
        double powerResult = power(base, exponent);
        System.out.println(base + " raised to the power of " + exponent

 + ": " + powerResult);
    }
}

Output:

2.0 raised to the power of 5: 32.0

We have seen 40 Java Programs which will help you to get good knowledge of basic programming.

Happy Learning.

Leave a Reply

Your email address will not be published. Required fields are marked *