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!

How to integrate Salesforce webservices with Ruby on Rails

In this article we will see how to integrate Salesforce REST API to push data from Ruby on Rails application. Please note it requires Ruby greater than 2.0 because of TLS security issues. 

Here are the detailed steps for integrating Salesforce API with Rails application:-


(a) GET WSDL Files and Security Token


Enterprise/ParterWSDL Files: If you have salesforce account you can get your WSDL files from there. You can get this file from your salesforce account “App Setup > Develop > Download your organization-specific WSDL” link.


<?xml version=”1.0″ encoding=”UTF-8″?>
<!–
Web Services API : WebToLeadServices
–>
<definitions targetNamespace=”http://soap.sforce.com/schemas/class/WebToLeadServices” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns=”http://schemas.xmlsoap.org/wsdl/” xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/” xmlns:tns=”http://soap.sforce.com/schemas/class/WebToLeadServices”>
<types>
<xsd:schema elementFormDefault=”qualified” targetNamespace=”http://soap.sforce.com/schemas/class/WebToLeadServices”>
.
.
.
<xsd:complexType name=”WebLead”>
<xsd:sequence>
<xsd:element name=”name” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”email” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”phone” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
<xsd:element name=”comments” minOccurs=”0″ type=”xsd:string” nillable=”true”/>
</xsd:sequence>
</xsd:complexType><xsd:element name=”createLeadFromWeb”>
<xsd:complexType>
<xsd:sequence>
<xsd:element name=”wl” type=”tns:WebLead” nillable=”true”/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
.
.
.
<service name=”WebToLeadServicesService”>
<documentation></documentation>
<port binding=”tns:WebToLeadServicesBinding” name=”WebToLeadServices”>
<soap:address location=”https://ap7.salesforce.com/services/Soap/class/WebToLeadServices”/>
</port>
</service>
</definitions>

Webtolead.wsdl : If you want to send data from your website to salesforce then it will require wsdl files for e.g webtosalesforcelead.xml with content something like this.


Security token : Navigate to My Settings > Personal > Reset My Security Token and click on “Reset Security Token”. This will send you security token on your registered mail id.


(b) Install the SOAP4R gem using Terminal.


gem install soap4r


(c) Run wsdl2ruby


Go to folder where have install soam gem. run the following commands in terminal.

cd /path/to/gem/soap/
wsdl2ruby.rb –wsdl ~/path/to/enterprise.wsdl.xml –type client

Change your paths accordingly. This will produce 4 files in your current working directory: default.rb, defaultDriver.rb, defaultMappingRegistry.rb, and SforceServiceClient.rb.

One more file is required as SOAP4R uses “header handlers” to modify outgoing and read incoming headers (and note that these are SOAP headers, not HTTP headers), so you’ll have to write one of your own (syntax highlighted version):

client_auth_header_handler.rb

require ‘soap/header/simplehandler’
class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
SessionHeader = XSD::QName.new(“rn:enterprise.soap.sforce.com”, “SessionHeader”)

attr_accessor :sessionid
def initialize
super(SessionHeader)
@sessionid = nil
end


def on_simple_outbound

if @sessionid
{“sessionId” => @sessionid}
end
end


def on_simple_inbound(my_header, mustunderstand)

@sessionid = my_header[“sessionid”]
end
end



(d) Create Rails application


install these two gems

gem ‘soap4r’
gem ‘soap4r-spox’


(e) Put all generated files and client_auth_header_handler.rb in you salesforce folder in lib folder of your project.

lib/salesforce
lib/salesforce/default.rb
lib/salesforce/defaultDriver.rb
lib/salesforce/defaultMappingRegistry.rb
lib/salesforce/SforceServiceClient.rb
lib/salesforce/client_auth_header_handler.rb

and change require path accordingly on each files e.g.

require ‘salesforce/default.rb’
require ‘salesforce/defaultMappingRegistry.rb’
require ‘soap/rpc/driver’


(f) Create helper salesfore_helper.rb


module SiteHelper
require ‘rubygems’
gem ‘soap4r’
require ‘soap/soap’
require ‘salesforce/defaultDriver’
require ‘salesforce/client_auth_header_handler’
require ‘soap/wsdlDriver’

def sendtosf

sf = User.first
d = Soap.new
d.wiredump_dev = STDOUT
h = ClientAuthHeaderHandler.new
username = “yourusername”
password = “yourpassword”
token = “yoursectoken”
l=d.login(:username => username, :password => password+token)
h.sessionid = l.result.sessionId
d.headerhandler << h
client = SOAP::WSDLDriverFactory.new( ‘lib/salesforce/webtosalesforcelead.xml’ ).create_rpc_driver
client.wiredump_dev = STDOUT
client.headerhandler << h
leadData = {}
leadData[“wl”] = sf #=> “wl” createLeadFromWeb element
Rails.logger.info “========#{leadData.inspect}============”
response = client.createLeadFromWeb(leadData) #=> createLeadFromWeb method which is present in webtosalesforcelead.xml

#Rails.logger.info “========#{leadData.inspect}============”

Rails.logger.info “========#{response.inspect}============”
#response = client.WebLead(sf)
end
end

That's all for steps to integrate Salesforce REST API with Ruby on Rails. If you have any query, please write in comment section.

Daemon Thread in Java

Introduction:

In Java, Daemon Threads are one of the types of thread which does not prevent Java Virtual Machine (JVM) from exiting.
The main purpose of daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

How to create a Daemon Thread in Java:

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

Code Example:


public class DaemonThread {

public static void main(String[] args) {
System.out.println("Entering Main Thread");
Thread t = new Thread(new Runnable(){
@Override
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Executing Daemon Thread");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.setDaemon(true); // Thread becomes daemon thread here
t.start();
System.out.println("Exiting Main Thread");
}
}

Here is the sample output:

Output1:
Entering Main Thread
Exiting Main Thread

Output2:
Entering Main Thread
Exiting Main Thread
Executing Daemon Thread
Executing Daemon Thread

Explanation

In the above code example, main thread is spawning a daemon thread, Here main thread is the only non-deamon thread. As soon as the main thread execution completes, JVM exits and daemon thread dies alongwith.

The above code example and output illustrates the following:
  • JVM doesn't wait for the daemon thread to complete its task
  • Daemon thread dies as soon as JVM exits

Finding if the thread is daemon or not:



To know if a thread is daemon or not, you can check with Thread.isDeamon(). If returns true, the thread is daemon.

Java Timer Example

Java Timer Example:

Think of a scenario where I want my code to execute at a particular time in my application or at sometime later from the current time. In other words, I want to schedule my task at the definite time. How can this be possible using Java Programming language?

Tutorial:

Java Timer class (java.util.Timer) allows an application to schedule the task on a separate background thread. Please note that by default the associated thread is a non-daemon thread i.e. application does not terminate pending timer thread to complete execution.However, you can change the associated thread to Timer Class as Daemon Thread during creation of Timer Object. (Learn more about Daemon Thread in java)

Timer Task:

Timer class needs Timer Task (java.util.TimerTask) (Runnable Object) to execute the task. This is the class where the actual logic implementation resides inside run method. Timer when scheduled, picks up Timer Task and executes (once or repetitive as the case may be).

How to schedule Task:

Timer class provides various ways to schedule the task based on number of execution and rate of execution. Here are the list:

Method Signature

Purpose

schedule (TimerTask task, Date time) Schedule task at specified Date time. It will be executed only once on the time specified
schedule (TimerTask task, Date firstTime, long period) Schedule task at specified Date time. It will start executing from the specified date time and then repeat after the period specified henceforth
schedule (TimerTask task, long delay)Schedule task after delay time. It will be executed only once on the delay time specified from the current time
schedule (TimerTask task, long delay, long period)Schedule task after delay time with fixed delay period time unit execution thereafter. 
scheduleAtFixedRate (TimerTask task, Date firstTime, long period)Schedule task at specified Date time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 
scheduleAtFixedRate (TimerTask task, long delay, long periodSchedule task after delay time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 


How Java Timer works internally:

Internally Timer uses binary heap data structure to store Timer tasks. The constructor to create Timer object also creates Timer Thread with it and schedule method put the task on binary heap. It works on Object.wait() call to maintain Thread wait and notify.
Timer class is also thread-safe so multiple threads can simultaneously use it.

Java Timer Code Example :

import java.util.Timer;
import java.util.TimerTask;
public class JavaTimer {
  public static void main(String[] args){
  Timer timer = new Timer();
  TimerTask task = new TimerTask() {
      @Override
   public void run() {
    System.out.println("Inside Timer Task" + System.currentTimeMillis());
       }
  };
  System.out.println("Current time" + System.currentTimeMillis());
  timer.schedule(task, 10000,1000);
  System.out.println("Current time" + System.currentTimeMillis());
   }
}

Output :

Current time1455469505220
Current time1455469505221
Inside Timer Task1455469515222
Inside Timer Task1455469516222
Inside Timer Task1455469517222
Inside Timer Task1455469518222
Inside Timer Task1455469519222
Inside Timer Task1455469520222
Inside Timer Task1455469521222
Inside Timer Task1455469522222
Inside Timer Task1455469523222
Inside Timer Task1455469524222
Inside Timer Task1455469525222
Inside Timer Task1455469526222
Inside Timer Task1455469527222
Inside Timer Task1455469528223
Inside Timer Task1455469529223 and it goes on

Analysis :

The call to timer.schedule(task, 10000,1000) is going to schedule the task which is going to execute for first time (on another thread) after 10 second from this call. After that it will call again after delay of 10 seconds. It is important to mention here that if the task cannot be started after 10 seconds, next task call will not get pre-pond. So here the delay time between two consecutive task is fixed.

How to cancel Timer Thread:

To cancel and discard all scheduled task from the queue, cancel() method needs to be called. If there is any on-going execution, it will not interrupt in between. Rather it cancels all other scheduled task from the queue and after completion of on-going task(if any), Timer thread exits gracefully.

How to cancel already running Task:



To cancel already running task, you need to identify check points where you need to cancel the task. Take AtomicInteger as signal to cancel task and change its value inside cancel() method and when cancel signal comes then inside your task there are various check points which will check the value  and exit the task (Please remember to do cleanup/rollback as needed before existing the task thread).

Spring boot Interview Questions and Answers

What is Spring Boot?

Spring boot is the solution for creating standalone and production grade Spring application with very little Spring configuration.

Explain some features of Spring Boot?

Here are some features of Spring Boot:
  • It embeds web-application like Tomcat or Jetty directly
  • Comes with various already available maven's POM file to do minimal build creation code.
  • Automatically configure Spring
  • Provides inbuilt health-check feature
  • Provides inbuilt 'metrics' feature


    What is the advantage of Spring Boot?

    Following are the advantages of using Spring Boot:
    • Reduces lots of development time by providing boilerplate Java code and configuration
    • Easy to integrate with Spring ORM, Spring Security, Spring JDBC etc
    • Provides various plugins to develop, build and unit test Spring Boot applications with minimum effort.


      Explain the purpose of spring-boot-starter-batch?

      The purpose of spring-boot-starter-batch is to import all the dependency for the spring batch application. The advantage of it is that searching and configuring all the dependencies has become easier.

      What are the template engines that Spring boot supports?

      Spring boot supports the following template engines:
      • Groovy
      • FreeMarker
      • Mustache


        What is the main disadvantage of Spring Boot?

        Converting legacy Spring Framework application into Spring Boot application is not straight forward and is bit time consuming, which makes it difficult to port legacy Spring projects to Spring Boot application.



        That's all for interview questions and answers on Spring Boot. Please provide your feedback in comment section.

        Java Interview Questions on Atomicity

        Here are the list of 5 good questions on Volatile and Synchronized keywords in Java:

        1. What is Atomic variables and its significance:

        Atomic variables performs atomic operation on its object. In other words, it operation will happen completely or will not happen at all, and no one can interrupt its operation in between. With its introduction in Java 1.5, it is being widely used in multi-thread environment without any synchronization.

        2. Is Atomic variable more faster or variable through synchronized code?

        For read access, it does not matter whether it is atomic or non-atomic, synchronized or non-synchronized. For write access, atomic variable does not require lock to write because all update to variable happens atomic (either happened or not happened completely) For eg: suppose you want to do i++ in a multi-threaded application and multiple threads can call this, you need to synchronized i++ call (as it is set to 3 registry levels call and you know it can be context switch at any point of registry level calls even in between) to avoid dirty reads and inconsistent write. Atomic variable has just 1 registry level calls.

        3. What is the disadvantage of Atomic variables as compared to its primitive type?

        All Objects in java requires more care by the programmer to avoid memory consistency errors, doesnt matter whether it is Atomic or not. While the siblings of Atomic variable can be primitive and not object, it doesn't falls into object category and hence not required to take care of memory consistency error The reason why every object requires to avoid memory consistency errors in multi-threaded application is because each thread stack caches the copy of object locally on thread stack (Runtime optimization) might result into not in sync with actual copy of heap if it gets modified by another thread (even in the same code but different thread stack). One solution to avoid is to use volatile for that object which can be changed by another thread frequently. Also the local copy tries to in sync with heap copy very fast but problem occurs if your thread access it more faster than sync happens.

        4. How Atomic variables are implemented internally or how atomic variables achieves atomicity?

        With the introduction of additional register being added to cpu, atomic variables harness it to achieve atomicity. Since its just 1 cpu register call, it cannot be interrupted in between.

        5. What are the atomic variable classes in java?

        There are only two classes: AtomicInteger and AtomicLong. There is no atomic level classes for other primitives like double, float etc.

        Java Equals Hashcode Contract Example

        This the one of the most common question we used to face during Core Java interview, however its understanding is bit tricky. I will rather take unique approach to make the understanding simple.

        So, what is the contract between hashcode and equals to be used as a key to HashMap / HashSet?

        Java specification says that if you want to use any object as key to a hashmap or hashset or any other hashing, the contract is that
        If two objects are equal according to the equals method, then its hashCode method on each of the two objects must return the same integer result.

        Why so?

        To understand why this contract even come into picture, we need to understand how hashmap works. Usually in best possible scenario, the time complexity to retrieve an object from hashmap is o(1). In other words, if you ask to retrieve an object by providing key from a map of millions, it just know where exactly it is and goes directly to that object and fetch it without iterating other objects. Thats the beauty of hashing technique.

        Hashing Technique:

        To understand hashing technique in simple terms, consider you have written a letter to me to be delivered.
        Does the postman passes goes to each person and ask his name to find me?
        Definitely not. He sends your post to the pincode and then it searches among the pincode. Since in best possible scenario, there is only one person per pincode, the letter reaches to me directly. This the way hashing technique works.
        When you store an object to an hashmap, its stores on the key hashcode (also known as bucket). So, while retrieving in one shot, it requires the key hashcode again and thats why it is required to have same hashcode integer result every time. If it is going to give different hashcode, HashMap stores element on different code/bucket and trying to retrieve from different code/bucket, hence unable to retrieve object even-if it is present in hashmap on different bucket / hashcode / pincode.