December 18, 2013

To check whether a number is prime or not in java

How to find Prime Number in java

How to determine a prime number in java :This program will check whether the given input is either prime number or not. it will return true or false.
copy and paste the code to notepad. compile it with javac and run it...

Instead of bufferedStream class you can use scanner class.  The logic i used is divide the given number from 2 to half of the number. if any one is divisible i stopped the loop and concluded it as not prime. if it successfully passed through all loop with out a division, then its a prime


 * Ramanujan s number 1729

 * @author Proximotech Java lazy

public class PrimeOrNot {

     * @param lazy java
      static int i,num,flag=0;
    public static void main(String[] vadassery) {
        // TODO Auto-generated method stub
        System.out.println("enter the integer no:");
       BufferedReader br=new BufferedReader(new InputStreamReader(;
       try {
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
           System.out.println("The given number is a prime number");
           System.out.println("The above number is not a prime number"); 


write a program in java to check the given number is prime or not

Checking the program with ramanujans number 1729 (smallest prime number which can be expressed as the sum of the cubes of two numbers in two ways )

out put : The given number is prime

Remember the smallest prime number is 2

To print all prime number in java

Alternative method to check a number is prime or not

public class JavaPrimeNumberCheck {
    public boolean isPrimeNumber(int number){
        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
        return true;
    public static void main(String a[]){
        JavaPrimeNumberCheck pc = new JavaPrimeNumberCheck();
        System.out.println("Is 17 prime number? "+pc.isPrimeNumber(17));
        System.out.println("Is 19 prime number? "+pc.isPrimeNumber(19));
        System.out.println("Is 15 prime number? "+pc.isPrimeNumber(15));

 Number to word convertor in java

class Test {
public static void main(String[] args) {
String []a = {"","one","two","three","four","five"};
String []b = {"","ten","twenty","thirty","fourty"};
int number = 432;
int i = number;
int d = i/100;
int r = i%100;
int t = r/10;
int tr = r% 10;
System.out.println(a[d]+" Hundered and "+b[t]+" "+a[tr]);

Are you looking for prime factor in java click here

Facebook comments