Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift

Bitwise Operators in Java – Right Shift, Left Shift and Unsigned Right Shift:
Java Operators are basically divided into six types,

  • Arithmetic Operators
  • Relational Operators
  • Assignment Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise Operators

In this article, We are going to cover Bitwise Operators. We might face some questions in interviews regarding Bitwise operators. So lets us understand what are bitwise operators with examples.

There are 3 types of Bitwise Operators,

  • Left Shift
  • Right Shift
  • Unsigned Right Shift

Before going ahead, Let us understand what these operators do,

Left Shift Operator:

  • Left shift Operator is declared as <<
  • Left shift operator performs the operation of Multiplication
  • The sign of the the integer, Positive or negative impacts the result of left shift operator
  • Example:
    • 2 << 5
    • Output will be 64. (2^0 * 2^1*…2^5)

Right Shift Operator:

  • Right shift operator is declared as >>
  • Right shift operator performs the operation of Division
  • The sign of the integer, Positive or negative impacts the result of Right Shift Operator
  • Example:
    • 2 >> 5
    • Output: 0, (5 is divided by 2)

Unsigned Right Shift Operator:

  • Unsigned Right Shift Operator is declared as >>>
  • Irrespective of sign, It shifts the bits to 0.
  • Example: -14 >>> 2
    • This is include 2 zero’s (>>>2 — we are requesting it to shift 2 bits) to the left, followed by the value

Once we go through the example, We will be able to understand this clearly.



Now let us see how this output works,

First we are getting the binary value of Both +7 and -7

7 << 2: Left shift is for multiplication,

7^0 = 7
Actual value is 28 and Binary value is 11100 –> Left Shift Operator Output.

Now for the Second Output,
Right Shift Operator is for division,

7 >> 2: Right Shift for Division,

2 Divided by 7, Not divisible so the value is 1. –> Right Shift Operator Output

Now the Unsigned Right Shift Operator,

7 >> 2 and 7>>>2 are always same, except 2 Zero’s are added to the left of the output. 
-7 >>> 2:
Binary value of -7: 11111111111111111111111111111001, Now we shift 2 Zero’s to the left,
Output is,

If we use, -7>>> 3 (3 zero’s to the left) Output will be,

Read More

Comparable and Comparator in Java

Comparable and Comparator in Java:

What is Comparable and Comparator?
Comparable is an interface used for sorting the objects. It supports Single sorting only.
Comparator is an interface used for Sorting, but supports multiple sorting.

Difference Between Comparable and Comparator:

Comparable Comparator
Compatable interface is used for Single sorting and overrides CompareTo() Comparator interface is used for Multiple Sorting and overrides Compare()
java.lang.Comparable java.util.Comparator

Comparable Example:
In comparable, We select a single object and compare with others to sort it. In this example, We are going to select one number and compare it with other numbers and sort them.




Comparator Example:
In comparator, We select two objects and compare them with each other and make the sort.




Read More

OOPS Concepts – Inheritance, Polymorphism, Abstraction and Encapsulation

OOPS Concepts – Inheritance, Polymorphism, Abstraction and Encapsulation:
What is OOPS?
Object Oriented Programming (OOP) is a methodology to write a program using classes and objects.

What is Inheritance?
When one object gets all the properties of super class or parent class is known as Inheritance. Subclass can also have its own properties in addition to parent class properties.

What is Polymorphism?
An object that takes various forms is known as Polymorphism.

What is Abstraction?
Hiding implementation details and showing essential features is known as abstraction.

What is Encapsulation?
Encapsulating (wrapping) the data and code into a single entity is known as Encapsulation.

Encapsulation and Abstraction seems like almost same, Let us see the difference between encapsulation and abstraction.

Abstraction Encapsulation
Abstraction helps at design level Encapsulation helps at implementation level
Abstraction hides irrelevant data and shows what is required Encapsulation hides the data to protect it from other developers

Inheritance Example:
We have a class Employee that has one property employeeName. We have another class ContractEmployee that has property salary. Now ContractEmployee extends Employee class. So ContractEmployee class can use the property  employeeName of Employee Class. This is known as Inheritance.

Output: Inheritance

When one object takes various forms. Before proceeding to example, We must know what is Method Overriding and Method Overloading in Polymorphism.

Method Overriding:
When same method name used in both Parent class and subclass with same arguments and same return type, Then the method can be overridden.

We need to make sure,

  • Arguments and Return type should be same for the method in parent class and subclass
  • Subclass must extend parent class to implement Method Overriding
  • Access level should not be restrictive

Method Overloading:
Method overloading is two or more methods having same name both in parent class and subclasses but with different arguments.

In this example, We have a method Display() in Parent class (Employee) and Subclass (ContractEmployee). We have a Calculate method both in Parent class and Subclass but with different arguments. We have created objects and we call methods in Display() method. We have implemented both Method Overriding and Method Overloading in this example.

Output: Polymorphism


Hiding Irrelevant data and show only necessary data.

In this example, We have an abstract class with an abstract method and non-abstract method. So when abstract class is extended, it shows abstract method but hides non-abstract method. Showing only the necessary method and hiding unwanted method is known as abstraction.

Output: Abstraction


Hiding data from outside world.

In this example, We have two properties, String name and string department. We have assigned name = “Beta” and department = “Java”. These properties are accessible only within the same class and outside class cannot access these properties. But outside class can use getters and setters for accessing variables. Thus the Beta and Java are hided to outside class.

Output: Encapsulation


Read More

Thread Synchronization in Java

Thread Synchronization in Java:
What is Synchronization?
When two or more threads access the same field at the same time, it results in concurrency issues and the results will be wrong. Synchronization makes sure that, even if we start multiple threads only one thread can access a resource at a time. This is known as Synchronization.

Points to Note:

  • When we use synchronize, it means only one thread can access a resource at a time. Means that the thread acquires a lock, so no other threads can access it.
  • Only Methods can be synchronized, not classes
  • A class can have both synchronized and non-synchronized methods
  • When multiple threads are trying to access synchronized method with same instance object, Only one thread can acquire the lock. Another thread has to wait till one thread finishes the operation and releases the lock.
  • When thread goes to sleep, it does not release the lock.
  • When a thread does not get lock, it has to wait till the executing thread releases the lock. But, that does not mean the longest waiting thread for that lock will get it, the lock may be acquired by any thread that will waiting for the lock irrespective of thread waiting for long or short time.

One of the most famous issue of Threads. Deadlock happens when, Consider there are two threads Thread A and Thread B.  Thread A enters a synchronization code 1 and acquires lock. Thread B enters another synchronized code 2 and acquires a lock.  A needs access to Synchronized code 2, to complete its process. B Needs access to Synchronized code 1 to complete. This situation where A waits for B to release the lock to complete and B inturn waits for A to release the lock to complete. Both threads wait for each other to release the lock. This is known a Deadlock.

In short, Thread 1 waits for Thread 2 to release the lock and Thread 2 waits for Thread 1 to release the lock.

wait(), notify() and notifyall():
Important Note:
These three methods are must be called within synchronized code. These methods cannot be called on an object unless object has the lock.


Class Objects Class Threads
wait(), notify(), notifyall() sleep(), join(), yield()

It informs the thread to release the lock and go to sleep, until some other thread enters and calls the notify() method.

It wakes up one thread from sleep that called wait() method from same object. But this does not mean that wake-up thread acquires lock. This method just notifies the sleeping thread that it can wake up. The waked up thread needs to wait till the thread (that called notify()) completes its process.

This method wakes up all the threads that called wait() in the same object.

Synchronized (object){

We are calling all these methods with object in synchronized context.

Now let us see an example with and without synchronization,
Example 1: Without Synchronization
We have an variable amount(100) in class balance. There are two persons trying to withdraw that money. They will make 2 transactions (50) each. Now let us see the output without synchronization.

Output: Without Synchronization
From output, We can see the concurrency issues. Amount withdrawn by person 2 is 50, But still we can see amount available is 50 and 100. This issue will happen when multiple threads try to access same resource.

Example 2: With Synchronization:
Now with the same example, We are going to add synchronize to the method. So, Only one thread will get the lock and process and another thread will wait till the executing thread releases the lock.
Expected Output:
One thread should access the block at a time, it should make 2 transactions. The balance amount will be 0. So no amount should be available for another thread.

Output: With Synchronized:
Now we can see, Person 1 makes two successful transactions and amount becomes 0. When person 2 tries to withdraw money, there is no money. Only one thread access the resource at a time and another thread waits till execution thread completes its process.


Read More

Threads – An Introduction

Threads – An Introduction:
What is a Thread?
Thread in java means, sequential path followed by a program in execution. All the java programs have atleast one thread (main thread).

Defining a Thread:
There are two ways of defining a thread,

  • Extending java.lang.thread
  • Implementing Runnable Interface

When working with threads, it executes run method. We need to write the code that needs to be run in separate thread in run() method

Best Way for Thread:
It is always a good practice to Implement Runnable Interface. As Java does not support Multiple inheritance, If we extend thread class we cant extend any other class. So it is always better to implement Runnable.

How to Start a thread:
Even when we have code written in run() method for execution, We need Thread object to do the job for us. So in order to make thread start, We need to create thread object,

Extending thread class,
Thread thread = new Thread();

Implements Runnable,
Runnable runnable = new Runnable();
Thread thread = new Thread(runnable);

How to start multiple Threads?
We need to create multiple thread objects and use start() to start multiple threads, Here is a simple example

As you can see, We have started 3 threads, But the behavior is not same. Each time when you execute the code the thread output will differ.

Thread States:

  • New
  • Runnable
  • Running
  • Waiting/Sleeping/Blocked
  • Dead

When thread instance has been created but start() method is not been invoked.

When thread is eligible to run but it is not running. When start() method is invoked thread becomes Runnable state, also when thread comes back from sleep or waiting it will be in Runnable State.

When the thread is executing, it is in Running state.

This is the state when thread is not eligible to Run. The thread might be blocked, or waiting for some resource or developer might invoked sleep method

Thread is said to be dead when run() method completes. Once the thread is dead, we cant start that thread again. If we try to start the dead thread using start(), it will throw an exception

Thread Priorities:
We can set priorities for the thread for execution.
         Thread thread = new Thread();

Once we set priority, at any given time thread that runs will have the highest priority than other threads.

But Still…
When two or more threads have same priority, then the behavior is not guaranteed. It depends on the scheduler to decide which thread to run.

Yield ():
Yield is a Static method.  The work of yield() is to give equals chances to other threads with same priority. That is, It will make the running thread pushed to runnable state and gives chance to another thread with same priority. But that does not mean that Same thread might be get chosen again over others. The fact is yield does not do what it claims to do.

join is a non-static method. Join() allows one thread to join at the end of another thread. If Thread one cant execute until thread two is completed, Then thread one will join at the end of thread two. This causes the current thread to stop until the thread it joins completes.

Read More