34 Advanced Java Interview Questions - Senior Level Java Interview

Dear Readers, Welcome to Advanced Java Interview questions with answers and explanation. These 34 solved Advanced Java questions will help you prepare for technical interviews and online selection tests during job interviews for professionals interviewing for TechLead and other higher positions.

After reading these tricky Advanced Java questions, you can easily attempt the objective type and multiple choice type questions on Java.

Can we compare String using equality operator (==) operator?

- We can compare String using equality operator. But we mostly use equals() method because of following reasons:

1. The equality operator is used to compare primitives values only where as equals method() should be used to compare objects.

2. The equality operator can invoke subtle issue while comparing primitive to object. Where as equals() method is used to perform character based comparison.

3. equals() return true if two String represent to the same object or when both strings contents are exactly same but equality operator returns true if two string object represents to same object but return false if two different string object contains same contents.

What is intern() method in Java?

- The intern() method is of String class. The intern() method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

- Example :
String str1 = "hello";
String str2 = "hello";
String str3 = "hello".intern();
if ( s1 == s2 )
{
   System.out.println("str1 and str2 are same");
}
if ( str1 == str3 )
{
   System.out.println("str1 and str3 are same" );
}
- We are assuming that str1 and str3 are same will be printed as str3 is interned, and str1 and str2 are same will not be printed. Actual output is: both lines are printed, which make clear that by default String constants are interned.

When is class garbage collected?

- Java uses the garbage collector to free memory which is occupied by those objects which is no more reference by any of the program.

- An object becomes eligible for Garbage Collection when no live thread can access it.

- There are many ways to make a class reachable and thus prevent it from being eligible for Garbage Collection:

1. Objects of that class are still reachable.
2. Class object representing the class is still reachable.
3. ClassLoader that loaded the class is still reachable.
4. Other classes loaded by the ClassLoader are still reachable.

- When all of the above are false, then the ClassLoader together with all classes it loaded are eligible for Garbage Collection.

What is the difference between a Choice and a List?

- The between Choice and list are following:

- Choice class presents a pop-up menu of choices whereas List is a collection of different visible item.

- Choice is displayed in a compact form, to see the list of available choices we need to scroll down whereas list displays the entire available items.

- Choice allows selecting only one items but List supports the selection of one or more List items.

- Lists typically allow duplicate elements selection. List allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

What is JCA in java?

Java Cryptography Architecture term from Sun for implementing security functions for the Java platform. It provides a platform and gives architecture and APIs for encryption and decryption. JCA is used by the developer to combine the application with the security measure. A programmer uses the JCA to meet the security measure. It helps in performing the third partly security rules. It uses the hash table, encryption message digest, etc. to implement the security.

What is JPA in java?

- The Java Persistence API is enabling us to create the persistence layer for desktop and web applications. Java Persistence deals in following:

1. Java Persistence API
2. Query Language
3. Java Persistence Criteria API
4. Object Mapping Metadata

What is difference between eager and lazy loading?

The difference between eager and lazy loading are:

- Eager loading means to load the data before the requirement whereas lazy loading mean that load the data only when required.
- Eager loading fetch the data in one query whereas lazy loading fetch the data when needed by triggering the sub query.

What is JMS in Java?

Java Message Service (JMS) is used for creating the communication interface between two clients by using the message passing services. This helps the application to interact with other components irrespective of components location whether they rely on same system or connect to the main system through LAN or internet.

What is shallow cloning and deep cloning?

Shallow copy : In this, object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.

Deep copy : In this object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.

What is the difference between applications and applets?

The differences between an applet and an application are as follows:

- Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.

- Application starts execution with its main method whereas Applet starts execution with its init method.

- Application must be run on local machine whereas applet needs no explicit installation on local machine.

- Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.

- Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

What are Class loaders?

- Class loader enables the program to load the class at run time. This is located in the java.lang package.

- Using Class loader we can also load the customize classes which is required for the application execution. The class loaders in Java are organized in a tree. When JVM is started three class loaders are used:

1. Bootstrap class loader : The core java libraries. It is written in native code.

2. Extensions class loader : Loads the code in the extension directories. It is implemented by ExtClassLoader class.

3. System class loader : Code found on the java.class.path which map to the system class path variables. It is implemented by AppClassLoader class. All user classes by default are load by the system class loader.

What is the Comparable interface?

- The Comparable interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the comparable interface can be ordered.

- All classes implementing the comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
1. If object1 < object2: The value of i returned will be negative.
2. If object1 > object2: The value of i returned will be positive.
3. If object1 = object2: The value of i returned will be zero.

What is Single Threaded Model in Servlets?

- Single Thread Model is a marker interface which contains no methods and variable in it.

- When using Single thread model with Servlet, it make sure that only one thread can be executed at a time. It avoids running of two or more thead simultaneously.

- If we wants to make single threaded we can implement this interface in the following fashion.
public class SingleThreadedTest implements SingleThreadModel
{
   //some code
}

What are the different Authentication Options available in Servets?

- Authentication options available in Servlets: There are four different options for authentication in servlet:

1. Basic Authentication : Username and password provided by the client to authenticate the user.
2. Form-based authentication : In this the login form is made by the programmer by using HTML.
3. Digest Authentication : It is similar to basic authentication but in this the passwords are encrypted using Hash formula. This makes digest more secured.
4. Client certificate Authentication : It requires that each client accessing the resource has a certificate that it sends to authenticate itself. This requires SSL protocol.

What is the disadvantage of garbage collector?

- Garbage Collector runs in its own thread which affects the performance of the system. It increases the workload of JVM because it constantly monitor the object which is not referenced.
- The two main disadvantages of garbage collector are:

1. TIME : To collect all those no referenced object JVM spends a considerable amount of time by scanning the entire heap.
2. Mark and sweep : Sometimes it is difficult to implement mark and sweep in the application.

Does java support global variable?

- No, java does not support global variable because of the following reasons:

1. Globally accessible : Global variables are globally accessible.
2. Referential transparency : Global variable breaks the referential transparency and also a global variable generate problem in the namespace.
3. Object oriented : As java is object oriented language so where each variable is declared inside the class. To use this variable, object should be initialized.

Explain different layout manager in Java.

- There are following types of layouts are used to organize or to arrange objects :

- Border Layout : Have five areas for holding components: north, east, west, south and center.
- Flow Layout : Default layout manager, lays out the components from left to right.
- Card Layout : Different components at different times are laid out, Controlled by a combo box.
- Grid Layout : Group of components are laid out I equal size and displays them in certain rows and columns.
- Grid Bag Layout : Flexible layout for placing components within a grid of cells.

What is chained exceptions in java?

- When in a program the first exception causes another exception that is termed as Chained Exception.
- Chained exceptions helps in finding the root cause of the exception that occurs during application’s execution.
- The constructors that support chained exceptions in Throwable classes are:

1. Throwable initCause(Throwable)
2. Throwable(Throwable)
3. Throwable(String, Throwable)
4. Throwable getCause()

When is the main thread stop in java?

When we execute the java program, it call the main() method because main() method is the first thread in the program. This main() method or thread invokes the other thread which is required for the complete execution of the program. The main thread should be the last thread in the program to end. so to make main() method to be last we make sure when we called to another function by giving execution control to that must return the control back to the main() method.

What are the ways to create child threads?

- There are two ways to create java threads:

1. Implementing the Runnable Interface :
This overcomes the limitation of inheriting from only one parent class Thread. Using Runnable interface, lays a path to ground work of a class that utilizes threads.

2. Extending Thread Class :
It inherits the methods and data members, fields from the class thread. In this process only one class can be inherited from the parent class Thread.

- The advantage is a class can extend Thread class and also implements the Runnable interface, if required. The Runnable interface is set for implementing a thread and the class that implements the interface performs all the work.

Why bytecode is important to Java?

- The compiled Java source code is known as byte code. We need bytecode due to following reasons:

- Is independent of the input language.
- Plays an important role in the execution speed of the application.
- Can run on any platform irrespective of system architecture.
- Can be used for internet applications where security is important
- Enable us to load classes which are required for the execution of the application.
- Allows the web applications to run on various platforms, on various browsers on different infrastructures.

What is an Iterator and explain traversing through a collector using Iterator?

We can access each element in the Collection by using Iterators irrespective of how they are organized in the collector. Iterator can be implemented a different way for every Collection. To use an iterator to traverse through the contents of a collection we do:

- Obtain an iterator by calling the collections iterator() method to the start of the collection.
- Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true.
- Within the loop, obtain each element by calling next().
- The remove() method is used to remove the current element in the iteration.

What is Race condition?

Race Condition :
- It is the situation when two threads raise the request for the same resource allocation, but the manner in which resources are allocated are significant, is called race conditions.
- Race condition is created in program in order to run the parallel execution of program by using multiple threads in a same period.
- A race condition occurs when two threads operate on same object without proper synchronization and there operation interleaves on each other.
- The risk of race condition is higher in Java.

What is difference between Java and JavaScript?

The difference between java and java scripts are:

- Java is an Object Oriented Programming Language and capable of running on multiple operating systems with the help of interpreter whereas Java Script is the object oriented scripting language and it is embedded in HTML and runs directly on the browser.
- JVM is used to executed java program on different program whereas Java Script code is not compiled they are directly run on the browser.
- Java language is used to develop the software whereas java script is used providing interactivity to the simple HTML pages.

What is the difference between factory and abstract factory pattern?

The differences between factory and abstract factory are following:

- Factory pattern is a single method but abstract factory is an object.
- The Abstract Factory pattern is one level of abstraction higher than the factory pattern.
- Factory pattern generally returns the common parent class or method whereas the abstract factory pattern returns the one of the several factories.

What is Singleton?

- Singleton in Java is a class with just one instance in whole Java application.
- This make sure that only one instance of a class is created.
- The getInstance() method is used to get single instance of the class.
- It creates a global point to access all object.

What is the difference between JAR and WAR files?

The differences between JAR and WAR files are:

- JAR files (Java Archive) allows combining many files into one whereas WAR files (Web Application Archive) stores XML, java classes, and JavaServer pages for Web Application purposes.
- JAR is used to hold Java classes in a library whereas in WAR files are stored in lib directory of the application.
- In this EJB module which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extension whereas in WAR web modules which contains Servlet class files, JSP Files, GIF and HTML files are packaged as JAR file with .war extension.

Explain the usage of serialization.

- Objects are serialized when need to be sent over network.
- They are serialized when the state of an object is to be saved.

How are Observer and Observable used?

- The observable class represents an observable object.
- The object to be observed can be represented by sub-classing observable class.
- When there is a change in an observable instance, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

Difference between Swing and AWT.

AWT are heavy-weight components. Swings are light-weight components. Thus, swing works faster than AWT.

Define inner class in Java.

Class that is nested within a class is called as inner class. The inner class can access private members of the outer class. It is mainly used to implement data structure and sometimes called as a helper class.

Differences between constructors and methods.

- A constructor is used to create objects of a class. A method is an ordinary member in a class.
- Constructor does not have a return type. A method should have a return type.
- Constructor name is the name of the class. A method name should not be the name of the class
- Constructor is invoked at the time of creation of the class. Method needs to be invoked in another method by using the dot operator.
- Constructor can not have ‘return’ statement. All methods that return non-void return type should have ‘return’ statement.

Define Method overriding. Explain its uses.

Method overriding is the process of writing functionality for methods with the same signature and return type, both in super class and subclass The uses of method overriding:

- Time to invest method signature is reduced .
- Different functionality in both super class and sub class by sharing same signature.
- The functionality can be enhanced.
- The behavior can be replaced in the sub class.

What is the purpose of the File class?

- The File class provides access to the files and directories of a local file system.

Can you explain Native methods in Java?

- The Java native method is used to merge the power of C or C++ programming into Java.
- To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.
- Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

Explain class loaders in Java with an example.

- The class loader describes the behavior of converting a named class into the bits responsible for implementing that class.
- Class loaders eradicate the JREs need to know anything about the files and the file systems when running Java programs.
- A class loader creates a flat name space of class bodies that are referenced by a string name and are written as:
Class r = loadClass(String className, boolean resolveIt);

What is Reflection API in Java?

- The Reflection API allows Java code to examine classes and objects at run time.
- The new reflection classes allow you to call another class's methods dynamically at run time.
- With the reflection classes, you can also examine an instance's fields and change the fields' contents.
- It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
- The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.

Static class loading vs. Dynamic class loading.

- The static class loading is done through the new operator.
- Dynamic class loading is achieved through Run time type identification. Also called as reflection. This is done with the help of the following methods:
getClass(); getName(); getDeclaredFields();
- Instance can also be created using forName() method. It loads the class into the current class memory.

Can you explain shallow cloning and deep cloning?

- Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.

Deep cloning :
- You clone the object and their constituent parts.
- It should be used when it is inappropriate to separate the parts; the object is formed of, from it.

Shallow cloning :
- You clone only the object, not their parts. You add references to their parts.
- It should be used when it is adequate to have the references added to the cloned object.

Explain the purpose of Comparator Interface.

- Comparators can be used to control the order of certain data structures and collection of objects too.
- The interface can be found in java.util.Comparator.
- A Comparator must define a compare function which takes two objects and returns a -1, 0, or 1.
- Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

What is the impact of private constructor?

- Private Constructors can't be access from any derived classes neither from another class.
- So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.
- This can be useful for objects that can't be instantiated.

Can you explain static Initializers in Java?

- A static initializer block resembles a method with no name, no arguments, and no return type.
- There is no need to refer to it from outside the class definition.
- Syntax :
static
{
   //CODE
}
- The code in a static initializer block is executed by the virtual machine when the class is loaded.
- Because it is executed automatically when the class is loaded, parameters don't make any sense, so a static initializer block doesn't have an argument list.

Define Externalizable Interface and explain its purpose.

- The Externizable interface extends the serializable interface.
- When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process.
- When you use Externalizable interface, you have a complete control over your class's serialization process.
- The two methods to be implemented are :
void readExternal(ObjectInput)
- The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
void writeExternal(ObjectOutput)
- The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.
Interface vs. an abstract class
Interface vs. an abstract class - An abstract class may contain code in method bodies whereas code is not allowed in an interface......
Synchronized block vs. synchronized method
Synchronized block vs. synchronized method - Synchronized block is better since it places locks for shorter periods than synchronized methods.....
Explain how to force garbage collection
Explain how to force garbage collection - Garbage collection can't be forced, it can explicitly be called using System.gc(), but there is not guarantee....
Post your comment
Discussion Board
Thanks for effort
Better than most interview questions. Just scanned it and only say a couple of errors.

Why do developers dress up for job interviews even though most IT shops dress casual? To avoid being excluded due to prejudice.

Grammar is similar, but worse. People who have poor grammar have historically been associated with the ignorant and uneducated.

I am a native English speaker and I still type into a word processor to check my grammar, then copy and paste. It is fast, easy and included with MS Word and even free word processors.

Of course everyone knows this, so poor grammar is now associated with either laziness or egotism. So I suggest you dress up your writing like you would dress for an interview. It takes A LOT less time than putting on a business suit!
Eric B Goode 04-1-2013
Content Level
The content in your site is just awesome. It's way better than other interview site and help a lot to prepare for interview.
Keep up the good work
Mohammed Moosa Naqvi 12-10-2012