The Most Important 50 Java Programs for Beginners

By | August 4, 2023

Master Java with Ease: Top 50 Java Programs for Beginners!

Read, Study and practice these “The Most Important 50 Java Programs for Beginners” programs to be a good programmer in Java programming.

1. Write down a Java Program to input a number and display its square.

The Most Important 50 Java Programs for Beginners

The Most Important 50 Java Programs for Beginners


import java.util.Scanner;

public class SquareNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        int square = num * num;
        System.out.println("Square of " + num + " is: " + square);
    }
}

Explanation of Code

1. We start by importing the `Scanner` class from the `java.util` package. The `Scanner` class allows us to read user input from the console.

2. We create the `SquareNumber` class with the `main` method, which is the entry point of the program.

3. Inside the `main` method, we create a new `Scanner` object called `scanner` to read user input.

4. We prompt the user to enter a number by displaying the message “Enter a number: ” using `System.out.print()`.

5. We read the user’s input as an integer using the `nextInt()` method of the `Scanner` class and store it in the variable `num`.

6. We calculate the square of the number by multiplying it by itself and store the result in the variable `square`.

7. Finally, we display the square of the number using `System.out.println()` with an appropriate message. For example, if the user enters the number 5, the program will display “Square of 5 is: 25”.

The program takes the user’s input, calculates the square, and then outputs the result on the console.

2. Write a Java Program to input two numbers and calculate sum.

Source Code


import java.util.Scanner;

public class SumCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}
Output
Enter the first number: 10
Enter the second number: 20 
Sum: 30

Explanation:

  1. We start by importing the Scanner class from the java.util package. The Scanner class allows us to read user input from the console.
  2. We create the SumCalculator class with the main method, which is the entry point of the program.
  3. Inside the main method, we create a new Scanner object called scanner to read user input.
  4. We prompt the user to enter the first number by displaying the message “Enter the first number: ” using System.out.print().
  5. We read the user’s input for the first number as an integer using the nextInt() method of the Scanner class and store it in the variable num1.
  6. We prompt the user to enter the second number by displaying the message “Enter the second number: ” using System.out.print().
  7. We read the user’s input for the second number as an integer using the nextInt() method of the Scanner class and store it in the variable num2.
  8. We calculate the sum of the two numbers by adding num1 and num2 together, and store the result in the variable sum.
  9. Finally, we display the sum of the two numbers using System.out.println() with an appropriate message. For example, if the user enters the first number as 10 and the second number as 20, the program will display “Sum: 30”.

The program takes two numbers as input, calculates their sum, and then outputs the result on the console.

3. Temperature Conversion Program-1. Write a program in Java to input temperature in Centigrade and convert it into Fahrenheit.

import java.util.Scanner;

public class TemperatureConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter temperature in Centigrade: ");
        double celsius = scanner.nextDouble();
        double fahrenheit = (celsius * 9 / 5) + 32;
        System.out.println("Temperature in Fahrenheit: " + fahrenheit);
    }
}
Output:
The program takes the temperature in Centigrade as input, converts it to Fahrenheit using the conversion formula, and then outputs the result on the console.
Enter temperature in Centigrade: 25
Temperature in Fahrenheit: 77.0

4. Temperature Conversion Program 2: Write a Java Program to input temperature in Fahrenheit and convert it into Centigrade.

import java.util.Scanner;

public class FahrenheitToCentigrade {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter temperature in Fahrenheit: ");
        double fahrenheit = scanner.nextDouble();
        double celsius = (fahrenheit - 32) * 5 / 9;
        System.out.println("Temperature in Centigrade: " + celsius);
    }
}

Output
The program takes the temperature in Fahrenheit as input, converts it to Centigrade using the conversion formula, and then outputs the result on the console.

Enter temperature in Fahrenheit: 77
Temperature in Centigrade: 25.0

5. Write a Java Program to input a number and check it for Even or Odd.


import java.util.Scanner;

public class EvenOrOddChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        if (number % 2 == 0) {
            System.out.println(number + " is an even number.");
        } else {
            System.out.println(number + " is an odd number.");
        }
    }
}

Output

Enter a number: 15
15 is an odd number.

Explanation:

  1. We start by importing the Scanner class from the java.util package. The Scanner class allows us to read user input from the console.
  2. We create the EvenOrOddChecker class with the main method, which is the entry point of the program.
  3. Inside the main method, we create a new Scanner object called scanner to read user input.
  4. We prompt the user to enter a number by displaying the message “Enter a number: ” using System.out.print().
  5. We read the user’s input for the number as an integer using the nextInt() method of the Scanner class and store it in the variable number.
  6. We check whether the number is even or odd using the condition number % 2 == 0. The % operator calculates the remainder of the division of number by 2. If the remainder is 0, the number is even; otherwise, it is odd.
  7. Finally, we display the result using System.out.println() with an appropriate message. For example, if the user enters 5, the program will display “5 is an odd number.” If the user enters 10, the program will display “10 is an even number.”

6. Write a Java program to input a number. Check it for Positive , Negative or Zero.


import java.util.Scanner;

public class NumberTypeChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        if (number > 0) {
            System.out.println(number + " is a positive number.");
        } else if (number < 0) {
            System.out.println(number + " is a negative number.");
        } else {
            System.out.println("The number is zero.");
        }
    }
}

Output
Enter a number: -5
-5 is a negative number.

7. Write a Java program using switch statement. Input a number between 1 to 7. Display the name of Day.


import java.util.Scanner;

public class DayNameSwitch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number between 1 to 7: ");
        int dayNumber = scanner.nextInt();

        String dayName;

        switch (dayNumber) {
            case 1:
                dayName = "Sunday";
                break;
            case 2:
                dayName = "Monday";
                break;
            case 3:
                dayName = "Tuesday";
                break;
            case 4:
                dayName = "Wednesday";
                break;
            case 5:
                dayName = "Thursday";
                break;
            case 6:
                dayName = "Friday";
                break;
            case 7:
                dayName = "Saturday";
                break;
            default:
                dayName = "Invalid input";
                break;
        }

        System.out.println("Day: " + dayName);
    }
}
Output:
Enter a number between 1 to 7: 3
Day: Tuesday
Output:
Enter a number between 1 to 7: 9
Day: Invalid input

Explanation:

  1. We create the DayNameSwitch class with the main method, which is the entry point of the program.
  2. Inside the main method, we create a new Scanner object called scanner to read user input.
  3. We prompt the user to enter a number between 1 to 7 by displaying the message “Enter a number between 1 to 7: ” using System.out.print().
  4. We read the user’s input for the day number as an integer using the nextInt() method of the Scanner class and store it in the variable dayNumber.
  5. We use the switch statement to determine the name of the day based on the input dayNumber.
  6. Each case represents a possible value of dayNumber, and we assign the corresponding day name to the variable dayName.
  7. If the input dayNumber does not match any of the cases (i.e., it’s not between 1 to 7), the default case is executed, and dayName is set to “Invalid input”.
  8. Finally, we display the name of the day using System.out.println() with the appropriate message. For example, if the user enters 3, the program will display “Day: Tuesday”.

The program takes a number as input, uses a switch statement to determine the name of the day, and then outputs the result on the console.

8. Write a Java program to input a year, check whether the given year is a Leap year or not.


import java.util.Scanner;

public class LeapYearChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();

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

    public static boolean isLeapYear(int year) {
        // A leap year is either divisible by 4 but not by 100,
        // or divisible by 400.
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
Output
Enter a year: 1900
1900 is not a Leap Year.

Enter a year: 2000
2000 is a Leap Year.

Enter a year: 2000
2000 is a Leap Year.

Enter a year: 2023
2023 is not a Leap Year.

9.  Write a Java Program to input three numbers and find the maximum number using Math class.


import java.util.Scanner;

public class MaxNumberFinder {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();
        System.out.print("Enter the third number: ");
        int num3 = scanner.nextInt();

        int maxNumber = Math.max(num1, Math.max(num2, num3));

        System.out.println("The maximum number is: " + maxNumber);
    }
}
Output
Enter the first number: 10
Enter the second number: 25
Enter the third number: 15
The maximum number is: 25
In this example, the user enters three numbers: 10, 25, and 15. The program then finds the maximum number among these three using the Math.max() method. Since 25 is the largest among them, the program outputs "The maximum number is: 25".

10. Write a Java Program to input three numbers and find the minimum number using if else if.


import java.util.Scanner;

public class MinNumberFinder {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();
        System.out.print("Enter the third number: ");
        int num3 = scanner.nextInt();

        int minNumber;

        if (num1 <= num2 && num1 <= num3) {
            minNumber = num1;
        } else if (num2 <= num1 && num2 <= num3) {
            minNumber = num2;
        } else {
            minNumber = num3;
        }

        System.out.println("The minimum number is: " + minNumber);
    }
}
Output
Enter the first number: 10
Enter the second number: 5
Enter the third number: 15
The minimum number is: 5

11. Write a Java program to find the average of 10 numbers using a while loop.


import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 0;
        int sum = 0;

        while (count < 10) {
            System.out.print("Enter number " + (count + 1) + ": ");
            int number = scanner.nextInt();
            sum += number;
            count++;
        }

        double average = (double) sum / 10;
        System.out.println("Average of the 10 numbers is: " + average);
    }
}
Output:
Enter number 1: 15
Enter number 2: 25
Enter number 3: 10
Enter number 4: 8
Enter number 5: 12
Enter number 6: 30
Enter number 7: 7
Enter number 8: 18
Enter number 9: 22
Enter number 10: 5
Average of the 10 numbers is: 15.2

12. Write a Java program to find the average of 5 real numbers using a for loop.


import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int totalNumbers = 5;
        double sum = 0;

        for (int i = 1; i <= totalNumbers; i++) {
            System.out.print("Enter number " + i + ": ");
            double number = scanner.nextDouble();
            sum += number;
        }

        double average = sum / totalNumbers;
        System.out.println("Average of the 5 numbers is: " + average);
    }
}
Output:
Enter number 1: 10.5
Enter number 2: 20.8
Enter number 3: 15.3
Enter number 4: 12.7
Enter number 5: 18.9
Average of the 5 numbers is: 15.64

13. Write a Java program to show total and average of 15 real numbers using do while loop.


import java.util.Scanner;

public class TotalAndAverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int totalNumbers = 15;
        int count = 0;
        double sum = 0;

        do {
            System.out.print("Enter number " + (count + 1) + ": ");
            double number = scanner.nextDouble();
            sum += number;
            count++;
        } while (count < totalNumbers);

        double average = sum / totalNumbers;
        System.out.println("Total: " + sum);
        System.out.println("Average: " + average);
    }
}
Output:
Enter number 1: 10.5
Enter number 2: 20.8
Enter number 3: 15.3
Enter number 4: 12.7
Enter number 5: 18.9
Enter number 6: 25.0
Enter number 7: 14.6
Enter number 8: 9.3
Enter number 9: 17.2
Enter number 10: 22.1
Enter number 11: 11.8
Enter number 12: 16.5
Enter number 13: 19.7
Enter number 14: 13.4
Enter number 15: 21.6
Total: 239.4
Average: 15.96

14. Write a Java program to input N numbers and show their sum and average using while loop.


import java.util.Scanner;

public class SumAndAverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the value of N: ");
        int N = scanner.nextInt();

        int count = 0;
        int sum = 0;

        while (count < N) {
            System.out.print("Enter number " + (count + 1) + ": ");
            int number = scanner.nextInt();
            sum += number;
            count++;
        }

        double average = (double) sum / N;

        System.out.println("Sum of the numbers is: " + sum);
        System.out.println("Average of the numbers is: " + average);
    }
}
Output:
Enter the value of N: 5
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Sum of the numbers is: 150
Average of the numbers is: 30.0

15. Write a Java program to calculate sum of numbers using Sentinel value concept. The user should input a number, as long as the user does not enter -1. At the end show count and sum and of all numbers except -1.


import java.util.Scanner;

public class SentinelSumCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int sum = 0;
        int count = 0;

        System.out.println("Enter numbers (Enter -1 to stop):");

        while (true) {
            int number = scanner.nextInt();

            if (number == -1) {
                break;
            }

            sum += number;
            count++;
        }

        System.out.println("Count of numbers entered: " + count);
        System.out.println("Sum of numbers (excluding -1): " + sum);
    }
}
Output:
Enter numbers (Enter -1 to stop):
10
25
15
7
-1
Count of numbers entered: 4
Sum of numbers (excluding -1): 57

16. Write a Java program to input starting and ending number. Show all even numbers and their sum between starting and ending number.


import java.util.Scanner;

public class EvenNumbersAndSum {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the starting number: ");
        int start = scanner.nextInt();

        System.out.print("Enter the ending number: ");
        int end = scanner.nextInt();

        

        System.out.println("Even numbers between " + start + " and " + end + ":");
        int sum = 0;

        for (int num = start; num <= end; num++) {
            if (num % 2 == 0) {
                System.out.print(num + " ");
                sum += num;
            }
        }

        System.out.println("\nSum of even numbers between " + start + " and " + end + ": " + sum);
    }
}
Output:
Enter the starting number: 5
Enter the ending number: 15
Even numbers between 5 and 15:
6 8 10 12 14 
Sum of even numbers between 5 and 15: 50

17. Write a Java program to input a number , display its table (Multiplication table).


import java.util.Scanner;

public class MultiplicationTable {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        
        System.out.println("Multiplication table of " + number + ":");
        for (int i = 1; i <= 10; i++) {
            int result = number * i;
            System.out.println(number + " x " + i + " = " + result);
        }
    }
}
Output:
Enter a number: 7
Multiplication table of 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

18. Write a Java Program to input a number. Display its Factorial.


import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        
        if (number < 0) {
            System.out.println("Factorial is not defined for negative numbers.");
        } else {
            long factorial = 1;
            for (int i = 2; i <= number; i++) {
                factorial *= i;
            }
            System.out.println("Factorial of " + number + " is: " + factorial);
        }
    }
}
Output:
Enter a number: 5
Factorial of 5 is: 120

19. Write a Java Program to input a number. Display its Factorial using user defined Method.


import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();


        long factorial = calculateFactorial(number);

        System.out.println("Factorial of " + number + " is: " + factorial);
    }

    public static long calculateFactorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
        }

        if (n == 0 || n == 1) {
            return 1;
        }

        long result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }
}
Output:
Enter a number: 5
Factorial of 5 is: 120

In this example, the user entered the number 5. The program then calculated the factorial of 5 using the method calculateFactorial() which is 5 x 4 x 3 x 2 x 1 = 120, and displayed the result as the output. 

20. Write a Java program to input number of terms and display these terms for Fibonacci series.


import java.util.Scanner;

public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms in the Fibonacci series: ");
        int numTerms = scanner.nextInt();


        System.out.println("Fibonacci series with " + numTerms + " terms:");
        int firstTerm = 0;
        int secondTerm = 1;

        if (numTerms >= 1) {
            System.out.print(firstTerm);
        }
        
        for (int i = 2; i <= numTerms; i++) {
            System.out.print(", " + secondTerm);
            int nextTerm = firstTerm + secondTerm;
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }

        System.out.println();
    }
}
Output:
Enter the number of terms in the Fibonacci series: 10
Fibonacci series with 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Enter the number of terms in the Fibonacci series: 5
Fibonacci series with 5 terms:
0, 1, 1, 2, 3

21. Write a Java program to input two numbers. display GCD.


import java.util.Scanner;

public class GCD {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();


        int gcd = 1;
        int smaller = (num1 < num2) ? num1 : num2;

        for (int i = 1; i <= smaller; i++) {
            if (num1 % i == 0 && num2 % i == 0) {
                gcd = i;
            }
        }

        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
    }
}
Output:
Enter the first number: 48
Enter the second number: 18
GCD of 48 and 18 is: 6

Enter the first number: 27
Enter the second number: 9
GCD of 27 and 9 is: 9

Enter the first number: 21
Enter the second number: 14
GCD of 21 and 14 is: 7

22. Java Program to input a number and display its reverse number.


import java.util.Scanner;

public class ReverseNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the reverse of the number
        int reversedNumber = 0;
        while (number != 0) {
            int lastDigit = number % 10;
            reversedNumber = reversedNumber * 10 + lastDigit;
            number /= 10;
        }

        // Display the reverse of the number
        System.out.println("The reverse of the entered number is: " + reversedNumber);

        
    }
}
Output:
Enter a number: 12345
The reverse of the entered number is: 54321

23. Java program to input a number and count its digits.


import java.util.Scanner;

public class CountDigits {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the number of digits in the number
        int count = countDigits(number);

        // Display the result
        System.out.println("The number of digits in the entered number is: " + count);

    }

    public static int countDigits(int number) {
        if (number == 0) {
            return 1;
        }

        int count = 0;
        while (number != 0) {
            count++;
            number /= 10;
        }

        return count;
    }
}
Output:
Enter a number: 123456
The number of digits in the entered number is: 6

24. Java program to input a number and find sum of digits.


import java.util.Scanner;

public class SumOfDigits {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the sum of digits in the number
        int sum = calculateSumOfDigits(number);

        // Display the result
        System.out.println("The sum of digits in the entered number is: " + sum);

    }

    public static int calculateSumOfDigits(int number) {
        int sum = 0;

        while (number != 0) {
            int lastDigit = number % 10;
            sum += lastDigit;
            number /= 10;
        }

        return sum;
    }
}
Output
Enter a number: 4567
The sum of digits in the entered number is: 22

25. Java program to input a number and check it for Armstrong number.


An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or pluperfect number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

For example:
153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
----
import java.util.Scanner;

public class ArmstrongNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Check if the number is an Armstrong number
        if (isArmstrongNumber(number)) {
            System.out.println(number + " is an Armstrong number.");
        } else {
            System.out.println(number + " is not an Armstrong number.");
        }

    }

    public static boolean isArmstrongNumber(int number) {
        int originalNumber = number;
        int numberOfDigits = String.valueOf(number).length();
        int sum = 0;

        while (number != 0) {
            int digit = number % 10;
            sum += Math.pow(digit, numberOfDigits);
            number /= 10;
        }

        return sum == originalNumber;
    }
}
output:

Enter a number: 153
153 is an Armstrong number.


Enter a number: 123
123 is not an Armstrong number.

Enter a number: 370
370 is an Armstrong number.


26. Java program to check whether the given integer is a prime number or not.


import java.util.Scanner;

public class PrimeNumberCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Check if the number is a prime number
        if (isPrime(number)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }

    }

    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }

        // A prime number is divisible only by 1 and itself.
        // So we check if the number is divisible by any number from 2 to square root of the number.
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}
Output:
Enter a number: 17
17 is a prime number.

Enter a number: 0
0 is not a prime number.

Enter a number: 1
1 is not a prime number.

Enter a number: 100
100 is not a prime number.

27. Java program to show all prime numbers between 1 to N.


import java.util.Scanner;

public class PrimeNumbersInRange {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the value of N from the user
        System.out.print("Enter the value of N: ");
        int N = scanner.nextInt();

        // Display prime numbers between 1 and N
        System.out.println("Prime numbers between 1 and " + N + " are:");
        for (int i = 2; i <= N; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }

    }

    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}

Output:
Enter the value of N: 30
Prime numbers between 1 and 30 are:
2 3 5 7 11 13 17 19 23 29

28. Java program to show, count and add all prime numbers between 1 to N.


import java.util.Scanner;

public class PrimeNumbersCountAndSum {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the value of N from the user
        System.out.print("Enter the value of N: ");
        int N = scanner.nextInt();

        // Initialize variables to store count and sum
        int count = 0;
        int sum = 0;

        // Display, count, and add prime numbers between 1 and N
        System.out.println("Prime numbers between 1 and " + N + " are:");
        for (int i = 2; i <= N; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
                count++;
                sum += i;
            }
        }

        // Display the count and sum
        System.out.println("\nTotal prime numbers: " + count);
        System.out.println("Sum of prime numbers: " + sum);

    }

    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}
Output:
Enter the value of N: 30
Prime numbers between 1 and 30 are:
2 3 5 7 11 13 17 19 23 29
Total prime numbers: 10
Sum of prime numbers: 129

29. Java program to show all prime numbers between starting number N1 to ending number N2.


import java.util.Scanner;

public class PrimeNumbersInRange {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the value of N1 and N2 from the user
        System.out.print("Enter the starting number (N1): ");
        int N1 = scanner.nextInt();

        System.out.print("Enter the ending number (N2): ");
        int N2 = scanner.nextInt();

        // Display prime numbers between N1 and N2
        System.out.println("Prime numbers between " + N1 + " and " + N2 + " are:");
        for (int i = N1; i <= N2; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }

    }

    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}
Output:
Enter the starting number (N1): 100
Enter the ending number (N2): 120
Prime numbers between 100 and 120 are:
101 103 107 109 113 

30. Java program to input a number. Find its factorial by recursion ( recursive function ).


import java.util.Scanner;

public class FactorialRecursive {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number from the user
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the factorial using recursion
        long factorial = calculateFactorial(number);

        // Display the factorial
        System.out.println("Factorial of " + number + " is: " + factorial);

    }

    public static long calculateFactorial(int number) {
        if (number == 0 || number == 1) {
            return 1;
        } else {
            return number * calculateFactorial(number - 1);
        }
    }
}

Output:
Enter a number: 5
Factorial of 5 is: 120

31. Java program to find GCD of two numbers by recursion.


import java.util.Scanner;

public class GCDRecursive {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the two numbers from the user
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Calculate and display the GCD using recursion
        int gcd = findGCD(num1, num2);
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);

    }

    public static int findGCD(int a, int b) {
        if (b == 0) {
            return a;
        } else {
            return findGCD(b, a % b);
        }
    }
}
Output:
Enter the first number: 45
Enter the second number: 63
GCD of 45 and 63 is: 9

32. Java program to calculate power of a number n^p using recursion.


import java.util.Scanner;

public class PowerRecursive {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the values of n and p from the user
        System.out.print("Enter the value of n: ");
        int n = scanner.nextInt();

        System.out.print("Enter the value of p: ");
        int p = scanner.nextInt();

        // Calculate and display n^p using recursion
        long result = calculatePower(n, p);
        System.out.println(n + " raised to the power " + p + " is: " + result);

    }

    public static long calculatePower(int n, int p) {
        if (p == 0) {
            return 1;
        } else {
            return n * calculatePower(n, p - 1);
        }
    }
}
Output:
Enter the value of n: 2
Enter the value of p: 5
2 raised to the power 5 is: 32

33. Java program to find LCM of two numbers.


import java.util.Scanner;

public class LCMCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the two numbers from the user
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Calculate and display the LCM
        int lcm = findLCM(num1, num2);
        System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);

    }

    public static int findLCM(int a, int b) {
        return (a * b) / findGCD(a, b);
    }

    public static int findGCD(int a, int b) {
        if (b == 0) {
            return a;
        } else {
            return findGCD(b, a % b);
        }
    }
}
Output:
Enter the first number: 12
Enter the second number: 18
LCM of 12 and 18 is: 36

34. Java program to input 5 numbers in array and show sum and average.


import java.util.Scanner;

public class ArraySumAndAverage {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Create an array to store 5 numbers
        int[] numbers = new int[5];

        // Input 5 numbers from the user and store them in the array
        for (int i = 0; i < 5; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            numbers[i] = scanner.nextInt();
        }

        // Calculate the sum and average of the numbers
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        double average = (double) sum / 5;

        // Display the sum and average
        System.out.println("Sum of the numbers: " + sum);
        System.out.println("Average of the numbers: " + average);

    }
}
Output:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Sum of the numbers: 150
Average of the numbers: 30.0

35. Java program to input 10 numbers in array. Show all even numbers their count and sum.


import java.util.Scanner;

public class ArrayEvenNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Create an array to store 10 numbers
        int[] numbers = new int[10];

        // Input 10 numbers from the user and store them in the array
        for (int i = 0; i < 10; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            numbers[i] = scanner.nextInt();
        }

        // Display all the even numbers, their count, and sum
        int count = 0;
        int sum = 0;
        System.out.print("Even numbers in the array: ");
        for (int num : numbers) {
            if (num % 2 == 0) {
                System.out.print(num + " ");
                count++;
                sum += num;
            }
        }

        // Display the count and sum of even numbers
        System.out.println("\nCount of even numbers: " + count);
        System.out.println("Sum of even numbers: " + sum);

    }
}
Output:
Enter number 1: 5
Enter number 2: 10
Enter number 3: 15
Enter number 4: 20
Enter number 5: 25
Enter number 6: 30
Enter number 7: 35
Enter number 8: 40
Enter number 9: 45
Enter number 10: 50
Even numbers in the array: 10 20 30 40 50 
Count of even numbers: 5
Sum of even numbers: 150

 

36. Java program to input 10 numbers in array. Find maximum number.


import java.util.Scanner;

public class FindMaxNumberInArray {
    public static void main(String[] args) {
        int[] numbers = new int[10];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 10 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 10; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Finding the maximum number in the array
        int max = numbers[0];
        for (int i = 1; i < 10; i++) { if (numbers[i] > max) {
                max = numbers[i];
            }
        }

        System.out.println("The maximum number is: " + max);

        
    }
}
Output:
Enter 10 numbers:
5
10
2
15
7
1
20
8
13
3
The maximum number is: 20

37. Java program to input 5 numbers and find minimum and maximum number in array.


import java.util.Scanner;

public class FindMinMaxNumbersInArray {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Finding the minimum and maximum numbers in the array
        int min = numbers[0];
        int max = numbers[0];
        for (int i = 1; i < 5; i++) {
            if (numbers[i] < min) { min = numbers[i]; } if (numbers[i] > max) {
                max = numbers[i];
            }
        }

        System.out.println("The minimum number is: " + min);
        System.out.println("The maximum number is: " + max);

        // Close the scanner
    }
}
Output:
Enter 5 numbers:
12
5
8
20
3
The minimum number is: 3
The maximum number is: 20

38. Java program to input 5 numbers in array and find second smallest number without sorting.


import java.util.Scanner;

public class FindSecondSmallestInArray {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Finding the second smallest number in the array
        int smallest = Integer.MAX_VALUE;
        int secondSmallest = Integer.MAX_VALUE;

        for (int i = 0; i < 5; i++) {
            if (numbers[i] < smallest) {
                secondSmallest = smallest;
                smallest = numbers[i];
            } else if (numbers[i] < secondSmallest && numbers[i] != smallest) {
                secondSmallest = numbers[i];
            }
        }

        if (secondSmallest != Integer.MAX_VALUE) {
            System.out.println("The second smallest number is: " + secondSmallest);
        } else {
            System.out.println("There is no second smallest number.");
        }

        
    }
}
Output:
Enter 5 numbers:
15
8
20
10
15
The second smallest number is: 10

39. Java program to input 5 numbers in array find second largest number without sorting.


import java.util.Scanner;

public class FindSecondLargestInArray {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Finding the second largest number in the array
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

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

        if (secondLargest != Integer.MIN_VALUE) {
            System.out.println("The second largest number is: " + secondLargest);
        } else {
            System.out.println("There is no second largest number.");
        }

        
    }
}
Output:
Enter 5 numbers:
25
10
15
20
25
The second largest number is: 20

40. Java program to input 5 numbers and sort in ascending order using bubble sort.


import java.util.Scanner;

public class BubbleSortAscending {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Bubble Sort Algorithm (Ascending Order)
        for (int i = 0; i < 5 - 1; i++) {
            for (int j = 0; j < 5 - i - 1; j++) { if (numbers[j] > numbers[j + 1]) {
                    // Swap numbers[j] and numbers[j+1]
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }

        // Printing the sorted array
        System.out.println("Numbers in ascending order:");
        for (int i = 0; i < 5; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

       
    }
}
Output:
Enter 5 numbers:
35
10
20
5
15
Numbers in ascending order:
5 10 15 20 35

41. Java program to input 5 numbers in array. Sort the array in descending order using bubble sort method.


import java.util.Scanner;

public class BubbleSortDescending {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        // Bubble Sort Algorithm (Descending Order)
        for (int i = 0; i < 5 - 1; i++) {
            for (int j = 0; j < 5 - i - 1; j++) {
                if (numbers[j] < numbers[j + 1]) { // Modified comparison for descending order
                    // Swap numbers[j] and numbers[j+1]
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }

        // Printing the sorted array in descending order
        System.out.println("Numbers in descending order:");
        for (int i = 0; i < 5; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

        
    }
}
Output:
Enter 5 numbers:
35
10
20
5
15
Numbers in descending order:
35 20 15 10 5

42. Java program to input 5 numbers in array. Separate even and odd numbers in two arrays called evenArray and oddArray. Show all three arrays.


import java.util.Scanner;

public class SeparateEvenAndOddNumbers {
    public static void main(String[] args) {
        int[] inputArray = new int[5];
        int[] evenArray = new int[5];
        int[] oddArray = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the inputArray
        for (int i = 0; i < 5; i++) {
            inputArray[i] = scanner.nextInt();
        }

        int evenIndex = 0;
        int oddIndex = 0;

        // Separating even and odd numbers into evenArray and oddArray
        for (int i = 0; i < 5; i++) {
            if (inputArray[i] % 2 == 0) {
                evenArray[evenIndex] = inputArray[i];
                evenIndex++;
            } else {
                oddArray[oddIndex] = inputArray[i];
                oddIndex++;
            }
        }

        // Displaying all three arrays
        System.out.println("Input Array:");
        displayArray(inputArray);

        System.out.println("Even Array:");
        displayArray(evenArray);

        System.out.println("Odd Array:");
        displayArray(oddArray);

       
    }

    // Helper method to display the contents of an array
    private static void displayArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }
}
Output:
Enter 5 numbers:
12
5
8
7
20
Input Array:
12 5 8 7 20 
Even Array:
12 8 20 
Odd Array:
5 7 

The Most Important 50 Java Programs for Beginners

43. Java program to input two 3×3 Matrices in two 2D arrays. Calculate and display addition matrix.


import java.util.Scanner;

public class MatrixAddition {
    public static void main(String[] args) {
        int[][] matrix1 = new int[3][3];
        int[][] matrix2 = new int[3][3];
        int[][] resultMatrix = new int[3][3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter elements of the first 3x3 matrix:");

        // Taking input for the first matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix1[i][j] = scanner.nextInt();
            }
        }

        System.out.println("Enter elements of the second 3x3 matrix:");

        // Taking input for the second matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix2[i][j] = scanner.nextInt();
            }
        }

        // Calculating the addition matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        // Displaying the addition matrix
        System.out.println("Addition Matrix:");

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(resultMatrix[i][j] + " ");
            }
            System.out.println();
        }

        
    }
}
Output:
Enter elements of the first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Enter elements of the second 3x3 matrix:
9 8 7
6 5 4
3 2 1
Addition Matrix:
10 10 10 
10 10 10 
10 10 10 

44. Java Program to find the frequency of odd & even numbers in the given matrix


import java.util.Scanner;

public class MatrixOddEvenFrequency {
    public static void main(String[] args) {
        int[][] matrix = new int[3][3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter elements of the 3x3 matrix:");

        // Taking input for the matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        // Initializing variables to count frequency of odd and even numbers
        int oddCount = 0;
        int evenCount = 0;

        // Calculating the frequency of odd and even numbers in the matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (matrix[i][j] % 2 == 0) {
                    evenCount++;
                } else {
                    oddCount++;
                }
            }
        }

        // Displaying the frequency of odd and even numbers
        System.out.println("Frequency of even numbers: " + evenCount);
        System.out.println("Frequency of odd numbers: " + oddCount);

        
    }
}
Output
Enter elements of the 3x3 matrix:
1 2 3
4 5 6
7 8 9
Frequency of even numbers: 4
Frequency of odd numbers: 5


45. Java Program to determine whether a given string is palindrome

import java.util.Scanner;

public class PalindromeChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String inputString = scanner.nextLine();

        boolean isPalindrome = checkPalindrome(inputString);

        if (isPalindrome) {
            System.out.println("The string is a palindrome.");
        } else {
            System.out.println("The string is not a palindrome.");
        }

      }

    public static boolean checkPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }
}
Output:
Enter a string: radar
The string is a palindrome.


47. Java Program to input 5 numbers in array. Input an item to search in array. Find the position of the search item in array or show message “Not found”.


import java.util.Scanner;

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 5 numbers:");

        // Taking input from the user and storing in the array
        for (int i = 0; i < 5; i++) {
            numbers[i] = scanner.nextInt();
        }

        System.out.print("Enter the item to search: ");
        int searchItem = scanner.nextInt();

        int position = searchItemPosition(numbers, searchItem);

        if (position != -1) {
            System.out.println("Item found at position: " + position);
        } else {
            System.out.println("Item not found.");
        }

        }

    // Helper method to find the position of an item in the array
    public static int searchItemPosition(int[] array, int item) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == item) {
                return i;
            }
        }
        return -1;
    }
}
Output:
Enter 5 numbers:
10 20 30 40 50
Enter the item to search: 30
Item found at position: 2



48. Java program to input two 3×3 Matrices in two 2D arrays. Calculate and display multiplication matrix.


import java.util.Scanner;

public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrix1 = new int[3][3];
        int[][] matrix2 = new int[3][3];
        int[][] resultMatrix = new int[3][3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter elements of the first 3x3 matrix:");

        // Taking input for the first matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix1[i][j] = scanner.nextInt();
            }
        }

        System.out.println("Enter elements of the second 3x3 matrix:");

        // Taking input for the second matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix2[i][j] = scanner.nextInt();
            }
        }

        // Calculating the multiplication matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }

        // Displaying the multiplication matrix
        System.out.println("Multiplication Matrix:");

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(resultMatrix[i][j] + " ");
            }
            System.out.println();
        }

    }
}
Output:
Enter elements of the first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Enter elements of the second 3x3 matrix:
9 8 7
6 5 4
3 2 1
Multiplication Matrix:
30 24 18 
84 69 54 
138 114 90 

49. Java program to input a 3×3 matrix in a 2D array. Show transpose of matrix.


import java.util.Scanner;

public class MatrixTranspose {
    public static void main(String[] args) {
        int[][] matrix = new int[3][3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter elements of the 3x3 matrix:");

        // Taking input for the matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        // Calculating the transpose of the matrix
        int[][] transposeMatrix = new int[3][3];

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                transposeMatrix[j][i] = matrix[i][j];
            }
        }

        // Displaying the transpose of the matrix
        System.out.println("Transpose of the Matrix:");

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(transposeMatrix[i][j] + " ");
            }
            System.out.println();
        }

        
    }
}
Output:
Enter elements of the 3x3 matrix:
1 2 3
4 5 6
7 8 9
Transpose of the Matrix:
1 4 7 
2 5 8 
3 6 9 

50. Java Program to find the sum of each row and each column of a matrix


import java.util.Scanner;

public class MatrixSumRowColumn {
    public static void main(String[] args) {
        int[][] matrix = new int[3][3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter elements of the 3x3 matrix:");

        // Taking input for the matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        // Calculating the sum of each row
        int[] rowSum = new int[3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                rowSum[i] += matrix[i][j];
            }
        }

        // Calculating the sum of each column
        int[] columnSum = new int[3];
        for (int j = 0; j < 3; j++) {
            for (int i = 0; i < 3; i++) {
                columnSum[j] += matrix[i][j];
            }
        }

        // Displaying the sum of each row
        System.out.println("Sum of each row:");
        for (int i = 0; i < 3; i++) {
            System.out.println("Row " + (i + 1) + ": " + rowSum[i]);
        }

        // Displaying the sum of each column
        System.out.println("Sum of each column:");
        for (int j = 0; j < 3; j++) {
            System.out.println("Column " + (j + 1) + ": " + columnSum[j]);
        }

       
    }
}
Output:
Enter elements of the 3x3 matrix:
1 2 3
4 5 6
7 8 9
Sum of each row:
Row 1: 6
Row 2: 15
Row 3: 24
Sum of each column:
Column 1: 12
Column 2: 15
Column 3: 18

The Most Important 50 Java Programs for Beginners

Loading

Leave a Reply

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