What is difference between (| and || ) and ( & and && ) in Java.

Posted on Updated on

6db3a-downloadThe operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean on both left and right side.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

| is the binary or operator
|| is the logic or operator

Below are some conclusion here :

the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&, ¦¦) and ternary operator
behaviour can produce unexpected results if you’re not careful. For example, the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available:

int i = 10;
int j = 12;

if( (i<j) ¦ (i=3) > 5 ) // value of i after oper: 3
if( (i<j) ¦¦ (i=3) > 5 ) // value of i after oper: 10

if( (i>j) & (i=3) > 5 ) // value of i after oper: 3
if( (i>j) && (i=3) > 5 ) // value of i after oper: 10

  • with & and ¦ both operands are always evaluated.
  • with && and ¦¦ the second operand is only evaluated when it is necessary.
  • with ¦¦ (i<j) evaluates to true; there is no need to check the other operand as ¦¦ returns true if either of the operands are true.
  • with && (i>j) evaluates to false; there is no need to check the other operand as && returns true only if both operands are true. In this case one is false so there is no need to check the other operand

What is Defensive Copying , Shallow Copy and Deep Copy ?

Posted on Updated on

Defensive copying is concerned with protecting mutable objects e.g. objects who’s state can be modified by the user. If you were pass back the reference of an object any changes a user made to that copy of the object would effect your object because you are only passes a reference to the object and not the actual object itself. This is known as a shallow copy.
To avoid users being able to change the values of your object you can pass back a defensive copy. This means that instead of passing back a reference to your object it passes back a new object but with the same values. This means that any changes the user makes to that copy of the object doesn’t change the value/state of your object.
It’s an interesting idea but I can’t think of a use for this at the moment but I’m sure one day this will come in useful.

Before knowing about Shallow Copy and Deep Copy you need to know about Clonable interface.

Clonable interface –
Java has a clonable interface for make clone of any object.
Clonable Interface is a marker interface.
Clonable Interface has no method.
Class which implements Clonable interface, JVM give the permission for making the clone of         this class.

Shallow Copy –  
Clone can be archived by object.clone() method. It gives the Shallow copy of the object. In this process a new object is created That have all the value and instance variable. And if main object has any references to other object then the references are copied in the shallow copy.

Example – 

class A implements Cloneable{
    A(String personName, Integer age){
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    private String personName = null;
    private transient Integer age = null;
    public Integer getAge() {
        return age;
    public String getPersonName() {
        return personName;

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        A a = new A("Albar", new Integer(50));
        A a1 = (A)a.clone();

Deep Copy:- 
Deep Copy of any object can be achieved by write the object into byte stream and again deserialize it. It gives the Deep Copy of the object. Deep copy is a totally duplicate copy of an object.
And if main object has any references to other object then the complete new copies of those objects will be available  in the Deep Copy.

Example to get Deep Copy – 

class A implements Serializable{
    A(String personName, Integer age){
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    private String personName = null;
    private transient Integer age = null;
    public Integer getAge() {
        return age;
    public String getPersonName() {
        return personName;

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        try {
            A a = new A("Albar", new Integer(50));
            A deepCopy = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(bos);


            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            Object obj = in.readObject();
            deepCopy = (A)obj;
            catch(IOException e) {
            catch(ClassNotFoundException cnfe) {

What is Static and Dynamic binding in Java

Posted on Updated on

java-logo It is important to get to know the concept of earlier binding and late binding ( static and dynamic binding ) for every level of Java guys, Also it became a popular interview question which make confuse during interview but good concept always appreciable.

In this section we will explain with good example of how to achieved these two concept and how Java recognized binding is Static or Dynamic.

Most of Java guys says, binding is held at compile time is call earlier binding or static binding like method overloading and binding is held at run time is call dynamic binding like method overriding. Which is enough to make sense for interviewer but If interviewer screw this concept on practical ways and asked you to give  correct output of given code snippet then real confusion get started.

Key Points:-

  • earlier binding is also called as static binding and dynamic binding is also called as run-time binding.
  • method overloading is used to achieved static binding while method overriding is used to achieved dynamic binding.
  • Compiler checks Object Type to achieved Static binding but Dynamic binding used object reference at run-time to call corresponding override method in a Class.
  • Dynamic binding is slower than Static binding because at run time it takes  extra time to find out which method to be called. like C++ virtual table.
  • A method to be called method overload when method name same but number of parameters or type of parameter must be different but A method is called method override when method name is same as well parameter.
  • static or final or private method can be overload but it can’t override.
  • Using return type method overloading can’t be achieved but using covariant return type method override could be achieved. similarly covariant throws exception type.
  • Method overload happened within a class but Method override happened at sub-classes.


As below given snippet code need to be considered the binding type and it’s Output.

Compile-time binding example:-

public class CheckBindingType {

	public void print(Object obj) {
		System.out.println(" Print Object");

	public void print(String str) {
		System.out.println(" Print String");

	public static void main(String args[]) {
		Object obj = new String("Hello,This is String Initilization");
		CheckBindingType type = new CheckBindingType();

// Output : "Print String" because the JVM will search for the method from the most specific type to least specific type. 
} } 

In this above code, It is compile time binding. Here, object of CheckBindingType Class call print(obj) method, then Compiler will check the type of “obj”  which is Object Type  and then it look for  print(Object) method and bind the call to this method. hence result will be “Print Object”.

Dynamic binding example:-

class Shape{
	public void draw(){
		System.out.println(" Shape Draw");
class Circle extends Shape{
	public void draw(){ // This is method override here
		System.out.println(" Circle Draw");
	public void draw(int x){ // This is method overloading
		System.out.println( " Circle Draw at "+x);

public class CheckBindingType {

	public static void main(String args[]) {
		Shape shape0 = new Circle();
		shape0.draw();  //  Circle Draw
		Shape shape1 = new Shape();
		shape1.draw(); //  Shape Draw
		Circle circle1 = new Circle();
		circle1.draw(); // Circle Draw
		circle1.draw(10); // Circle Draw at 10
		//Circle circle2 = new Shape(); 
                // Compile time exception, SubType cann't allow to hold the reference of Parent Type.


Output :-

Circle Draw
Shape Draw
Circle Draw
Circle Draw at 10

In this below code snippet, It’s Dynamic binding which occurs at run-time. In example, Shape class has a Overridden method “draw()” which overrides into respective sub-class Circle having one additional method “draw(int)”  that’s overloading in this class.

In main class CheckBindingType, draw() method is being called by object i.e Shape or Circle. At run time Java check object reference type if object referenced type is Shape then it call Shape’s draw(), if object hold reference of Circle then it call Circle’s draw().

Hence, first case Shape Type hold reference of sub-class Circle then draw() of sub-class will be called. similarly 2nd and 3rd case, Shape’s draw() and Circle’s draw()  will be called.


Fail-fast vs Fail-safe Iterator

Posted on

fail-fast vs fail-safe


Since Jdk1.5, It’s becoming a popular interview question today, reason is it touches a bit concurrent package and interviewer can ask more about concurrent package like have you ever used concurrent package in your project if yes then “what concurrent package did you use, explain it.” . This is up to you how to answer those question otherwise say “No”.

In this article, we will discuss how “fail-fast and fail-safe iterator” implemented in Java and it advantage.

fail-fast Iterator occurred when structure of Collection has been modified by one or more Thread during iteration process. Thus in the face of Concurrent modification failed and throw ConcurrentModificationException.

Suppose, we have a Set of Object, In the way One Thread try to iterate over the collection using iterator() and meanwhile structure of collection has been changed by adding,removing or updating element at a same time, Since java.util.Iterator doesn’t support concurrent modification so it will throw an exception.


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CheckFailFast {

	public static void main(String args[]) {
		Set setOfName = new HashSet();

		Iterator it = setOfName.iterator();
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("Santosh")) {
			} else {
				System.out.println(" Name is " + key);


Output here :-

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at CheckFailFast.main(CheckFailFast.java:16)

fail-safe Iterator never throw Exception during iteration process, just because fail-safe works on clone of collection rather than original collection that’s why it is called fail-safe iterator.

Iterator of ConcurrentHashMap keySet is also fail-safe and never throw “java.util.ConcurrentModificationException


import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CheckFailSafe {
	public static void main(String args[]) {
		Map<String,String> map = new ConcurrentHashMap<String,String>();

		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			if (key.equals("Santosh")) {
			} else {
				System.out.println(" Name is " + key);


Output here :-

Name is Wasim
Name is Amit
Name is Ajay

Why Java ?

Posted on Updated on

Why Java


Today Java became a fundamental programming language that is used to develop application,web ,plugin and mobile application. Simple reason is cross platform,multi-threading capability,object oriented,security,robustness,distributed programming and more.

Why Java ?

We are quite sure that you have heard of Java programming language but there are also many programming language as well such that python,Ruby and C++ to name few. However Java is still one of favorite choice for developer for many reasons. As of date, Java is one of most secure programming language that is used in most of Banking domain and other security base application due to security in nature. Java use own ‘sandbox’ to run untrusted code obtained from open Network.

In addition to that, many enterprise solutions also make use of Java due to the possible types of integrations associated with it. For example, through Java, it is possible to integrate the
application or product with various web services such as payment gateways, crud applications as well as health domain applications. Suffice to say that the possibility through Java can easily be endless but it doesn’t mean that everything should be developed with Java.

Java has been the solution to various platforms that are both developing and stable. In fact, there are many noteworthy companies and projects that use Java for their day-to-day jobs. Some of the ones that you might have heard include Google Maps, Blu-ray discs, Kindle and a few other devices. In addition to that, laptops, supercomputers, and cell phones are also supported by Java making it a very versatile language as compared with others.

In statistical terms, there are roughly 1.1 billion desktops that run Java, 3 billion smartphones running Java, 1.4 billion Java Cards manufactured and is also being used in GPS systems, parking payment stations, lottery terminals, ATMs and many more. That is the power of Java not found in any other platform in the market.

Following are some Java development technologies, tools, and frameworks used to design complex architectures and built applications:

  • Struts, Spring, Hibernate and JPA
  • JAXB and Apache Axis 2/Java
  • JSP, Servlets, JDBC, EJB, JMS, JTA and JUnit
  • Apache Tomcat, JBoss and GlassFish
  • JavaScript, JSF, GWT,AngularJS and jQuery
  • Eclipse, Netbeans and JBoss tools
  • TestNG
  • jBPM and Drools
  • JCR

Why do Programmer choose Java ?

In short, Java is a solution to build a stable, reliable and secure application that run on cross-platform due to platform independent nature. It’s fast and high the performance of application due to atomically handle garbage collector i.e robustness. In fact today most of web site wouldn’t run unless your install JDK in your machine.

Key feature of Java :-

  • Looks familiar to existing programmers: related to C and C++:
  • Omits many rarely used, poorly understood, confusing features of C++, like operator overloading, multiple inheritance, automatic coercions, etc.
  • Contains no goto statement, but break and continue
  • Has no header files and eliminated C preprocessor
  • Eliminates much redundancy (e.g. no structs, unions, or functions)
  • has no pointers

Added features to simplify:

  • Garbage collection, so the programmer won’t have to worry about storage management, which leads to fewer bugs.
  • A rich predefined class library

Java is an object-oriented language, which means that you focus on the data in your application and methods that manipulate that data, rather than thinking strictly in terms of procedures.
In an object-oriented system, a class is a collection of data and methods that operate on that data. Taken together, the data and methods describe the state and behavior of an object. Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass.

Java comes with an extensive set of classes, arranged in packages, that you can use in your programs.

  • It has a spring-like transparent RPC ( Remote Procedure call ) system
  • Now uses mostly TCP/IP based protocols like ftp & http

Java supports various levels of network connectivity through classes in the java.net package (e.g. the URL class allows a Java application to open and access remote objects on the internet).


The Java compiler generates byte-codes, rather than native machine code. To actually run a Java program, you use the Java interpreter to execute the compiled byte-codes. Java byte-codes provide an architecture-neutral object file format. The code is designed to transport programs efficiently to multiple platforms.

  • rapid turn-around development
  • Software author is protected, since binary byte streams are downloaded and not the source code

Java has been designed for writing highly reliable or robust software:

  • language restrictions (e.g. no pointer arithmetic and real arrays) to make it impossible for applications to smash memory (e.g overwriting memory and corrupting data)
  • Java does automatic garbage collection, which prevents memory leaks
  • extensive compile-time checking so bugs can be found early; this is repeated at runtime for flexibility and to check consistency

Security is an important concern, since Java is meant to be used in networked environments. Without some assurance of security, you certainly wouldn’t want to download an applet from a random site on the net and let it run on your computer. Java’s memory allocation model is one of its main defenses against malicious code (e.g can’t cast integers to pointers, so can’t forge access). Furthermore:

  • access restrictions are enforced (public, private)
  • byte codes are verified, which copes with the threat of a hostile compiler
  • Compiler generates byte codes, which have nothing to do with a particular computer architecture
  • Easy to interpret on any machine

Java goes further than just being architecture-neutral:

  • No “implementation dependent” notes in the spec (arithmetic and evaluation order)
  • standard libraries hide system differences
  • the Java environment itself is also portable: the portability boundary is POSIX compliant

Java is an interpreted language, so it will never be as fast as a compiled language as C or C++. In fact, it is about 20 times as slow as C. However, this speed is more than enough to run interactive, GUI and network-based applications, where the application is often idle, waiting for the user to do something, or waiting for data from the network.


Java allows multiple concurrent threads of execution to be active at once. This means that you could be listening to an audio clip while scrolling the page and in the background downloading an image. Java contains sophisticated synchronization primitives (monitors and condition variables), that are integrated into the language to make them easy to use and robust. The java.lang package provides a Thread class that supports methods to start, run, and stop a thread, and check on its status.

Java was designed to adapt to an evolving environment:
  • Even after binaries have been released, they can adapt to a changing environment
  • Java loads in classes as they are needed, even from across the network
  • It defers many decisions (like object layout) to runtime, which solves many of the version problems that C++ has
  • Dynamic linking


In this article we try to explore about Java and it’s feature which may be help you to choose a better and powerful language to develop an application. Please follow me at social network as well.


Difference between TreeMap and TreeSet in Java

Posted on Updated on

Today it’s going to vital in Java interview asked question about difference between Map implementation and Set implementation  like TreeSet vs TreeMap, HashSet vs HashMap and Hashtable vs HashMap. If your preparing for Java Interview question/Answer then must go though all these points. It helps you to get a credit in Interview.

Key Points :-

  • Both internally used Red-Black tree.
  • Object which is said to be unequal using compareTo() is return false even if it is equals using equals() method. so compareTo() and equals() does not work in consistent way.
  • Both guaranteed log(n) time cost for operation like get,put,containKey and remove.
  • Both guaranteed that Objects or Key Objects will be sorted order according to object comparable or custom comparator given in constructor argument. In case object is not  implemented comparable interface and to be added into TreeSet then an exception would thrown like “Exception in thread “main” java.lang.ClassCastException: User cannot be cast to java.lang.Comparable”
  • Both are not synchronized means it’s not used in concurrent application.
  • Both Iterator are “fail-fast” means it will throw ConcurrentModificationException when TreeMap or TreeSet is modified structurally once Iterator is created.
  • Null value is not permitted neither in TreeSet nor TreeMap.

Difference between TreeMap and TreeSet in Java .

Now see the difference between these two type:-

  1. Main difference between TreeMap implemented NavigableMap interface underlying Map interface and TreeSet implemented NavigableSet interface underlying Set.
  2.  Second difference between TreeMap and TreeSet is the way they store objects. TreeSet stores one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.
  3. TreeSet does not allowed to store duplicate Object while duplicates value are allowed to TreeMap.

Example code here :-

import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;

public class TreeSetAndMapExample {

public static void main(String args[]) {
User user1 = new User("Ajay", "10001");
User user2 = new User("Santosh", "10002");

TreeSet empTree = new TreeSet();
// empTree.add(null); //Exception in thread "main"
// java.lang.NullPointerException
System.out.println("Size of TreeSet " + empTree.size());
Iterator it = empTree.iterator();
while (it.hasNext()) {

System.out.println(" TreeMap implementation here -");
TreeMap<User, User> empTreeMap = new TreeMap<User, User>();
empTreeMap.put(user1, user1);
empTreeMap.put(user2, user2);
empTreeMap.put(user1, user1);
// empTreeMap.put(null,user1); // Exception in thread "main"
// java.lang.NullPointerException

System.out.println("Size of TreeMap " + empTreeMap.size());
Iterator itMap = empTreeMap.keySet().iterator();
while (itMap.hasNext()) {


output here :-

Size of TreeSet 2
User [name=Ajay, emp_id=10001]
User [name=Santosh, emp_id=10002]
TreeMap implementation here –
Size of TreeMap 2
User [name=Ajay, emp_id=10001]
User [name=Santosh, emp_id=10002]


class User implements Comparable {
private String name;
private String emp_id;

public User(String name, String emp_id) {
this.name = name;
this.emp_id = emp_id;

public String getName() {
return name;

public void setName(String name) {
this.name = name;

public String getEmp_id() {
return emp_id;

public void setEmp_id(String emp_id) {
this.emp_id = emp_id;

public int compareTo(User o) {
// TODO Auto-generated method stub
return this.name.compareTo(o.name);

public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", emp_id=")
return builder.toString();


What is Singleton pattern and it’s uses ?

Posted on Updated on

What is Singleton pattern and it’s uses ?

This is most frequently asked question in Java interview for freshers, their uses in developement. In this article we will discuss following topics :-

  • What is Singleton Pattern ?
  • How to implement in coding ?
  • How many possible way to create a Singleton object in Java.
  • What is double check in Singleton Pattern and advantage of it.

Singleton is a creation Design pattern, it’s used to control the initialization of Object and ensure that only one instance of Object will be created in the Java Virtual Machine.In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects

Key Points :-

  • Global access point, a scope of Singleton object is Global or an application level.

How to implement in coding ?

There are various way to implement singleton class in Java.

  1. Class-loader static initialization or Eager Loading
  2. synchronized or Lazy Loading
  3. Using Enum

Implementation with Class-loader static initialization or Eager Loading :-

In this case class loader initialized the Object instance at the time of loading and subsequently calling this method get same object reference. It slow the application start-up performance.

public class MyFactory {
  private static final MyFactory instance = new MyFactory();

  public static MyFactory getInstance() {
    return instance;

  private MyFactory() {}

Implementation with Synchronized i.e Lazy loading:-

In this case, a thread calling this method getInstance() an Object will be created and second time onward all subsequently calling this method point to same reference.  This is also call on demand object creation.

public class MyFactory {
  private static MyFactory instance;

  public static synchronized MyFactory getInstance() {
    if (instance == null)
      instance = new MyFactory();
    return instance;

  private MyFactory() {}

Implementation with Enum example:-

Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment

public Enum MyFactory {
  private static final ConnectionFactory factory = new ConnectionFactory();

  public Connection getConnection() {
    return factory.getConnection();

Question: Why can’t we use a static class instead of singleton?

  • One of the key advantages of singleton over static class is that it supports inheritance.while the static class cannot
  • Another difference is that static class will have all its member as static only unlike Singleton.
  • Another advantage of Singleton is that it can be lazily loaded whereas static will be initialized whenever it is first loaded.
  • Singleton object stores in Heap but, static object stores in stack.
  • We can clone the object of Singleton but, we can not clone the static class object.
  • Singleton can use the Object Oriented feature of polymorphism but static class cannot.

Question: Can the singleton class be subclassed?

Answer: Frankly speaking singleton is just a design pattern and it can be subclassed. However it is worth to understand the logic or requirement behind subclassing a singleton class as the child class might not inherit the singleton pattern objective by extending the Singleton class. However the subclassing can be prevented by using the final keyword in the class declaration.

Question: Can there be multiple instance of singleton using cloning?
Answer: That was a good catch! What do we do now? To prevent the another instance to be created of the singleton instance we can throw exception from inside the clone() method.

Question: What is the impact if we are creating another instance of singleton using serialization and deserialization?
Answer: When we serialize a class and deserialize it then it creates another instance of the singleton class. Basically as many times as you deserialize the singleton instance it will create multiple instance. Well in this case the best way is to make the singleton as enum. In that way the underlying Java implementation takes care of all the details. If this is not possible then we will need to override the readobject() method to return the same singleton instance.

Question: Which other pattern works with Singleton?
Answer:There are several other pattern like Factory method, builder and prototype pattern which uses Singleton pattern during the implementation.

Question: Which classes in JDK uses singleton pattern?
Answer: java.lang.Runtime : In every Java application there is only one Runtime instance that allows the application to interface with the environment it is running. The getRuntime is equivalent to the getInstance() method of the singleton class.


Uses of Singleton design pattern:

Various usages of Singleton Patterns:

  • Hardware interface access: The use of singleton depends on the requirements. However practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.
  • Logger : Similarly singleton is a good potential candidate for using in the log files generation. Imagine an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference.
  • Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file at the first time and there after from second call onwards the client applications read the data from in-memory objects.
  • Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.