Java Number Programs

This blog post will teach you 15+ Java programs on Numbers with output and step-by-step explanations.

Note that these Java Number programs are frequently asked in the Java interviews for beginners.

java number programs

1. Java Program to Find Factorial Using Recursion

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It's denoted by n! and plays a significant role in various mathematical equations, including permutations and combinations. Calculating the factorial of a number using recursion is a classic example that demonstrates the power and simplicity of recursive functions in programming. Recursion involves a function calling itself with a smaller subset of the original problem until it reaches a base case, which, in the case of factorial, is 0! = 1. This program will demonstrate how to implement a program in Java to find the factorial of a number using recursion.

Program Steps

1. Define a method factorial that takes an integer n as input and returns its factorial using recursion.

2. In the factorial method, check if n is 0 or 1, which are the base cases, and return 1 since 0! = 1! = 1.

3. If n is greater than 1, recursively call the factorial method with n-1 and multiply the result by n.

4. In the main method, call the factorial method with a specific number and print the result.

Code Program

public class FactorialRecursion {
    public static void main(String[] args) {
        int number = 5; // Number to find the factorial of
        long factorial = factorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }

    // Step 1: Defining the recursive factorial method
    public static long factorial(int n) {
        // Step 2: Base case
        if (n == 0 || n == 1) {
            return 1;
        }
        // Step 3: Recursive case
        else {
            return n * factorial(n - 1);
        }
    }
}

Output:

Factorial of 5 is: 120

Explanation:

1. The program defines a factorial method that calculates the factorial of an integer n using recursion. This method uses a simple mathematical principle: n! = n * (n-1)!.

2. The base case of the recursion is when n is 0 or 1. In these cases, the method returns 1, as defined by the mathematical property of factorials.

3. For values of n greater than 1, the factorial method calls itself with n-1, multiplying the result by n. This recursive call continues until the base case is reached.

4. In the main method, the factorial method is called with a specific number (in this example, 5), and the result is printed to the console. The output shows the factorial of 5, which is 120, demonstrating the effectiveness of using recursion to solve problems that can be broken down into smaller, simpler sub-problems.

2. Java Program to Find Sum of Natural Numbers

Finding the sum of natural numbers is a common problem in mathematics and computer science education. Natural numbers are all positive integers starting from 1. The sum of the first n natural numbers can be found using a simple mathematical formula: n(n + 1)/2. However, it can also be calculated using a loop or recursion in programming. This program will demonstrate how to calculate the sum of natural numbers up to a given number n in Java, showcasing both a loop-based approach and the direct application of the formula for educational purposes.

Program Steps

1. Declare and initialize a variable to store the number n up to which the sum is to be calculated.

2. Calculate the sum using a loop.

3. Calculate the sum using the direct formula.

4. Display both results.

Code Program

public class SumOfNaturalNumbers {
    public static void main(String[] args) {
        int n = 100; // The number up to which the sum is calculated

        // Step 2: Calculating the sum using a loop
        int sumWithLoop = 0;
        for (int i = 1; i <= n; i++) {
            sumWithLoop += i;
        }

        // Step 3: Calculating the sum using the formula
        int sumWithFormula = n * (n + 1) / 2;

        // Step 4: Displaying both results
        System.out.println("Sum using loop: " + sumWithLoop);
        System.out.println("Sum using formula: " + sumWithFormula);
    }
}

Output:

Sum using loop: 5050
Sum using formula: 5050

Explanation:

1. The program starts by declaring an integer variable n with a value of 100, representing the number up to which the sum of natural numbers will be calculated.

2. It then initializes another variable sumWithLoop to 0. A for loop is used to iterate from 1 to n, incrementing sumWithLoop by the value of i with each iteration. This loop-based approach systematically adds each natural number up to n to calculate the total sum.

3. For the direct calculation using the formula, the program calculates the sum using the expression n * (n + 1) / 2 and stores the result in sumWithFormula. This formula is a quick and efficient way to find the sum without iterating through each number.

4. Finally, the program prints the results obtained from both the loop and the formula, demonstrating that they yield the same result. This example illustrates two different approaches to solving the same problem in Java, highlighting the efficiency of using mathematical formulas for certain calculations.

3. Java Program to Reverse a Number

Reversing a number is a common problem in programming, often used in exercises to practice control structures, such as loops. The objective is to take a number as input and reverse its digits. For example, if the input is 123, the output should be 321. This operation does not consider the mathematical sign of the number, treating all numbers as if they were positive. This program will demonstrate how to reverse a number using Java, showcasing the use of a while loop to iteratively process each digit of the number.

Program Steps

1. Declare and initialize a variable to store the original number.

2. Use a while loop to extract each digit from the number and build the reversed number.

3. Display the original number and its reversed version.

Code Program

public class ReverseNumber {
    public static void main(String[] args) {
        // Step 1: Initializing the original number
        int originalNumber = 1234;
        System.out.println("Original Number: " + originalNumber);

        // Step 2: Reversing the number
        int reversedNumber = 0;
        while (originalNumber != 0) {
            int digit = originalNumber % 10; // Extracting the last digit
            reversedNumber = reversedNumber * 10 + digit; // Appending the digit to the reversed number
            originalNumber /= 10; // Removing the last digit from the original number
        }

        // Step 3: Displaying the reversed number
        System.out.println("Reversed Number: " + reversedNumber);
    }
}

Output:

Original Number: 1234
Reversed Number: 4321

Explanation:

1. The program starts by declaring an integer originalNumber and initializes it with the value 1234. This variable holds the number to be reversed.

2. It then declares another integer reversedNumber and initializes it to 0. This variable will store the reversed number as the program processes each digit of the original number. A while loop is used to iterate as long as originalNumber is not 0. During each iteration, the last digit of originalNumber is extracted using the modulus operator %, and this digit is appended to reversedNumber. After appending the digit, originalNumber is divided by 10 to remove the last digit. This process continues until originalNumber becomes 0.

3. Finally, the program prints both the original and the reversed numbers, demonstrating the reversal process. The output confirms that the digits of the original number have been reversed successfully.

4. Java Program to Find Prime Numbers

Prime numbers are numbers that are greater than 1 and have only two factors: 1 and themselves. Finding prime numbers is a fundamental problem in mathematics and computer science, with applications ranging from cryptography to number theory. In programming, generating a list of prime numbers up to a given number can be accomplished using various algorithms. The most straightforward approach involves checking each number to see if it is divisible by any number other than 1 and itself. This program will demonstrate a simple Java program to find all prime numbers up to a given limit.

Program Steps

1. Define the upper limit up to which prime numbers should be found.

2. Use a for loop to iterate through each number from 2 to the defined limit.

3. For each number, check if it is prime by trying to divide it by all smaller numbers.

4. If a number is found to be prime, print it.

5. Repeat the process until all numbers up to the limit have been checked.

Code Program

public class FindPrimeNumbers {
    public static void main(String[] args) {
        int limit = 50; // Step 1: Define the upper limit
        System.out.println("Prime numbers up to " + limit + ":");

        for (int number = 2; number <= limit; number++) { // Step 2: Iterating through each number
            boolean isPrime = true;

            for (int i = 2; i <= number / 2; i++) { // Step 3: Checking if the number is prime
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime) { // Step 4: If the number is prime, print it
                System.out.print(number + " ");
            }
        }
    }
}

Output:

Prime numbers up to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation:

1. The program starts by setting an upper limit (limit) for the search of prime numbers, in this case, 50. This means the program will find all prime numbers between 2 and 50.

2. It then iterates through each number starting from 2 (the smallest prime number) up to the limit using a for loop.

3. For each number in this range, it checks whether the number is prime. It does this by attempting to divide the number by all integers from 2 up to half of the number itself. If any division results in a remainder of 0, the number is not prime, and the loop breaks early.

4. If, after checking all possible divisors, no divisor other than 1 and the number itself is found, the number is considered prime, and it is printed to the console.

5. The process repeats until all numbers up to the defined limit have been checked, resulting in a list of all prime numbers within the range. The program output confirms the prime numbers up to 50, demonstrating the effectiveness of this simple prime-finding algorithm.

5. Java Program to Check Armstrong Number

An Armstrong number (also known as a narcissistic 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 = 153. Armstrong numbers are an interesting topic in number theory and have applications in fields where digit manipulation is relevant. Here is a Java program to check whether a given number is an Armstrong number.

Program Steps

1. Input or define a number to be checked.

2. Calculate the number of digits in the number.

3. Calculate the sum of the digits each raised to the power of the number of digits.

4. Compare the calculated sum with the original number to determine if it is an Armstrong number.

5. Display the result.

Code Program

public class CheckArmstrongNumber {
    public static void main(String[] args) {
        int number = 370; // Step 1: The number to check
        int originalNumber = number;
        int sum = 0;

        // Step 2: Calculate the number of digits
        int numberOfDigits = String.valueOf(number).length();

        // Step 3: Calculate the sum of digits each raised to the power of number of digits
        while (number > 0) {
            int digit = number % 10;
            sum += Math.pow(digit, numberOfDigits);
            number /= 10;
        }

        // Step 4 & 5: Check and display if the number is an Armstrong number
        if (sum == originalNumber) {
            System.out.println(originalNumber + " is an Armstrong number.");
        } else {
            System.out.println(originalNumber + " is not an Armstrong number.");
        }
    }
}

Output:

370 is an Armstrong number.

Explanation:

1. The program starts with a predefined number 370, which is the number to check for being an Armstrong number.

2. It calculates the number of digits in 370 by converting the number to a string and measuring its length. This step is crucial as the power to which each digit is raised depends on the total number of digits in the number.

3. Using a while loop, it iterates through each digit of the number, calculating the sum of each digit raised to the power of the number of digits (numberOfDigits). The modulus operator (%) is used to extract the last digit, and the division operator (/) reduces number by one digit from the right on each iteration.

4. After calculating the sum, it compares the sum with the original number. If they are equal, the program concludes that the number is an Armstrong number and prints the result.

5. The output confirms that 370 is an Armstrong number, as the sum of each of its digits raised to the power of 3 (the number of digits) equals the number itself. This example demonstrates how to identify Armstrong numbers using basic arithmetic operations and control structures in Java.

6. Java Program for Prime Numbers Within a Range

Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Finding prime numbers within a specified range is a classic problem in mathematics and computer science, often used to teach the fundamentals of loops and conditionals. This task is academically interesting and has practical applications in cryptography, where prime numbers are used to encrypt data. Let's write a Java program to find and list all the prime numbers within a given range.

Program Steps

1. Define the start and end of the range within which to find prime numbers.

2. Iterate through each number in the range using a loop.

3. For each number, check if it is prime by attempting to divide it by all smaller numbers.

4. If a number is found to be prime, print it.

5. Repeat the process for each number within the specified range.

Code Program

public class PrimeNumbersInRange {
    public static void main(String[] args) {
        int start = 10; // Start of the range
        int end = 50; // End of the range
        System.out.println("Prime numbers between " + start + " and " + end + ":");

        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
    }

    // Method to check if a number is prime
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false; // Numbers less than or equal to 1 are not prime
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false; // Found a divisor other than 1 and the number itself
            }
        }
        return true; // No divisors found, so it's prime
    }
}

Output:

Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47

Explanation:

1. The program defines a range from 10 to 50, within which it will search for prime numbers.

2. It iterates through each number in this range. For each number, it calls the isPrime method to check if the number is prime.

3. The isPrime method checks if a number is prime by attempting to divide it by all numbers from 2 to the square root of the number. If any division has no remainder, the number is not prime, and the method returns false. Otherwise, it returns true.

4. If a number is determined to be prime, the program prints it. This process repeats for each number in the specified range.

5. The output lists all prime numbers between 10 and 50. This demonstrates how to find and print prime numbers within a range in Java, utilizing a method to check the primality of each number efficiently.

7. Java Program to Find the Largest of Three Numbers

Comparing numbers to find the largest one is a basic yet essential operation in programming, often encountered in sorting algorithms, decision-making processes, and data analysis. Determining the largest of three numbers requires comparing them using conditional statements. This task illustrates the use of control flow in programming and is a great exercise for beginners to understand how to make decisions in code. Let's write a Java program that finds the largest of three numbers, showcasing the application of conditional (if-else) statements.

Program Steps

1. Declare and initialize three numbers to be compared.

2. Use conditional statements to compare the numbers and find the largest one.

3. Display the largest number.

Code Program

public class LargestOfThreeNumbers {
    public static void main(String[] args) {
        // Step 1: Initializing three numbers
        int num1 = 10, num2 = 20, num3 = 30;

        // Step 2: Using conditional statements to find the largest number
        int largest;
        if (num1 >= num2 && num1 >= num3) {
            largest = num1;
        } else if (num2 >= num1 && num2 >= num3) {
            largest = num2;
        } else {
            largest = num3;
        }

        // Step 3: Displaying the largest number
        System.out.println("The largest number is: " + largest);
    }
}

Output:

The largest number is: 30

Explanation:

1. The program begins by declaring and initializing three integer variables, num1, num2, and num3, with values 10, 20, and 30, respectively. These variables represent the numbers to be compared.

2. It then uses a series of conditional (if-else) statements to compare the numbers. The program checks each number against the others to determine which one is the largest. The comparison logic is straightforward: it first checks if num1 is greater than or equal to both num2 and num3. If this condition is true, num1 is the largest. If not, it checks if num2 is greater than or equal to both num1 and num3. If this is true, then num2 is the largest. If neither condition is true, num3 must be the largest by elimination.

3. Finally, the program prints the largest number found by the conditional statements. The output clearly indicates that among the numbers 10, 20, and 30, the largest is 30. This example demonstrates the fundamental programming concept of making decisions using conditional statements to compare and find the largest of three numbers.

8. Java Program to Find the Fibonacci Series

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. It has applications in various fields, including mathematics, computer science, financial modeling, and even biology. The sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so forth. Writing a program to generate the Fibonacci series up to a certain number or for a certain number of terms is a common exercise in programming, demonstrating the use of iteration or recursion. This section will show how to implement a program in Java to generate the Fibonacci series up to a given number of terms.

Program Steps

1. Define the number of terms for which the Fibonacci series is to be generated.

2. Initialize the first two terms of the series (0 and 1).

3. Use a loop to generate the rest of the series up to the specified number of terms.

4. Display each term of the series as it is generated.

Code Program

public class FibonacciSeries {
    public static void main(String[] args) {
        int terms = 10; // Step 1: The number of terms to generate
        int firstTerm = 0, secondTerm = 1;
        System.out.println("Fibonacci Series up to " + terms + " terms:");

        for (int i = 1; i <= terms; ++i) {
            System.out.print(firstTerm + " ");

            // Step 3: Calculate the next term
            int nextTerm = firstTerm + secondTerm;
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }
    }
}

Output:

Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation:

1. The program begins by defining the number of terms (terms) for which the Fibonacci series is to be generated, in this case, 10.

2. It initializes the first two terms of the Fibonacci series, firstTerm as 0 and secondTerm as 1. These are the starting points of the series.

3. A for-loop iterates from 1 up to the specified number of terms. In each iteration, it prints the current firstTerm as part of the series. It then calculates the next term by adding the current firstTerm and secondTerm together, updating firstTerm and secondTerm to proceed to the next pair of terms in the series.

4. The output of the program shows the first 10 terms of the Fibonacci series, demonstrating how each term is generated from the sum of the two preceding terms. This example showcases a simple yet effective way to generate and display the Fibonacci series using a loop in Java.

9. Java Program to Find GCD of Two Numbers

The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that perfectly divides both numbers without leaving a remainder. Calculating the GCD is a fundamental concept in number theory and has practical applications in problems involving ratios, proportions, and modular arithmetic. The Euclidean algorithm is a well-known method for finding the GCD of two numbers, based on the principle that the GCD of two numbers also divides their difference. This section will demonstrate how to implement a Java program to find the GCD of two numbers using the Euclidean algorithm.

Program Steps

1. Declare and initialize two integer variables with the numbers whose GCD is to be found.

2. Implement the Euclidean algorithm to calculate the GCD.

3. Display the calculated GCD.

Code Program

public class GCDOfTwoNumbers {
    public static void main(String[] args) {
        int number1 = 48; // First number
        int number2 = 18; // Second number
        System.out.println("The GCD of " + number1 + " and " + number2 + " is: " + gcd(number1, number2));
    }

    // Method to calculate GCD using the Euclidean algorithm
    public static int gcd(int num1, int num2) {
        while (num1 != num2) {
            if (num1 > num2)
                num1 = num1 - num2;
            else
                num2 = num2 - num1;
        }
        return num1; // or num2, since they are equal now
    }
}

Output:

The GCD of 48 and 18 is: 6

Explanation:

1. The program begins with two integer variables, number1 and number2, initialized with the values 48 and 18, respectively. These are the two numbers for which the GCD is to be found.

2. The gcd method implements the Euclidean algorithm to calculate the GCD. It repeatedly subtracts the smaller number from the larger one until both numbers become equal. This equal value at the end of the loop is the GCD of the original two numbers.

3. The main method calls the gcd method with number1 and number2 as arguments and prints the result. The Euclidean algorithm efficiently finds the GCD, demonstrating its effectiveness with a simple loop structure.

4. The output of the program indicates that the GCD of 48 and 18 is 6, which is the largest number that divides both 48 and 18 without leaving a remainder. This example showcases a practical implementation of the Euclidean algorithm in Java for finding the GCD of two numbers.

10. Java Program to Find Strong Number

A strong number is a special number whose sum of the factorial of digits is equal to the original number. For example, 145 is a strong number because 1! + 4! + 5! = 145. Finding strong numbers is an interesting problem in computer science and mathematics, often used to practice loops and conditionals in programming. This program will illustrate how to determine if a given number is a strong number using Java, highlighting the use of loops to calculate factorials and sum them up to compare with the original number.

Program Steps

1. Define a number to check if it is a strong number.

2. Calculate the sum of the factorial of each digit of the number.

3. Compare the sum with the original number to determine if it is a strong number.

4. Display the result.

Code Program

public class StrongNumber {
    public static void main(String[] args) {
        int number = 145; // Step 1: Number to check
        int originalNumber = number;
        int sum = 0;

        while (number > 0) {
            int digit = number % 10;
            sum += factorial(digit); // Add the factorial of the digit to the sum
            number /= 10; // Move to the next digit
        }

        // Step 3: Compare sum with original number
        if (sum == originalNumber) {
            System.out.println(originalNumber + " is a Strong Number.");
        } else {
            System.out.println(originalNumber + " is not a Strong Number.");
        }
    }

    // Method to calculate the factorial of a number
    public static int factorial(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }
}

Output:

145 is a Strong Number.

Explanation:

1. The program starts with a predefined number 145, which is the candidate for checking whether it is a strong number.

2. It then calculates the sum of the factorials of each digit of 145. This is done by extracting each digit using the modulus operator (%), computing its factorial using the factorial method, and adding the result to sum. The process repeats for each digit by dividing the number by 10 until all digits have been processed.

3. After computing the sum of the factorials, the program compares this sum to the original number. If they are equal, it concludes that the number is a strong number.

4. The result is printed to the console. The output confirms that 145 is indeed a strong number, as the sum of the factorials of its digits equals the number itself. This example demonstrates how to use loops and basic arithmetic operations in Java to solve an interesting problem related to number theory and combinatorics.

11. Java Program to Find LCM of Two Numbers

The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both. Finding the LCM is a fundamental concept in arithmetic and number theory, with applications ranging from solving fractions to cryptographic algorithms. The LCM of two numbers can be found using their Greatest Common Divisor (GCD), based on the formula: LCM(a, b) = (a * b) / GCD(a, b). This program will demonstrate how to calculate the LCM of two numbers in Java by first finding their GCD.

Program Steps

1. Declare and initialize two integer variables with the numbers whose LCM is to be found.

2. Calculate the GCD of the two numbers.

3. Calculate the LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b).

4. Display the calculated LCM.

Code Program

public class FindLCM {
    public static void main(String[] args) {
        int num1 = 72, num2 = 120; // Step 1: Numbers to find the LCM of
        System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm(num1, num2));
    }

    // Method to find the LCM of two numbers
    public static int lcm(int a, int b) {
        return (a * b) / gcd(a, b); // Step 3: Calculating LCM using the formula
    }

    // Method to find the GCD of two numbers
    public static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

Output:

LCM of 72 and 120 is: 360

Explanation:

1. The program begins by declaring two integer variables, num1 and num2, with values 72 and 120, respectively. These are the numbers for which the LCM is to be calculated.

2. It defines a method gcd to calculate the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. This method iteratively applies the operation b = a % b and swaps a and b until b becomes 0, at which point a contains the GCD.

3. The lcm method calculates the Least Common Multiple (LCM) using the relationship between GCD and LCM: LCM(a, b) = (a * b) / GCD(a, b). It calls the gcd method to find the GCD of a and b and then applies the formula to find the LCM.

4. Finally, the main method calls the lcm method with num1 and num2 as arguments and prints the result, which is the LCM of 72 and 120. The output confirms that the LCM is 360, demonstrating the use of the GCD-LCM relationship to efficiently calculate the LCM of two numbers in Java.

12. Java Program to Check Palindrome Number

A palindrome number is a number that remains the same when its digits are reversed. Examples include 121, 1331, or 12321. Checking whether a number is a palindrome is a common problem in programming, illustrating basic control flow and string manipulation techniques. This problem can be solved by comparing the number with its reverse. If both are the same, the number is a palindrome. This program will demonstrate how to check if a number is a palindrome in Java.

Program Steps

1. Declare and initialize a variable to store the original number.

2. Reverse the original number.

3. Compare the original number with the reversed number.

4. Display whether the number is a palindrome.

Code Program

public class PalindromeNumber {
    public static void main(String[] args) {
        int originalNumber = 12321; // Step 1: Number to be checked
        int reversedNumber = 0;
        int number = originalNumber; // Temporary variable to hold the original number

        // Step 2: Reversing the number
        while (number != 0) {
            int lastDigit = number % 10;
            reversedNumber = reversedNumber * 10 + lastDigit;
            number /= 10;
        }

        // Step 3: Comparing the original number with the reversed number
        if (originalNumber == reversedNumber) {
            System.out.println(originalNumber + " is a palindrome number.");
        } else {
            System.out.println(originalNumber + " is not a palindrome number.");
        }
    }
}

Output:

12321 is a palindrome number.

Explanation:

1. The program begins with an integer originalNumber set to 12321. This is the number that will be checked to determine if it is a palindrome.

2. It declares reversedNumber to store the reverse of the original number and uses a while loop to populate reversedNumber. Inside the loop, it extracts the last digit of number (a temporary variable holding originalNumber) using the modulus operator % and adds this digit to reversedNumber, appropriately scaling reversedNumber by 10 on each iteration to shift digits left.

3. After reversing the number, it compares originalNumber with reversedNumber. If they are equal, the original number is a palindrome.

4. The program then prints the result. In this case, since 12321 is equal to its reverse, the output confirms that 12321 is a palindrome number. This example demonstrates a straightforward approach to checking palindrome numbers in Java, employing arithmetic operations and control flow.

13. Java Program to Check if a Given Number is Perfect Square

A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. For example, 16 is a perfect square because it equals 4 * 4. Checking if a number is a perfect square is a common problem in programming and mathematics, with applications ranging from algebra to computer graphics. This section will demonstrate a Java program to check if a given number is a perfect square by leveraging the Math.sqrt() method and ensuring the result is an integer.

Program Steps

1. Declare and initialize a variable to store the number to be checked.

2. Calculate the square root of the number using Math.sqrt().

3. Check if the square of the rounded square root equals the original number.

4. Display whether the number is a perfect square.

Code Program

public class PerfectSquareCheck {
    public static void main(String[] args) {
        int number = 16; // Step 1: Number to check
        double squareRoot = Math.sqrt(number); // Step 2: Calculating square root

        // Step 3: Checking if the square of the rounded square root equals the original number
        if ((int)squareRoot * (int)squareRoot == number) {
            System.out.println(number + " is a perfect square.");
        } else {
            System.out.println(number + " is not a perfect square.");
        }
    }
}

Output:

16 is a perfect square.

Explanation:

1. The program starts with a predefined integer number, which is the candidate for the perfect square check. In this example, number is set to 16.

2. It calculates the square root of number using Math.sqrt(number) and stores the result in squareRoot. This method returns a double, so the precision is high enough for the square root calculation.

3. The program then checks if the square of the rounded square root ((int)squareRoot * (int)squareRoot) equals the original number. The cast to int is crucial as it ensures we're working with integers when comparing to number.

4. Finally, based on the result of the comparison, the program prints a message indicating whether number is a perfect square. The output confirms that 16 is a perfect square because its square root is an integer that, when squared, equals the original number. This example showcases a practical use of mathematical functions in Java to perform number theory checks.

Comments