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

5 Ways to Convert Integer into String in Java.

We can convert an integer into a String in Java using multiple ways and here in this article, we are going to learn 5 different ways to do so. Let's discuss each of them one by one.

Using the String.valueOf() method:

This method is a static method of the String class, which takes an int argument and returns a String representation of the integer value.

Example code:
int num = 42;
String str = String.valueOf(num);

Using the Integer.toString() method:

This method is a static method of the Integer class, which takes an int argument and returns a String representation of the integer value.

Example code:
int num = 42;
String str = Integer.toString(num);

Using concatenation with an empty string:

In Java, when a String is concatenated with another value, the other value is automatically converted to a String.

Example code:
int num = 42;
String str = "" + num;

Using the String.format() method:

This method is a static method of the String class, which takes a format string and an int argument, and returns a formatted String.

Example code:
int num = 42;
String str = String.format("%d", num);

Using StringBuilder or StringBuffer class:

Both StringBuilder and StringBuffer classes are used to create and manipulate strings in Java. They have methods to append various types of data to the string they are building.

Example code: 
int num = 42;
StringBuilder sb = new StringBuilder();
sb.append(num);
String str = sb.toString();

Java Program to Add Two Numbers.

In this article, we are going to learn addition of two integer number in Java programming,  we will discuss two different approach of doing this one assigning value to variable and another by taking input value from the user. 


Java Program to Add Two Integer Number.

Step by steps approach:
  • Define a class called AddTwoNumbers.
  • Declare two integer variables num1 and num2 and initialize them to 5 and 7.
  • Calculate the sum of num1 and num2 and store it in an integer variable called sum.
  • Print out the sum using System.out.println().
  • The output should be "The sum of 5 and 7 is 12".
Java Code:
//Java code to add two int number
public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
    }
}
Output:
The sum of 5 and 7 is 12

Java Program to Add Two Numbers Taking Input from User.

Here is the another approach of doing the same program in which we are taking two integer value as an input from the user and then printing the sum of those two value as an output.

Java Code:
//Java program to add two number from user
import java.util.Scanner;

public class AddTwoNumbers {
    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("The sum of " + num1 + " and " + num2 + " is " + sum);
        scanner.close();
    }
}
Output:
Enter the first number: 5
Enter the second number: 10
The sum of 5 and 10 is 15

Hello World Program in Java.

"Hello World" program is the most basic program that is used to introduce any new Programming Language to a newbie. This program basically prints a "Hello World" message on your console screen.

In this article, we are going to understand the working of the "Hello World" program in Java. 

Java Program:
// Java First Program

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

In the above code, the first line of code defined a new class called HelloWorld because in Java all code must be contained within classes, so this is the starting point of our program.

The next line public static void main(String[] args) defines a main method within the HelloWorld class. The main method is the entry point for the program and is the first method that is called when the program is run. It takes an array of String objects called args as a parameter.

The next line System.out.println("Hello, world!"); to print the message "Hello, world!" to the console. The println method adds a new line character after the message, so the next line of output will start on a new line.

How To Take Input from User in Java?

Java programming has various I/O packages to perform Input-Output operations. Unlike other programming languages, taking input from users is a little difficult in Java. 


There are multiple ways to take all different kinds of input from the user or from a file. These are:

  • Scanner Class.
  • BufferedReader Class.
  • Console Class.

1. Scanner Class.
We use the Scanner class to take input from the user through the command line. It has predefined functions to take different data types as input like integer, character, float, double, etc. 

Syntax:
We need to import the Scanner class to use the Scanner function.
  • import java.util.Scanner;
We need to create a new Scanner object called Scanner.
  • Scanner scan = new Scanner(System.in);

Example Code Implementation:

//Java program to take input from user using Scanner class
import java.util.Scanner;

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

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Probin
Enter your age: 24
Hello, Probin. You are 24 years old.

In this example, we first import the Scanner class and create a new Scanner object called a scanner. We then use the System.out.print method to prompt the user to enter their name, and then use the nextLine method of the Scanner class to read in the input as a string.

We then do the same thing for the user's age, using the nextInt method to read in the input as an integer.

Java Scanner Class Methods List.

Method Description
next() It is used to read the next token (word) from the input as a String.
nextLine() It is used to read the next line of input as a String.
nextInt() It is used to read the next token (integer) from the input as an int.
nextDouble() It is used to read the next token (a floating-point number) from the input as a double.
nextFloat() It is used to read the next token of the input as a float.
nextByte() It is used to read the next token of the input as a byte.
hasNext() It returns true if there is another token in the input (i.e. the end of the input has not been reached).
hasNextLine() It returns true if there is another line of input (i.e. the end of the input has not been reached).
useDelimiter(String pattern) It Sets the delimiter for the input to the specified regular expression pattern.

Note: The Scanner class can also be used to read input from files or other sources, not just from the command line.

2. BufferedReader Class.

The BufferedReader class is a simple class that is used to read a sequence of characters. It is used to read the data line by line using the readLine() method. The BufferedReader class is faster and more efficient for reading a large amount of input. 

Example Code Implementation.
//Java code to take input from user using BufferedReader class
import java.io.*;

public class InputExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter your name: ");
        String name = reader.readLine();

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(reader.readLine());

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Kumar
Enter your age: 24
Hello, Kumar. You are 24 years old.

In the above example, we are using the InputStreamReader() method that converts the input stream of bytes into a stream of characters.

3. Console class

Console class in Java is a built-in method for reading and writing text from the console. It is more secure for reading sensitive data like passwords without echoing them to the console.

List of some commonly used methods of console class:
Method Description
readLine() Reads a line of text from the console and returns it as a string.
readPassword() Reads a line of text from the console, but doesn't echo the characters to the screen.
printf(string format, Object... args) Writes formatted text to the console, similar to System.out.printf().
writer() Returns a PrintWriter object that can be used to write text to the console.

Example Code Implementation.
//Java code for taking user input using console class
import java.io.Console;

public class InputExample {
    public static void main(String[] args) {
        Console console = System.console();

        System.out.print("Enter your name: ");
        String name = console.readLine();

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(console.readLine());

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Jhon
Enter your age: 18
Hello, Jhon. You are 18 years old.

Note: Consoles class is not available in all IDEs and web applications so in that case you can use either Sanner or BufferedReader class for reading input from the user.

DON'T MISS

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