Java - Interview Questions and Answers - Difference Between

Q1.  Difference between TreeMap and HashMap ?

Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly. 

Q2.  What is the difference between List, Set and Map ?

Ans. List - Members are stored in sequence in memory and can be accessed through index. 
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.

Q3.  Difference between Public, Private, Default and Protected ?

Ans. Private - Not accessible outside object scope. 
Public - Accessible from anywhere. 
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.

Q4.  Difference between == and .equals() ?

Ans. "equals" is the member of object class which returns true if the content of objects are same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

Q5.  Difference between Checked and Unchecked exceptions ?

Ans. Checked exceptions and the exceptions for which compiler throws an errors if they are not checked whereas unchecked exceptions and caught during run time only and hence can't be checked.

Q6.  Difference between HashMap and Hashtable?

Ans. Hashtable is synchronized whereas HashMap is not.

HashMap allows null values whereas Hashtable doesn’t allow null values.

Q7.  Difference between long.Class and Long.TYPE ?

Ans. They both represent the long primitive type. They are exactly the same.

Q8.  What are the difference between Threads and Processes ?

Ans. 

1. when an OS wants to start running program it creates new process means a process is a program that is currently executing and every process has at least one thread running within it.

2. A thread is a path of code execution in the program, which has its own local variables, program counter(pointer to current execution being executed) and lifetime.

3. When the JavaVirtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be created.

4. Consider an example : when you open Microsoft word in your OS and you check your task manger then you can see this running program as a process. now when you write something in opened word document, then it performs more than one work at same time like it checks for the correct spelling, it formats the word you enter , so within that process ( word) , due to different path execution(thread) all different works are done at same time.

5. Within a process , every thread has independent path of execution but there may be situation where two threads can interfere with each other then concurrency and deadlock come is picture.

6. like two process can communicate ( ex:u open an word document and file explorer and on word document you drag and drop another another file from file explorer), same way two threads can also communicate with each other and communication with two threads is relatively low.

7. Every thread in java is created and controlled by unique object of java.lang.Thread class.

8. prior to jdk 1.5, there were lack in support of asynchronous programming in java, so in that case it was considered that thread makes the runtime environment asynchronous and allow different task to perform concurrently.

Q9.  What is the difference between yield() and sleep()?

Ans. When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.

Q10.  What is the difference between time slicing and preemptive scheduling ?

Ans. In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

Q11.  what is the use of cookie and session ? and What is the difference between them ?

Ans. Cookie and Session are used to store the user information. Cookie stores user information on client side and Session does it on server side. Primarily, Cookies and Session are used for authentication, user preferences, and carrying information across multiple requests. Session is meant for the same purpose as the cookie does. Session does it on server side and Cookie does it on client side. One more thing that quite differentiates between Cookie and Session. Cookie is used only for storing the textual information. Session can be used to store both textual information and objects.

Q12.  What is the difference between StringBuffer and String class ?

Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

Q13.  What is difference between Encapsulation And Abstraction?

Ans. 1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level

2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.

4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.

Q14.  Difference between Abstract and Concrete Class ?

Ans. Abstract classes are only meant to be sub classed and not meant to be instantiated whereas concrete classes are meant to be instantiated.

Q15.  Difference between Overloading and Overriding ?

Ans. Overloading - Similar Signature but different definition , like function overloading. 

Overriding - Overriding the Definition of base class in the derived class.

Q16.  Difference between Vector and ArrayList ?

Ans. Vectors are synchronized whereas Array lists are not.

Q17.  Difference between object instantiation and construction ?

Ans. Though It's often confused with each other, Object Creation ( Instantiation ) and Initialization ( Construction ) are different things in Java. Construction follows object creation.

Object Creation is the process to create the object in memory and returning its handler. Java provides New keyword for object creation. 

Initialization is the process of setting the initial / default values to the members. Constructor is used for this purpose. If we don't provide any constructor, Java provides one default implementation to set the default values according to the member data types. 


Q18.  Difference between boolean and Boolean ?

Ans. boolean is a primitive type whereas Boolean is a class.

Q19.  Difference between Process and Thread ?

Ans. Process is a program in execution whereas thread is a separate path of execution in a program.

Q20.  Difference between Serialization and Deserialization ?

Ans. Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Q21.  Difference between StringBuffer and StringBuilder ?

Ans. StringBuffer is synchronized whereas StringBuilder is not.

Q22.  Difference between Map and HashMap ?

Ans. Map is an interface where HashMap is the concrete class.

Q23.  Difference between implicit and explicit type casting ?

Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in case of implicit type casting you need not provide the data type. 

Q24.  Difference between loadClass and Class.forName ?

Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Q25.  Difference between Factory and Abstract Factory Design Pattern ?

Ans. Factory Pattern deals with creation of objects delegated to a separate factory class whereas Abstract Factory patterns works around a super-factory which creates other factories.

Q26.  Difference between Factory and Builder Design Pattern ?

Ans. Builder pattern is the extension of Factory pattern wherein the Builder class builds a complex object in multiple steps.

Q27.  Difference between Proxy and Adapter Design Pattern?

Ans. Adapter object has a different input than the real subject whereas Proxy object has the same input as the real subject. Proxy object is such that it should be placed as it is in place of the real subject.

Q28.  Difference between Adapter and Facade Design Pattern?

Ans. The Difference between these patterns in only the intent. Adapter is used because the objects in current form cannot communicate where as in Facade , though the objects can communicate , A Facade object is placed between the client and subject to simplify the interface.

Q29.  Difference between Builder and Composite ?

Ans. Builder is a creational Design Pattern whereas Composite is a structural design pattern. Composite creates Parent - Child relations between your objects while Builder is used to create group of objects of predefined types.

Q30.  Difference between Factory and Strategy Design Pattern ?

Ans. Factory is a creational design pattern whereas Strategy is behavioral design pattern. Factory revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision at runtime.

Q31.  Difference between nested and inner classes ?

Ans. Inner classes are non static nested classes.

Q32.  Difference between serializable and externalizable interface ?

Ans. Serializable is a marker interface whereas externalizable  is not.

Q33.  Difference between suspend() and stop() ?

Ans. Suspend method is used to suspend thread which can be restarted by using resume() method. stop() is used to stop the thread, it cannot be restarted again.

Q34.  what is the difference between collections class vs collections interface ?

Ans. Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

Q35.  Difference between Java beans and Spring Beans ?

Ans. Java Beans managed by Spring IoC are called Spring Beans.

Q36.  What is the difference between System.console.write and System.out.println ?

Ans. System.console() returns null if your application is not run in a terminal (though you can handle this in your application)

System.console() provides methods for reading password without echoing characters

System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

Q37.  Difference between C++ and Java ?

Ans. Java does not support pointers.

Java does not support multiple inheritances.

Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. 

Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.

C++ compiles to machine language , when Java compiles to byte code .

In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables.

Java is platform independent language but c++ is depends upon operating system.

Java uses compiler and interpreter both and in c++ their is only compiler.

C++ supports operator overloading whereas Java doesn't.

Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.

Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.

There is no goto statement in Java.

There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.

Java is pass by value whereas C++ is both pass by value and pass by reference.

Java Enums are objects instead of int values in C++

C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine.

C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing.

C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled.

C++ has several addressing operators . * & -> where Java has only one: the .

We can create our own package in Java(set of classes) but not in c and c++.


Q38.  Difference between static vs. dynamic class loading?

Ans. static loading - Classes are statically loaded with Java’s “new” operator.

dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.

Class.forName (Test className);

Q39.  What is the difference between final, finally and finalize() ?

Ans. final - constant variable, restricting method overloading, restricting class subclassing.

finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.

finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. 

Q40.  Difference between yield() and sleeping()? 

Ans. When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.

Q41.  What is the difference between AWT and Swing?

Ans. Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.

Swing components can change their appearance based on the current “look and feel” library that’s being used.

Swing components follow the MVC paradigm, and thus can provide a much more flexible UI.

Swing provides extras for components, such as icons on many components, decorative borders for components, tool tips for components etc.

Swing components are lightweight than AWT.

Swing provides built-in double buffering ,which means an off-screen buffer is used during drawing and then the resulting bits are copied onto the screen. 

Swing provides paint debugging support for when you build your own component.

Q42.  Difference between SAX and DOM Parser ?

Ans. A DOM (Document Object Model) parser creates a tree structure in memory from an input document whereas A SAX (Simple API for XML) parser does not create any internal structure.

A SAX parser serves the client application always only with pieces of the document at any given time whereas A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.

A SAX parser, however, is much more space efficient in case of a big input document whereas DOM parser is rich in functionality.

Use a DOM Parser if you need to refer to different document areas before giving back the information. Use SAX is you just need unrelated nuclear information from different areas.

Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers.

Q43.  What is the difference between comparable and comparator in java.util pkg?

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.