How to run two thread one after another in java

how to run two thread one after another in java.


How to run two thread one after another in java. To execute threads one after another it needs to be synchronized. wait notify notifyAll is useful.

This is the famous interview question for the beginners, 
Write a program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Expected Output:
 
A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.

Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java
package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted 

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Difference between wait notify notifyall example in Java.

Difference between wait notify notifyall example in Java.


Difference between wait notify notifyall example in Java. lets see difference between wait notify notifyall example using sample Java program.

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}


You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted 

Count trailing zeros in factorial of a number 

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

wait notify notifyall example in Java Thread.

wait notify notifyall example in Java.


wait notify notifyall example in Java Thread. how wait notify notifyAll works in Java. difference between wait, notify and notifyAll in java thread. 

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Running Threads In Sequence in Java

Running Threads In Sequence in Java. OR
Run Threads Sequentially in Java. OR
To Execute the Threads one after another in Java. OR
Synchronizing Threads in Java OR
Java Program to execute Threads in sequential order.


Running Threads In Sequence in Java. for sequential execution or to execute threads one after another in Java, threads must be Synchronized in Java. 

This is the famous interview question for the beginners, 
Write a program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Expected Output:
 
A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.

Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java
package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted 

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

Tower Of Hanoi Program in Java. 

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Why Prepared Statement is faster than Statement in Java JDBC.

Why Prepared Statement is faster than Statement in Java.


Prepared Statement is faster than Statement in Java. Prepared Statement is better because it caches query so is fast and prevents from SQL Injection.

This is the famous interview question for the beginners, So Let's see what it is all about.

SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query, and ultimately changes query purpose which upon execution gives harmful result.

Detailed explanation on SQL Injection: What is SQL Injection?


How can SQL Injection happen.


At server side, queries generally by themselves are not complete and require user data to make it complete, meaningful and executable.
"select * from user where username = ' " + username + " ' ";
Above query is not complete as it has dependency on username variable.
Now if username variable is filled by third party, then there are chances that user data contains SQL,

Take an example. Application is asking user to enter user name,
Enter user name:________________________

Enter user name:___jayesh'; delete from user where id='1__

At Server Side,

username = "jayesh'; delete from user where id='1"
Final Query = "select * from user where username = ' jayesh'; delete from user where id='1 ' ";

If you observe final query, upon execution it will delete the record from user table which was never the purpose of original query and this is called SQL Injection attack. 

Because of user data (which can be anything and uncontrolled) involvement in formation of query, SQL Injection attack can happen.

Detailed explanation on: How can SQL Injection happen?

How PreparedStatement in Java prevents SQL Injection?


To understand this, Lets see steps involved in query execution.
1. Compilation Phase.

2. Execution Phase.

Whenever SQL server engine receives a query, It has to pass through below phases,

Advantages of Prepared Statement in Java JDBC.

Advantages of Prepared Statement in Java.


Advantages of Prepared Statement in Java JDBC. benefit of using Prepared Statement is it prevents from SQL Injection. PreparedStatement is fast and gives better performance.

This is the famous interview question for the beginners, So Let's see what it is all about.

SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query, and ultimately changes query purpose which upon execution gives harmful result.

Detailed explanation on SQL Injection: What is SQL Injection?


How can SQL Injection happen.


At server side, queries generally by themselves are not complete and require user data to make it complete, meaningful and executable.
"select * from user where username = ' " + username + " ' ";
Above query is not complete as it has dependency on username variable.
Now if username variable is filled by third party, then there are chances that user data contains SQL,

Take an example. Application is asking user to enter user name,
Enter user name:________________________

Enter user name:___jayesh'; delete from user where id='1__

At Server Side,

username = "jayesh'; delete from user where id='1"
Final Query = "select * from user where username = ' jayesh'; delete from user where id='1 ' ";

If you observe final query, upon execution it will delete the record from user table which was never the purpose of original query and this is called SQL Injection attack. 

Because of user data (which can be anything and uncontrolled) involvement in formation of query, SQL Injection attack can happen.

Detailed explanation on: How can SQL Injection happen?

How PreparedStatement in Java prevents SQL Injection?


To understand this, Lets see steps involved in query execution.
1. Compilation Phase.

2. Execution Phase.

Whenever SQL server engine receives a query, It has to pass through below phases,

How Prepared Statement works internally in Java.

How Prepared Statement works internally in Java.


How Prepared Statement works internally in Java. Prepared Statement is part of Java JDBC API. PreparedStatement internally caches query.

This is the famous interview question for the beginners, So Let's see what it is all about.

SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query, and ultimately changes query purpose which upon execution gives harmful result.

Detailed explanation on SQL Injection: What is SQL Injection?


How can SQL Injection happen.


At server side, queries generally by themselves are not complete and require user data to make it complete, meaningful and executable.
"select * from user where username = ' " + username + " ' ";
Above query is not complete as it has dependency on username variable.

Now if username variable is filled by third party, then there are chances that user data contains SQL,

Take an example. Application is asking user to enter user name,
Enter user name:________________________

Enter user name:___jayesh'; delete from user where id='1__

At Server Side,

username = "jayesh'; delete from user where id='1"
Final Query = "select * from user where username = ' jayesh'; delete from user where id='1 ' ";

If you observe final query, upon execution it will delete the record from user table which was never the purpose of original query and this is called SQL Injection attack. 

Because of user data (which can be anything and uncontrolled) involvement in formation of query, SQL Injection attack can happen.

Detailed explanation on: How can SQL Injection happen?

How PreparedStatement in Java prevents SQL Injection?


To understand this, Lets see steps involved in query execution.
1. Compilation Phase.

2. Execution Phase.

Whenever SQL server engine receives a query, It has to pass through below phases,

Method Overloading Example In Java

Method overloading example program in Java OR
Method overloading Sample Code in Java.


Method Overloading Example In Java. Method Overloading sample code in Java. Method overloading example programs in Java.

What is method overloading?

If a class have multiple methods with same name but with different parameters list, it is known as Method Overloading. Parameters lists should differ in either,
  1. Number of parameters.
  2. Data type of parameters.
  3. Sequence of data type of parameters.