Generics in Java with Examples

Generics in Java with Examples

Generics allows us to pass the generic types as parameters to a class or methods.
Example: class A<T>

Generics Advantages:

  • Stronger type checking
  • Casting elimination

Type Parameter Naming Conventions:

  • E – Element
  • K – Key
  • V – Value
  • N – Number
  • T – Type

There are various ways of using Generics, In this post let us see, generics with

  • Upper Bounded Wildcards
  • Unbounded Wildcards
  • Lower Bounded Wildcards

First let us see an example of using generics along with the class


Now let us see another example of using Generics with Key and Value along with Upper Bound Wildcards, Unbounded Wildcard and Lower Bound Wildcards.

Wildcards usually starts with “?” – Example: List<? extends Number>

Upper Bound Wildcards
Used to relax restrictions on a variable. In the below example we have used upperBound wildcard to pass integers, calculate sum of it and change it double and print it.

Unbounded Wildcards:
Unbounded wildcards is used for unknown types. It can be of any type, Integer or String or object etc..

Lower Bound Wildcards:
Lower Bound Wildcards restricts the unknown type to be specific. (Upper Bound relaxes the restrictions)



Read More

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