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.

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.


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.


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.


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.

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


Explain SQL Injection with example?


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. 

Method Overloading Interview Questions in Java

How compiler resolves ambiguous method overloading call. OR
Which overloaded method will get selected for null parameter in java. OR
Important Java Interview Questions On Method Overloading OR
Method Overloading Tutorial


Method Overloading Interview Questions in Java. Can we overload static method in Java. Method overloading Java rules.

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. 

Types of Binary Tree.

Types of Binary Tree.


Types of Binary Tree in Data Structure. Let's see Binary Tree types with example. There are mainly 3 types of Binary trees.

  1. Full binary tree / Proper binary tree / 2-tree / Strictly binary tree) 
  2. Perfect Binary Tree. 
  3. Complete Binary Tree:

Print Linked List In Reverse Order in Java

Print Linked List In Reverse Order in Java.


Print linked list in reverse order in java. print singly linked list in reverse order using recursion. java program to print linked list in reverse.

Let's understand the problem statement in simple words, 
You are given a Singly linked list, print the linked list in reverse way, from end to start.

Example: 
Input:     10 -> 20 -> 30 -> 40 -> 50 -> null
Output:  50      40     30      20      10
 


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

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


Find minimum unsorted subarray index m and n such that if you sort elements from m through n, then complete array would be sorted.

Let's understand the problem statement in simple words, 
Given an array of partially sorted integers, you have to find start index 'm' from where mismatch started that is the point from which array is not in sorted order,  and you have to find index 'n' till which index array is unsorted, and if you sort elements m through n, then entire array would be sorted.
 

Let's see example to understand what is the input and expected output.



Count trailing zeros in factorial of a number.

Count trailing zeros in factorial of a number.


Count trailing zeros in factorial of a number. there are many ways to count trailing 0 in factorial of number. Java program to count trailing zero.

What is Trailing Zero in a number?
Trailing zeros are a sequence of 0 in the decimal representation of a number, after which no other digits follow.

Example: 5! = 120
Number of Trailing Zero = 1

Example: 7! = 5040
Number of Trailing Zero = 1

Example: 10! = 3628800
Number of Trailing Zero = 2

Below you can get Factorial of number till 20 for testing Trailing Zeros in java program.

Swap two numbers In Java without using third variable.

Swap two numbers In Java without using third variable.


Swap two numbers In Java without using third variable. Write a program to swap/exchange 2 numbers without using temporary or third variable.

There are many approaches to solve this problem, we will see all of them one by one.


BFS vs DFS with Example in Java

BFS vs DFS with Example


Breadth First Search(BFS) Vs Depth First Search(DFS) with example in Java. DFS uses Stack while BFS uses Queue.

Given two words, startWord and endWord, and a dictionary, find the length of shortest transformation sequence from startWord to endWord.
Rules:

1. Only one letter can be changed at a time.
2. Each intermediate word must exist in the dictionary.

Input
startWord     = CAT
endWord      = DOG
dictionary    = CAT, BAT, COT, COG, COW, RAT, BUT, CUT, DOG, WEB 


Output

One shortest transformation is CAT –> COT –> COG –> DOG.
the program should return Path and its length 4.


Let's look at few more example and better understand problem statement.

There can be many paths for reaching from startWord to endWord, but we have to find shortest path possible.

Can static method be called using object in java

Java Interview Questions


Can static method be called using object in java. Static methods are called by Class name. Static members belongs to class.

Java interview questions and answers focused on "Method overriding and Method hiding".
There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Can we override static methods in java. Explain with example.

Can we override static methods in java. Explain with example.


Can we override static methods in java. Static methods cannot be overridden because Static methods are not polymorphic in nature.

 
Java interview questions and answers focused on "Method overriding and Method hiding". 

There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Method overriding and Method hiding Interview Question in Java

Method overriding and Method hiding Interview Question in Java


Method overriding and Method hiding Interview Question in Java. Can we Override static methods in java? What is method hiding in Java?  
 
Java interview questions and answers focused on "Method overriding and Method hiding".
There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Factorial of number in Java

Factorial of number in Java.


Factorial of number in Java. Factorial of number is product of a number and all number below it. Example: 5! = 5 * 4 * 3 * 2 * 1 = 120.

Factorial of 3
3! = 3 * 2 * 1 = 120.

Note: The value of 0! is 1

Below you can get Factorial of number till 20.

Reverse String in Java.

How to Reverse String in Java.


Reverse String in Java. String can be reversed using Iterative and Recursive approach. We will Reverse a String using Recursion and using loop. For reversing a String we should not use any inbuilt methods.

Input:      "Reverse String"
Output:   "gnirtS esreveR"

Input:      "HELLO"
Output:   "OLLEH"

Input:      "123 abc"
Output:   "cba 321"

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

When to use SOAP over REST Web Service.
Is REST service better than SOAP service?
Difference between SOAP and REST Web Service. OR
SOAP Vs REST Web Service.


When to use SOAP over REST Web Service. Is REST service better than SOAP service. Benefits of SOAP over REST service. 

Let's see, important difference between SOAP and REST Service which will help you decide which to choose among both.


How Floyd's Cycle finding algorithm work

How floyd's cycle-finding algorithm work.


How floyd's cycle finding algorithm work in java. Floyd's cycle finding algorithm helps to detect and remove loop in linked list.

What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Find start node of loop in linked list in Java

Identify start node of loop in Linked list.


Find start node of loop in linked list in Java. For identifying start node of cycle in Circular linked list, first detect loop in linked list.
 
Let's begin with, What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Floyd's Cycle Detection Algorithm in Java

Floyd's Cycle Detection Algorithm in Java. OR
Detect loop in Linked list.


Floyd's Cycle Detection Algorithm in Java. Floyd's Cycle finding algorithm helps to detect loop  in linked list. How Floyd's Cycle Algorithm works.
 

Let's start with, What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Find a Loop in Singly Linked List

Detect loop in Linked list.
Find Cycle in Linked list.
Identify start node of loop in Linked list.
Remove loop in Linked list.


Find a Loop in Linked List. To Detect cycle in linked list is popular interview question. Java Program to Detect loop in linked list in Java.

What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Remove loop from Linked list in Java

Remove loop in Linked list.


Remove loop from Linked list in Java. Given a linked list, detect and remove loop in Linked list? Java Program to remove loop in linked list.

Remove loop in Linked list.


Removing the loop in Linked list is simple,

After identifying the loop node, we just require the previous node of loop node, So that we can set it to NULL.

For identifying the previous node of loop node, we will keep the previousPointer pointing to just previous node of loop node.

CASE 2:
When the meeting node of both pointers in loop is start node or root node itself, in this case by just setting previousPointer to NULL will work because previousPointer is already pointing to last node of the linked list.

CASE 1:
When the meeting node of both pointers in loop is in-between the linked list, in this case, first task is to identify the start of loop node in the way as we saw above and then by setting fastPointer, which is already pointing to last node of list to NULL will work.

Program to Remove loop in linked list.


package linkedlist.singly;

public class RemoveLoopInLinkList {
 
 Node startNode;
 public static void main(String[] args) {
  RemoveLoopInLinkList g = new RemoveLoopInLinkList();
  
  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);
  
  g.startNode = n1;
  
  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);
  n8.setNext(n6);
  
  //Detect and Remove Loop in a Linked List
  Node newStart = detectAndRemoveLoopInLinkedList(g.startNode);
  g.printList(newStart);
 }
 
 private static Node detectAndRemoveLoopInLinkedList(Node startNode) {
  Node slowPointer=startNode;
  Node fastPointer=startNode;
  Node previousPointer=null;
  
  while(fastPointer!=null && fastPointer.getNext()!=null){
   slowPointer = slowPointer.getNext();
   previousPointer = fastPointer.getNext(); // For capturing just previous node of loop node for setting it to null for breaking loop.
   fastPointer = fastPointer.getNext().getNext();
   
   if(slowPointer==fastPointer){ // Loop identified.
    slowPointer = startNode;
 
    //If loop start node is starting at the root Node, then we slowpointer, fastpointer and head all point at same location. 
    //we already capture previous node, just setting it to null will work in this case.
    if(slowPointer == fastPointer){
     previousPointer.setNext(null);
     
    }else{
     // We need to first identify the start of loop node and then by setting just previous node of loop node next to null.  
     while(slowPointer.getNext()!=fastPointer.getNext()){
      slowPointer = slowPointer.getNext();
      fastPointer = fastPointer.getNext();
     }
     fastPointer.setNext(null);
    }
   }
  }
  return startNode; 
 }
 
 //Print linked list.
 private void printList(Node startNode){
  while(startNode!=null){
   System.out.print(startNode.getData() + " " ); 
   startNode=startNode.getNext();
  }
 }
 
} 
 

Check below images for better understanding on how Linked list containing loop looks like. 



Check Number is Palindrome in Java Program

Java Program to Check Number is Palindrome.


Java Program to Check Number is Palindrome. Number is called Palindrome, if the reverse of number is equal to original number. Example: 12321, 545.

In this post, we will see Algorithm to check whether number is palindrome or not.


Java Program to check whether Number is Palindrome or not.


It is very easy to check whether Number is Palindrome or not.

Approach 1:

In this approach, 
STEP 1: Reverse the original number.
STEP 2: Check, whether original number and reversed number is same. If Yes, then number is
               Palindrome otherwise not


 Lets understand above algorithm step by step with below example.



Java Program to Check number is Palindrome or not.
package com.javabypatel;

public class PalindromeCheck {
 public static void main(String[] args) {
  palindromCheck(12321);
 }

 private static void palindromCheck(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return;
  }

  int temp = number;

  int reverseNumber = 0;
  while(number > 0){
   int mod = number % 10; //Get last digit of number 
   reverseNumber = (reverseNumber * 10) + mod;  //Append Last digit got to reverseNumber.
   number = number/10; //Get the remaining number except last digit.
  }

  if(temp == reverseNumber){
   System.out.println("Number is Palindrome");
  }else{
   System.out.println("Number is not Palindrome");
  }
 }
}


Approach 2:

STEP 1: Convert the Number to String by using String.valueOf() method.
STEP 2: Reverse the String.
STEP 3: Compare Reversed String with String we got in STEP 1, if both are same then Number is 
              Palindrome else not.

package com.javabypatel;
class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome(12122));
 }  

 public static boolean isPalindrome(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return false;
  }
  String originalString = String.valueOf(number);
  String reversedString = "";
  for (int i = originalString.length()-1; i >= 0; i--) {
   reversedString += originalString.charAt(i); 
  }

  return originalString.equals(reversedString);
 }
}
 


Approach 3:
In Approach 2, we reverse the whole String and then compared it with original string. 
In Approach 3, we will check whether string is palindrome without reversing original string and by comparing the characters of original string from both end that is from front and back together.

STEP: 1
Take 2 variable, pointer1 and pointer2. 
pointer1 initialise to index 0 and pointer2 initialise to originalString.length()-1.

STEP 2:
Compare characters at pointer1 and pointer2, if they are not same, then they are not Palindrome and stop. If they are same then increment pointer1, decrement pointer2.

STEP 3: Repeat STEP 2 til pointer1 < pointer2.
class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome(1221));
 }  

 public static boolean isPalindrome(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return false;
  }
  String originalString = String.valueOf(number);
  
  int pointer1 = 0;
  int pointer2 = originalString.length()-1;
  
  while(pointer1 < pointer2) {
   if(originalString.charAt(pointer1) != originalString.charAt(pointer2)) {
    return false;
   }
   pointer1++;
   pointer2--;
  }
  return true;
  
 }
}


I hope below diagram wil help you understand algorithm in better way. 

You may also like to see




Enjoy !!!! 

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

SQL Injection attack example in Java.

Explain SQL Injection along with example?


SQL Injection attack with Example in Java. Let's see what is SQL Injection. How SQL Injection attack works. How to prevent SQL Injection. SQL Injection is code injection technique.

SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query. Injected SQL data alters the purpose of original query and upon execution can gives harmful result.  

A SQL injection attack is very dangerous and attacker can,
1. Read sensitive data from the database.
2. Update database data (Insert/Update/Delete).

3. Slowdown the complete Database system etc.


Analysis of Heap Sort Time Complexity.

Analysis of Heap Sort Time Complexity.


Analysis of Heap Sort Time Complexity. Heap sort worst case, best case and average case time complexity is guaranteed O(n Log n). Heap sort space complexity is O(1). 

 

Heap Sort Time Complexity


1. Heap sort has the best possible worst case running time complexity of O(n Log n).
2. It doesn't need any extra storage and that makes it good for situations where array size is large.


Before looking into Heap Sort, let's understand what is Heap and how it helps in sorting.

What is Complete Binary Tree?


A Complete binary tree is a binary tree in which every node other than the leaves has two children. In complete binary tree at every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Let's understand with simple words now,
If a Binary Tree is filled level by level, left to right (Left child followed by Right child.) then it is called complete binary tree.
If Right child is present without Left child then it is not complete.



Analysis of Bubble Sort Time Complexity

Analysis of Bubble Sort Time Complexity.


Analysis of Bubble Sort Time Complexity. Bubble sort worst case time complexity is O(n^2), best case is O(n) and average case time complexity is O(n^2). Bubble Sort Java Program.

Time Complexity of Bubble Sort Algorithm.


1. Time complexity of Bubble sort in Worst Case is O(N^2), which makes it quite inefficient for 
    sorting large data volumes.
    O(N^2) because it sorts only one item in each iteration and in each iteration it has to compare n-i 
    elements.
2.
Time complexity of Bubble sort in Best Case is O(N)
    When the given data set is already sorted, in that case bubble sort can identify it in one single
    iteration hence O(N).
    It means while iteratng, from i=0 till arr.length, if there is no swapping required, then the array 
    is already sorted and stop there.
3. Bubble sort can identify when the list is sorted and can stop early.
4. Bubble sort is efficient for (quite) small data sets. 

5. It is Stable sort; i.e., does not change the relative order of elements with equal keys.
6. It takes O(1) extra space.


Let's see Bubble sort java program, How Bubble sort works in Java, Bubble sort Algorithm in java. 


Sort array using Bubble sort in Java.
Lets understand what is the input and the expected output.