Thursday 13 September 2018

How to avoid receiving same message twice in RabbitMQ

In this post, we will see how to avoid receiving / processing duplicate message more than once in RabbitMQ.

Background:
RabbitMQ is a messaging queue software (also called message broker) that implemented the Advanced Message Queuing Protocol (AMQP). The producer submits message on queue and consumer processes it. But sometimes we use to see the issue with duplicate processing of same message in case where consumer decide to acknowledge message after processing it.

Problem Statement and Solution:
Suppose there is a message that is published into message broker. There can be two scenario in case of consumers for this message type:

  • Single Consumer
    • Consumer receives the message and start processing it and dies (or hung) in betweenIn this case if the acknowledgement has not been send back to RabbitMQ message broker, the message will remain in queue and when the consumer starts again, it will receive the same message. 
      • Solution: In the above case, developer needs to know if the business logic is processed or not. So developer needs to implement status of the message in either database or flat file with the message id. If same message is received after consumer restarts, developer can take a call to process again or not
    • Consumer receives message and processed it but still it receives same message again:
      • Solution: If you are facing this issue, then the problem lies in the heart-beat  timeout between consumer and RabbitMQ. So here consumer has received the message and its thread is processing it but due to missed heart-beat (due to network latency or whatever reason) RabbitMQ assumes the consumer has died and it closes the connection with consumer. Meanwhile as the consumer thread is active, it is still processing the message and completed it successfully but it was unable to acknowledge it back to RabbitMQ. The solution lies in increasing the heart-beat timeout so that it doesn't misses the heart-beat.
  • Multiple Consumer:
    • Consumer receives the message and start processing it and dies (or hung) in betweenIn this case if the acknowledgement has not been send back to RabbitMQ message broker, the message will remain in queue and it has been send back to another consumer waiting for message
      • Solution: In the above case, developer needs to know if the business logic is processed or not. So developer needs to implement status of the message in either database or flat file with the message id. If same message is received after consumer restarts, developer can take a call to process again or not
    • Consumer receives message and processed it but other consumer receives same message again:
      • Solution: If you are facing this issue, then the problem lies in the heart-beat  timeout between consumer and RabbitMQ. So here consumer has received the message and its thread is processing it but due to missed heart-beat (due to network latency or whatever reason) RabbitMQ assumes the consumer has died and it closes the connection with consumer. Meanwhile as the consumer thread is active, it is still processing the message and completed it successfully but it was unable to acknowledge it back to RabbitMQ. The solution lies in increasing the heart-beat timeout so that it doesn't misses the heart-beat. 
Thats all about problems related to consumer receiving duplicate messages and its possible solutions. If you have query / suggestion, please feel free to post in comment section. Thanks.

Wednesday 5 September 2018

Max Priority Queue Implementation in Java

In this post, we will see how to implement max priority queue in Java.

Background:
Priority Queue is an non-blocking unbounded queue, the elements of which are arranged in either natural order (if no comparator is provided) or comparator provided as part of constructor. In both scenario, the queue is arranged in ascending order and the head of queue will have least value. Honestly, this does not make sense for Priority Queue to arrange elements in ascending order which can be called as Min Priority Queue

Have the elements arranged in reversed order will make it Max Priority Queue

Implementation:

Now the question arises, how can we make the Priority Queue as Max Priority Queue with the api provided by Java.
Here is the code example for Max Priority Queue in Java


package com.blogspot.tech693;

import java.util.Collections;
import java.util.PriorityQueue;

public class MaxPriorityQueue{

 public static void main(String[] args){
  // Generic Priority Queue -- Natural order
  PriorityQueue pq = new PriorityQueue<>(6);
  pq.add(4);
  pq.add(2);
  pq.add(1);
  pq.add(6);
  pq.add(5);
  
  System.out.println("Generic / Min Priority Queue::" + pq.poll());
  System.out.println("Generic / Min Priority Queue::" + pq.poll());
  
  // Max Priority Queue Example
  PriorityQueue pq1 = new PriorityQueue<>(6, Collections.reverseOrder());
  pq1.add(4);
  pq1.add(2);
  pq1.add(1);
  pq1.add(6);
  pq1.add(5);
  
  System.out.println("Max Priority Queue::" + pq1.poll());
  System.out.println("Max Priority Queue::" + pq1.poll());
 }
 
}



Output:

Generic / Min Priority Queue::1

Generic / Min Priority Queue::2

Max Priority Queue::6

Max Priority Queue::5


Explanation:
In the above code example, we tried to achieve Priority Queue in descending order. I strongly believe the head of the queue should be the highest element. By using Collections.reverseOrder() method we can conver the Priority Queue into Max Priority Queue.

That's all for Max Priority Queue Implementation in Java. If you have questions / suggestions, please mention in comments sections. Thanks. 

Related Articles:

You may also like:

Sunday 5 August 2018

Java when another new thread comes to synchronized block does it goes to wait state

In this post, I will discuss what happens when another new thread comes to synchronized block and what happens to its state.

Brief Introduction:

Lets start with understanding what is synchronized block. In Java, synchronized block is the set of code under curly brackets which can only be accessed by a thread holding lock of the object on which it is defined. For example

public class TestSynchronizedBlock {
 public void method1(){
  synchronized(this) {
   System.out.println("Inside synchronized block");
   // Do your stuff here
   System.out.println("Exiting synchronized block");
  }
 }
}


Consider the code above, in class TestSynchronizedBlock, inside method1 the synchronized block can be accessed by the thread who is holding lock for current object of TestSynchronizedBlock (as it is holding lock for this i.e. object of TestSynchronizedBlock class. Every Object (instance of class) in Java has one monitor lock (it is the part of Object class, thus is part of any class object) and the thread which first try to enter into synchronized block gets the monitor lock.

Conclusion:

As I said above, the thread which first try to enter into synchronized block has the exclusive monitor lock and it keeps the locks till the thread is executing inside the block. So if Thread A is executing inside synchronized block, what happens when Thread B try to execute. Thread B will go to wait state (waiting for lock) and it will release any other monitor lock it holds, if any. After Thread A will complete executing the synchronized block, it will release the lock and Thread B will get notified and will hold the monitor lock and then start executing (means it will come out of wait state and goes to Execution state). This holds true incase of multiple threads trying to acquire lock. It is worth to mention that If there is more than one thread waiting for lock and in wait state, after current thread completes the execution, only one thread out of waiting n thread will get notified and there is no such sequence as which one with get notified. You can also refer Spin lock for deep dive on locking mechanism.

That's all for synchronized block in context of multiple threads and its status. If you have any query / doubt / suggestion, please drop a comment.

Java Spin lock implementation

In this article we will see how to implement Spin Lock in Java.

Introduction:

Lets first understand what is Spin Lock. Spin Lock is a type of lock where the threads instead of getting blocked keeps looking for locks. In Spin Lock, the thread does not go into wait state. The thread remains in Runnable / Running state and continuously trying to get lock (say in while loop) and this is the reason it is named as Spin Lock.

Usecase / Advantage:

So the next question that pop ups in mind is that where to use the Spin Lock over Wait Lock. Here are the following use-cases:

  • Avoiding Deadlock : 

    • Spin Lock is another way to avoid Deadlock. Since the thread trying for lock does not go into wait state instead spinning for lock, using Spin Lock avoids deadlock.

  • When there is very small functionality between lock and unlock : 

    • Suppose I want to just write small functionality bounded by locks. If you use mechanism where thread goes to wait state (eg. Reentrant Lock ) and then back to Runnable state (after acquiring lock), this means you are making call cpu expensive for a thread going into wait and runnable state. Perhaps you could choose Spin Lock which is a kind of busy waiting for a very short period of time before acquiring lock.

Disadvantage:

Do-nothing loop : As Spin Locks constantly checking if locks are available, it keeps wasting CPU time which could be allocated to other productive thread. Thats why longer duration of spin lock is not recommended.

Code Example:

Here is the Code Example in Java for Spin Lock Implementation:


SpinLock.java
package com.blogspot.tech693;

import java.util.concurrent.locks.ReentrantLock;

public class SpinLock extends ReentrantLock{

public SpinLock() {
  super();
 }


 public void lock() {
  while(!super.tryLock()) {
    // Do Nothing
  }

 }

 public void unlock() {
  super.unlock();
 }

}

Thats all for Spin Lock Example in Java. If you have questions / doubts, please write it on comment sections Thanks.

Related Articles:

You may also like:

Tuesday 17 July 2018

Introduction to SonarQube - Continuous code quality

In this post, we will see the uses and benefits of SonarQube.

Background
One of the important process in CI/CD is code scan wherein it scans the code for code smells, vulnerabilities, non-standard code etc.

Introduction
To maintain good code quality, it requires continuous scanning of code after each code-checkin. One of the important tool for code scanning is SonarQube which doesn't only scans the code but provide details about its standard and list out where all the issue with its quality. SonarQube job is to provide you with Blockers (i.e. code that is poorly written that can potentially cause issues with the application running in production), critical, major and minor. It also presents you with a value of how much standard your code is. SonarQube currently supports 21 language. Even you can scan your code directly without writing any linting configuration. 

Features
SonarQube scans the code by using methodology called as Quality Gates. This means each scan that we do on our code is by comparing our code with the quality gates. SonarQube has a default quality gate called “SonarQube way”. Whenever we scan the code, it is scanned against default quality gate “SonarQube way” and results are displayed. SonarQube also gives us the ability to configure our own Quality Gate.

SonarQube Quality gates are the best way to ensure that standards are met and regulated across all the projects and every developer oblige it in the organization.  Quality gates are defined with set of threshold measures set on your project like code coverage, technical debt measure (which can increase software entropy), number of blockers/critical issues, security rating, unit test pass rate etc.
 
In order to pass a Quality gate, the project should pass through each of the thresholds defined and it is just a set of conditions the project must meet before it can qualify for production release. When SonarQube runs it will identify if the code meets all the quality thresholds we have defined – else it will fail the quality gate and will not allow you to check in code to the Source code system. 

It also acts as a gatekeeper for bad code when it is integrated with repository tool like GitHub. GitHub provides a way to not allow merging of code (i.e. Pull request) if SonarQube scan fails. Using Quality Gates, we can also scan for new issues that may arise with our new code which is being written.

We can define a quality gate in SonarQube by using an option "create a Quality gate". This is the place where we configure the thresholds for the project / code to meet. After configuring quality gate, it need to be assigned to the project. After assigning, the subsequent scan on the project will be scanned against the quality gates.


That's all the brief introduction to SonarQube. If you have a question / comment, please mention in comment section. Thanks!

Saturday 14 July 2018

[solved] local variable defined in an enclosing scope must be final or effectively final

In this article we will see how to resolve local variable defined in an enclosing scope must be final or effectively final error for lambda expression.


Background


Java 8 introduces lambda expression which makes an easy way to implement interface which has only one abstract method (also known as functional interfaces). It is a requirement for lambda expression that if it is using local variable, it must be effective final. 


Meaning of Effectively final:


Effectively final are those variable which value doesn't change after it has been set. The sudden question that came in our mind that if this is the meaning of effectively final, why doesn't we declare the variable with final keyword. The difference between effectively final (its a terminology and not a java keyword) and keyword final is that effectively final behaves like final variable even it has not been declared final. 
If you declare a variable as final, its value cannot be changed (will throw compilation error) while those variable which value has been set once and never changed (without declaring as final) is called effectively final. This has to be taken care by developer if he is considering any variable as effectively final because compiler will not throw exception in this case, if the coder changes the value (not in context of lambda expression).


Code Example and Solution:


Consider the below code example which will give the following compilation error:
local variable defined in an enclosing scope must be final or effectively final


Code with Compilation error:



@FunctionalInterface

interface  SingleMethodInterface{

    void value();

}



public class Test {  

    public static void main(String[] args) {

        int i = 10; // This should be effectively final because it is being used by lambda expression.

        // If the value of i changes, it will throw the exception.

        // lambda expression implementing the value method. This is just implementation of interface

        // Here intentionally changing the value of i (increasing by one)

        SingleMethodInterface singleMethodInterface = ()-> System.out.println("Value of i is " + ++i); 

        // Calling the implemented interface method. Since the value is changed, so it will give compilation error

        singleMethodInterface.value();

    }

}


Code with no error


@FunctionalInterface

interface  SingleMethodInterface{

    void value();

}



public class Test {  

    public static void main(String[] args) {

        int i = 10; // This should be effectively final because it is being used by lambda expression.

        // If the value of i changes, it will throw the exception.

        // lambda expression implementing the value method. This is just implementation of interface

        // Here no changing the value of i

        SingleMethodInterface singleMethodInterface = ()-> System.out.println("Value of i is " + i); 

        // Calling the implemented interface method. Since the value is not changed so no error here

        singleMethodInterface.value();

    }

}


That's all for resolution of error for lambda expression with respect to local variable. If you have any further query, feel free to write out in comment section.

Friday 13 July 2018

How to encrypt string using ansible vault with example

In this article we will see how to encrypt string in Ansible using vault.

Introduction

Encrypting password, keys and variable is required to make system roboust. Using Ansible vault we can store the sensitive data and use the vault when running playbooks on remote machines. Using vault, the sensitive data remains safe.

How to encrypt string using vault

It is required to pass sensitive information if we are using Ansible as a configuration management system or a orchestration engine. For eg. we might need to pass password or ssh key while running playbook. By using vault, we can write sensitive data to a file which Ansible can read and utilize the data from within.

For these ansible provides a way to protect your data at rest. This feature is called vault, which allows user to encrypt text files, strings etc so that they are stored "at rest" in encrypted format. Without the key or a significant amount of computing power, the data is indecipherable.ansible-vault command is provided by Ansible in securing stuff.

Code Example


[root@server1 vault]# ansible-vault encrypt_string --vault-id a_password_file 'pass123' --name 'user1'


Result:

user1: !vault |

      $ANSIBLE_VAULT;1.1;AES256

      64576845869345693586856858858685086748057683457845788957865897856045876085707851

      20364856840580208230475024378508247502483650489658498568436856486584685684658445

      34085620345824852034850824598622865984065893460598263846598406895248658094856249

      23452345
 

If you want to use vault-id label then:

[root@server1 vault]# ansible-vault encrypt_string --vault-id myuser@password 'pass123' --name 'user1'
  

Result:

user1: !vault |

      $ANSIBLE_VAULT;1.1;AES256;myuser

      64576845869345693586856858858685086748057683457845788957865897856045876085707851

      20364856840580208230475024378508247502483650489658498568436856486584685684658445

      34085620345824852034850824598622865984065893460598263846598406895248658094856249

      23452345
 

This is how we can encrypt string in Ansible using vault. If you have any query related to Ansible vault, feel free to ask in comment section. Thanks.

Tuesday 3 July 2018

Jenkins how to clear cache

In this article we will see how to clear cache for Jenkins

Introduction:

While deploying new installation or driver, there is a need to clear cache for Jenkins. Even though Jenkins is removed, the previous installation details (as cache) can cause issue to the new installation. The solution lies in clearing the cache.



Background & Solution:

To understand this, first find out which all paths / locations where jenkins will be installed.

[root@server1 install]# rpm -ql jenkins
/etc/init.d/jenkins
/etc/logrotate.d/jenkins
/etc/sysconfig/jenkins
/usr/lib/jenkins
/usr/lib/jenkins/jenkins.war
/usr/sbin/rcjenkins /var/cache/jenkins
/var/lib/jenkins
/var/log/jenkins

So, as you can see these are the above paths / locations where jenkins will be installed. Any jenkins cache files, which remains in these paths might cause trouble to the new installation. So as a solution to this problem, we need to remove all files from these paths:
/var/cache/jenkins
/var/lib/jenkins
/var/log/jenkins

Here are the steps / commands to clear cache:

[root@server1 install]# rm -rf /var/cache/jenkins/*
[root@server1 install]# rm -rf  /var/lib/jenkins/*
[root@server1 install]# rm -rf /var/log/jenkins/*

After these paths / locations are cleared, we can go ahead with a new installation with no previous cache.

That's all about steps to clear cache for Jenkins. If you have queries, please write in comment section. Thanks.

Monday 2 July 2018

Design Chess game

Chess Game Design


Here give an example about an object oriented design of a chess game.

The design can be modularized into four parts: board, piece sets, game and player.





Board

A Board class has an attribute of Squares Array (8x8) and PieceSets (black and white).

A Board class also has an attribute of "pieceSetOnTop". The attribute helps to figure the piece moves that are direction-restricted.


PieceSets

A PieceSet class has an attribute of a List<Piece>. The size of the List<Piece> is initially set to 16.

A Piece class has two attributes: color and placeAt (i.e. located at which square).

A Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations:

  • validMoves() - The valid movement for a Piece
  • attackSquares() - The squares that a Piece can attack
  • captureFreeMove - The squares that a Piece can move to without being captured. 
  • toBeCaptured() - The boolean indicates whether a Piece is going to be captured.

The validMoves() operation implements the movement rules. For example, the validMoves of a Pawn class ensures that the Pawn can only move in the direction towards the opponent side. A Pawn class has additional attributes of promoted and promotedTo, which describes the movement/conversion rule of a Pawn at reaching the end of an opponent side and at the conversion about the piece that a Pawn converted to.

Game

A Game class controls the flow of a game. The class has attributes:

  • playedMoves - Keep a record of moves
  • turn - Indicate either it is a Black's turn or a White's turn
  • players - Represent the two players, this can be Human/Human, Computer/Computer or Human/Computer
  • result - Indicate the result of a game
  • checkStatus - Indicate which side is being checked or checkmated

Player

A Player class represents a Player. A Player has two attributes:

  • pieceColor - The color that used by a Player
  • engine - The engine that makes the moves. This can be a human or a computer

Saturday 23 June 2018

Ansible Loops with_items, with_nested and with_subelements example

In this article we will see the usage of Ansible Loops

Ansible Loops are used to execute the task multiple times. Consider a scenario where we want to create multiple users or want to install multiple packages. In any normal programming language, we achieve these using loops. Anisble also provide a similar feature.


Example of Ansible Loops with_items, with_nested and with_subelements example

Using Loops for multiple tasks

By passing a list, Ansible will run the task for all packages listed. This is called Standard Loops. For example

[root@server1 loops]# cat loop3.yml
---
- hosts: ubuntu
  tasks:

  - name: Create Multiple users
    shell: useradd {{ item }}
    with_items:
       - testuser1
       - testuser2

This example playbook will run the useradd command taking each from the list defined under the with_items construct. Each of the names is exposed as item, which is a default variable that Ansible creates. Ansible then assigns a package name to item, based on the iteration it is currently part of.


Once we run the above playbook,

[root@server1 loops]# ansible-playbook loop3.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Create Multiple users] *************************************************
changed: [172.18.188.24] => (item=testuser1)
changed: [172.18.188.24] => (item=testuser2)

PLAY RECAP ********************************************************************

172.18.188.24              : ok=2    changed=1    unreachable=0    failed


From the above example, we can now see that both users are created by using loops


How to use with_items construct using Ansible:


Lets see one more example of using with_items construct with variable substitution.

[root@server1 loops]# cat loop6.yml
---
- hosts: ubuntu
  tasks:

  - name: Installing Packages
    yum: name={{item.name}} state={{item.value}}
    with_items:
       - {name: 'httpd', value: 'present'}

Here in the above example playbook, we have defined a task which installs packages that are defined in the with_items construct. We have defined the package name with name and value variable which are then accessed by the item element. The item does then have the name and value data which will substitute when needed. 

Lets execute the playbook:

[root@server1 loops]# ansible-playbook loop6.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Installing Packages] ***************************************************
changed: [172.18.188.24] => (item={'name': 'httpd', 'value': 'present'})

PLAY RECAP ********************************************************************

172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  



Nested Loops using with_nested construct

Nested loops comes into picture where we want to perform multiple operations on the same resource. Take a simple example of usecase where we want to set different permission on a file or directory thus defining them using sub elements. As the title explains, Nested loop is a loop within a loop.

[root@server1 loops]# cat nested_loop1.yml
---
- hosts: ubuntu
  tasks:

  - name: Nested Loop / Change File Permissions
    shell: chmod -R {{ item[0] }} {{ item[1] }}
    with_nested:
       - [ '700' ]
       - [ '/tmp/test' ]

Okay, here is the simple example of nested loops. In the above usecase we have defined a task which will change the permission on a file /tmp/test with 700. The values are defined with with_nested construct and can be accessed as an array access (a[0]), while executing the above playbook.

 [root@server1 loops]# ansible-playbook nested_loop1.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [Nested Loop / Change File Permissions] *********************************
changed: [172.18.188.24] => (item=['700', '/tmp/test'])

PLAY RECAP ********************************************************************
172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  


Sub Nested Loops using Ansible with_subelements

Sub Nested Loops come into picture when we want to give data dynamically. uptill now, we have seen loops with static data but what if we want give data dynamically. Consider an example of creating multiple users along with different comments. To deal with such cases, we can use a dictionary to loop over sub-elements. Using such loops, we can specify a set of comments per user. Consider a sample example as,

[root@server1 loops]# cat subnested1.yml
---
- hosts: ubuntu
  vars:
    users:
     - name: testuser
       comments:
         - 'For testing purpose'

     - name: devuser
       comments:
         - 'For Dev purpose' 

  tasks:
   - name: User Creation
     shell: useradd -c "{{ item.1 }}" "{{ item.0.name }}"
     with_subelements:
         - users
         - comments

In the above playbook we defined a task which will create users along with user comments taken from 2 dictionaries users and comments. As we can see both users and comments are defined in the vars element above. Both dictionaries are defined under the with_subelements construct making Ansible to get sub elements from users and comments for running the task. Now lets execute this playbook:

[root@server1 loops]# ansible-playbook subnested1.yml

PLAY [ubuntu] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.18.188.24]

TASK: [User Creation] *********************************************************
changed: [172.18.188.24] => (item=({'name': 'testuser'}, 'For testing purpose'))
changed: [172.18.188.24] => (item=({'name': 'devuser'}, 'For Dev purpose'))

PLAY RECAP ********************************************************************
172.18.188.24              : ok=2    changed=1    unreachable=0    failed=0  


That’s all about Ansible Loops with multiple tasks, with_items, with_nested and with_subelements.

Saturday 26 May 2018

Ansible delegate_to

In this post, we will see the use of Ansible delegation using delegate_to


Purpose:

By default, on remote configure machine, Ansible run the task all at once. Consider the situation where task is based on status / output of a certain command on another machine. For example, if we are doing patching a package on a machine and you need to continue until a certain file is available on another machine. This can be achieved in Ansible using the delegation option.

As the terminology indicates, through Ansible delegate option we can configure to run a task on a different host (and not the default one) than the one that is being configured using the delegate_to key. The module will still run once for every machine, but instead of running on the target machine, it will run on the delegated host. The facts available will be the ones applicable to the current host. 


Code Example / Playbook using Ansible delegate:

[root@server1 delegate]# cat delegation-playbook.yml
---
- hosts: cent
 
  tasks:
    - name: Install zenity
      action: yum name=zenity state=installed
    - name: configure zenity
      action: template src=hosts dest=/tmp/zenity.conf
    - name: Tell Master
      action: shell echo "{{ansible_fqdn}} done" >> /tmp/list
      delegate_to: 172.16.202.99

We have defined multiple tasks to install zenity, configure zenity and the last task is to echo command on the delegate machineof different IP address.  Ansible-playbook will delegate the last task to the IP address 172.16.202.99. 

Once we run the playbook we can see the following:

[root@server1 delegate]# ansible-playbook delegation-playbook.yml

PLAY [cent] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.16.202.96]

TASK: [Install zenity] ********************************************************
changed: [172.16.202.96]

TASK: [configure zenity] ******************************************************
changed: [172.16.202.96]

TASK: [Tell Master] ***********************************************************
changed: [172.16.202.96 -> 172.16.202.99]

PLAY RECAP ********************************************************************
172.16.202.96              : ok=4    changed=3    unreachable=0    failed=0  

Now we can check the remote machine 172.16.202.99 for the file created.

root@ubuntu:/home/vagrant# cat /tmp/list
dev.foohost.vm done

Thats all for usage of Ansible delegation using delegate_to.

Thursday 4 January 2018

Java Program to find Prime Number with explanation

In this post, we will see how to find if the given number is Prime or not. Prime number are those numbers which cannot be divided by any number. 

For Example: 7 is a Prime Number because it is not divisible by 2 to 6. Similarly, 9 is a non-prime number as it is divisible by 3 

In this article, we will see three ways to find a number as Prime. From first to third program, you will find improvement in finding the prime number. The last program will be much better way (performance wise) to find Prime Number.


Program-I:


import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < num; i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a Prime number");
   else
    System.out.println("Number "+ input + " is a not Prime number");
 }
}


Output:


Run-1:
Enter number:
99
Number 99 is a not prime number
Run-2:
Enter number:
97
Number 97 is a prime number

Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to that number and checking if any of the number is divisible by the given number or not. To check that we are checking if the remainder of the division is zero or not (num % i == 0).
% is the Java operator which returns the remainder of the divided number. If the number is divided and remainder is zero then the number is divisible by other number.



Program-II:

The second program is an improvement over the previous program. In this code example, we will check (if the input number is divisible) till half of that number. More information is provided in explanation section.

import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < num/2; i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a prime number");
   else
    System.out.println("Number "+ input + " is a not prime number");
 }
}


Output:


Run-1:
Enter number:
108
Number 108 is a not prime number
Run-2:
Enter number:
109
Number 109 is a prime number

Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to the half of that  number. We don't need to check more as if the number is not divisible till half of that number, it will not be divisible by other half. For example to check prime number upto 100, we need to check till 50 because if the number is divisible by any number, its other divisible part will already been considered. 


Program-III:

import java.util.Scanner;

public class Prime {

 public static void main(String[] args) {
  System.out.println("Enter number:");
   Scanner scanner = new Scanner(System. in); 
   String input = scanner. nextLine();
   int num = Integer.parseInt(input);
   boolean isPrime = true;
   for(int i = 2; i < Math.sqrt(num); i++) {
    isPrime = (num % i == 0)?false:true;
    if(isPrime == false) break;
   }
   if(isPrime)
    System.out.println("Number "+ input + " is a prime number");
   else
    System.out.println("Number "+ input + " is a not prime number");
 }
}


Output:


Run-1:
Enter number:
105
Number 105 is a not prime number
Run-2:
Enter number:
101
Number 101 is a prime number


Explanation:

In above code example, to find any number is prime or not, the code is using for loop start from 2 to square root of that number and checking if any of the number is divisible by the given number or not. We don't need to check the complete squence, checking till its square root value is enough to say whether the number is prime or not. The reason is that if the number is non-prime, one of the divisible will fall within the square root of that number.

Among all this three examplex, Program-III is the best optimized one and is prefer to use it to find prime number.

That's all for this topic Java Program to find Prime Number. Please drop a comment if you have any doubt or suggestion. Thanks!