Check Leap Year in Java.

In this article, we are going learn how to check if the given year is a leap year or not using Java Programming and we will use Java if-else condition to solve this problem.

Leap Year are those Year in which we have 366 days whereas a normal Year contains 365 days. In leap year, the month Feburary contain 29 days. (alert-success)


Algorithm for Leap Year.

Below algorithm used to check if a year is a leap year or not:

  • Take an input year from the user.
  • If the year is evenly divisible by 4, go to step 3. Otherwise, go to step 6.
  • If the year is evenly divisible by 100, go to step 4. Otherwise, go to step 5.
  • If the year is evenly divisible by 400, go to step 5. Otherwise, go to step 6.
  • The year is a leap year (it has 366 days).
  • The year is not a leap year (it has 365 days).


Java Code Implementation to Find Leap Year.

import java.util.Scanner;

public class LeapYear {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int year;
        
        // Prompt user to enter a year
        System.out.print("Enter a year: ");
        year = input.nextInt();
        
        // Check if the entered year is a leap year
        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 1:
Enter a year: 2020
2020 is a leap year

Output 1:
Enter a year: 2022
2020 is not a leap year

In the above code, a year is a leap year if it is divisible by 4 but not divisible by 100, or if it is divisible by 400. This algorithm is based on the rules of the Gregorian calendar, which is the calendar system used in most of the world today.

Find Largest Among Three Numbers in Java.

find greatest among three numbers in java

In this article, we are going to learn Java programs to find the greatest number among three integer numbers. There are multiple ways to solve this program and we will each of them one by one.


Approach 1: Find the Greatest using if-else statement.

In this approach, we will use if-else statements to compare the three numbers and find the greatest among them.

Java Example Code:

import java.util.Scanner;

public class GreatestOfThreeNumbers {

   public static void main(String[] args) {

      int num1, num2, num3;
      Scanner input = new Scanner(System.in);

      System.out.println("Enter three numbers:");
      num1 = input.nextInt();
      num2 = input.nextInt();
      num3 = input.nextInt();

      if (num1 > num2 && num1 > num3) {
         System.out.println(num1 + " is the greatest.");
      }
      else if (num2 > num1 && num2 > num3) {
         System.out.println(num2 + " is the greatest.");
      }
      else {
         System.out.println(num3 + " is the greatest.");
      }
   }
}
Output:
Enter three numbers:
12
23
11
23 is the greatest.

Here, we are taking input of three numbers from the user using the Scanner class. Then, we are using if-else statements to compare the numbers and print the greatest among them.


Approach 2: Using Math.max() method.

In this approach, we will use the Math.max() method to find the greatest among the three numbers.

Java Example Code:
import java.util.Scanner;

public class GreatestOfThreeNumbers {

   public static void main(String[] args) {

      int num1, num2, num3;
      Scanner input = new Scanner(System.in);

      System.out.println("Enter three numbers:");
      num1 = input.nextInt();
      num2 = input.nextInt();
      num3 = input.nextInt();

      int greatest = Math.max(num1, Math.max(num2, num3));
      System.out.println(greatest + " is the greatest.");
   }
}
Output:
Enter three numbers:
10
23
15
23 is the greatest.

Here, we are using the Math.max() method to find the greatest among the three numbers. We are taking input of three numbers from the user using the Scanner class and then passing them as arguments to the Math.max() method. The Math.max() method returns the greatest of the two numbers passed as arguments, so we are calling it twice to compare all three numbers.

Approach 3: Using Array and Loops.

In this approach, we will use arrays and loops to find the greatest among the three numbers.

Java Example Code:
//Java code for finding greatest number
import java.util.Scanner;

public class GreatestOfThreeNumbers {

   public static void main(String[] args) {

      int[] nums = new int[3];
      Scanner input = new Scanner(System.in);

      System.out.println("Enter three numbers:");
      for (int i = 0; i < 3; i++) {
         nums[i] = input.nextInt();
      }

      int greatest = nums[0];
      for (int i = 1; i < 3; i++) {
         if (nums[i] > greatest) {
            greatest = nums[i];
         }
      }
      System.out.println(greatest + " is the greatest.");
   }
}
Output:
Enter three numbers:
19
29
15
29 is the greatest.

Here, we are using an array to store the three numbers entered by the user. We are taking input of three numbers from the user using the Scanner class and then using a loop to store them in the array. Then, we are using another loop to compare the numbers in the array and find the greatest among them.

Find Factorial of a Number in Java.

In this article, we will learn multiple approaches to finding the factorial of a number in Java Programming. Before moving to the code part lets us first understand what is Factorial and how to calculate it. 


What is the Factorial of a Number?

Factorial is a mathematical operation that is used to calculate the product of all positive integers from 1 to a given positive integer n. 


It is denoted by the symbol "!" and is defined as follows:

  • n! = n x (n-1) x (n-2) x ... x 3 x 2 x 1


For example, the factorial of 5 is calculated as:

  • 5! = 5 x 4 x 3 x 2 x 1 = 120
  • The factorial of 0 is defined to be 1 by convention, that is: 0! = 1


We can find the factorial of a number using the following approaches:

Find Factorial using for loop.

In this approach, we use a for loop to multiply each number from 1 to n, where n is the number for which we need to find the factorial.

Java Code:

//Java code to find factroil of a number using for loop
import java.util.Scanner;

public class HelloWrold {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int n = input.nextInt();
    int factorial = 1;
    for (int i = 1; i <= n; i++) {
      factorial *= i;
    }
    System.out.println("Factorial of " + n + " is " + factorial);
  }
}
Output:
Enter a number: 5
Factorial of 5 is 120
  • Time Complexity: O(n)
  • Space Complexity: O(1)


Find Factorial using Recursion.

In this approach, we use a recursive function to find the factorial of a number. A recursive function is a function that calls itself.

Java Code:
//Java code to find factroil of a number using Recursion
import java.util.Scanner;

public class Factorial {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int n = input.nextInt();
    int factorial = fact(n);
    System.out.println("Factorial of " + n + " is " + factorial);
  }

  public static int fact(int n) {
    if (n == 0) {
      return 1;
    }
    return n * fact(n - 1);
  }
}
Output:
Enter a number: 5
Factorial of 5 is 120
  • Time Complexity: O(n)
  • Space Complexity: O(n)


Find Factorial using a while loop.

In this approach, we use a while loop to multiply each number from 1 to n, where n is the number for which we need to find the factorial.

Java Code:
//Java code to find factroil of a number using while loop
import java.util.Scanner;

public class Factorial {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int n = input.nextInt();
    int factorial = 1;
    int i = 1;
    while (i <= n) {
      factorial *= i;
      i++;
    }
    System.out.println("Factorial of " + n + " is " + factorial);
  }
}
Output:
Enter a number: 10
Factorial of 5 is 3628800
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Java Program to Check Prime Number.

In this article, we are going to discuss different approaches to checking if a number is in Prime or not using Java Programming. Before moving to the code part let us understand what are Prime Numbers.

java program to check prime

What is Prime Number?

A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. In other words, a prime number can only be divided evenly by 1 and itself.

For example, the first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, and so on.


There are multiple ways to check if a number is prime or not in Java.

  • Check Prime Number using Loop.
  • Check Prime Number using the square root property.
  • Check Prime Number using the Sieve of Eratosthenes.


Check Prime Number using Loop.

To check if a number is prime is to use a loop and iterate from 2 to n/2 (where n is the number we want to check) and check if n is divisible by any number in this range. If n is divisible by any number in this range, then it is not prime.

Java Code Implementation:
// Java code to check prime using loop
class CheckPrime {
    public static void main(String[] args) {
        boolean check = isPrime(11);
        if(check){
            System.out.println("Number is Prime!");
        }
        else{
            System.out.println("Number is not Prime!");
        }
    }
    public static boolean isPrime(int n) {
        if (n <= 1) {
           return false;
        }
        for (int i = 2; i <= n/2; i++) {
           if (n % i == 0) {
              return false;
           }
        }
        return true;
    }
}
Output:
Number is Prime!

Time Complexity:
  • The time complexity of this approach is O(n/2) = O(n), where n is the input number. This is because the loop iterates from 2 to n/2 and checks if n is divisible by any of these numbers.
Space Complexity:
  • The space complexity of this approach is O(1) because only a constant amount of memory is used to store the loop variable and other variables.


Check Prime Number using the square root property.

This approach is to check if n is divisible by any number in the range 2 to sqrt(n) (where sqrt(n) is the square root of n). This approach is more efficient because it reduces the number of iterations in the loop.

Java Code Implementation:
// Java code to check prime using the square root property
class CheckPrime {
    public static void main(String[] args) {
        boolean check = isPrime(7);
        if(check){
            System.out.println("Number is Prime!");
        }
        else{
            System.out.println("Number is not Prime!");
        }
    }
    //function to check prime
    public static boolean isPrime(int n) {
        if (n <= 1) {
           return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
              return false;
            }
        }
        return true;
    }
}
Output:
Number is Prime!

Time Complexity:
  • The time complexity of this approach is O(sqrt(n)), where n is the input number. This is because the loop iterates from 2 to sqrt(n) and checks if n is divisible by any of these numbers.
Space Complexity:
  • The space complexity of this approach is O(1) because only a constant amount of memory is used to store the loop variable and other variables.


Check Prime Number using the Sieve of Eratosthenes.

This is a more advanced approach to finding all the prime numbers up to a certain limit. 

This algorithm involves creating a boolean array of size n+1 and setting all the values to true. We then iterate from 2 to sqrt(n) and mark all multiples of each number as false. Finally, we iterate through the boolean array and return all the indexes that are marked as true.

Java Code Implementation:
// Java code to check prime using the Sieve of Eratosthenes
import java.util.Arrays;

class HelloWorld {
    public static void main(String[] args) {
        boolean check = isPrime(7);
        if(check){
            System.out.println("Number is Prime!");
        }
        else{
            System.out.println("Number is not Prime!");
        }
    }
    public static boolean[] sieveOfEratosthenes(int n) {
        boolean[] prime = new boolean[n+1];
        Arrays.fill(prime, true);
        prime[0] = false;
        prime[1] = false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
           if (prime[i]) {
               for (int j = i*i; j <= n; j += i) {
                   prime[j] = false;
               }
           }
        }
        return prime;
    }

    public static boolean isPrime(int n) {
       if (n <= 1) {
           return false;
       }
       boolean[] primes = sieveOfEratosthenes(n);
       return primes[n];
    }
}
Output:
Number is Prime!

Time Complexity:
  • The time complexity of the Sieve of Eratosthenes algorithm is O(n log log n), where n is the input number. This is because the algorithm involves iterating through all numbers up to n and marking multiples of each prime number as composite.
Space Complexity:
  • The space complexity of this approach is O(n) because we need to store a boolean array of size n+1 to mark all numbers as prime or composite.

Java Program to Reverse a String.

reverse string in Java

In this article, we will understand multiple approaches to reverse a string in Java Programming. 


We can reverse a string using the below approaches:

  • Reverse a string using a loop.
  • Reverse a string using the StringBuilder class.
  • Reverse a string using Recursion.

Let,s discuss each of them one by one,


Reverse a string using a loop.

One way to reverse a string is to use a loop and iterate through the characters of the string in reverse order. We can then append each character to a new string to create the reversed string.

Java Code Implementation:

// Java code to reverse string using loop
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
       String reversed = "";
       for (int i = str.length() - 1; i >= 0; i--) {
          reversed += str.charAt(i);
       }
       return reversed;
   }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)


Reverse a String using StringBuilder Class.

Java provides a StringBuilder class that has a reverse() method to reverse a string. We can create a StringBuilder object and then call the reverse() method to get the reversed string. This is the most efficient approach to reversing a string.

Java Code Implementation:
// Java code to reverse string using StringBuilder class
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        return sb.toString();
    }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Reverse a String using Recursion.

This approach is to use recursion to reverse a string. We can recursively swap the first and last characters of the string until we reach the middle of the string. This is the least efficient approach and can cause a stack overflow if the string is very long. 

Java Code Implementation:
// Java code to reverse string using Recursion
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
        if (str.isEmpty()) {
           return str;
        } else {
           return reverseString(str.substring(1)) + str.charAt(0);
        }
    }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Java Program to Reverse a Number.

In this article, we are going to discuss different methods of reversing a number in Java. There are three ways to reverse a number in Java and these are:

  • Reverse a number using the while loop.
  • Reverse a number using StringBuilder.
  • Reverse a number using Recursion.
Let,s discuss each approach one by one:

Reverse a number using the while loop.

In this approach, we extract each digit of the number from the right side using the modulus operator and keep adding it to a new number in reverse order.

Java Example code:

//Java code to Reverse a number using while loop
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:
Reverse Number: 54321


Reverse a number using StringBuilder.

In this approach, we convert the integer to a string, then use the StringBuilder class to reverse the string and convert it back to an integer.

Java Example Code:
//Reverse a number using StringBuilder class
public class ReverseNumber
{
	public static void main(String[] args) {
		int num = 12345;
                //converting integer to string
                String str = String.valueOf(num);
                StringBuilder sb = new StringBuilder(str);
                sb.reverse();
                //converting string to integer
                int reversed = Integer.parseInt(sb.toString());
                System.out.println("Reversed Number: " + reversed);
	}
}
Output:
Reverse Number: 54321


Reverse a number using Recursion.

In this approach, we call the same function recursively with the remaining part of the number until we have a single-digit number. Then we return the number as is.

Java Example Code:
//Reverse a number using Recursion
public class Main
{
	public static void main(String[] args) {
		int num = 12345;
        int reversed = reverseNumber(num);
        System.out.println("Reversed Number: " + reversed);
        }
    
    public static int reverseNumber(int num) {
          if (num < 10) {
          return num;
         }
        int digit = num % 10;
        return digit * (int) Math.pow(10, (int) Math.log10(num)) + reverseNumber(num / 10);
    }        
}
Output:
Reverse Number: 54321

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo