Basic Java Interview Questions - Frequently asked Java Questions

What is reflection?

Reflection :

It is property by which program can analyze itself. It is given by the java.lang.reflect package. This enables us to evaluate the software components and detailed knowledge of its capabilities dynamically. We can use this reflection to access the public methods of a class. Member which is present in the java.lang.reflect package is used to extract information regarding the fields, constructor and methods of a class.

What is JVM?

Java Virtual Machine (JVM) :

It is an interpreter for bytecode. JVM is a platform independent and converts Java byte code into machine language and executes it. Program calls compiler to translate the program code into executable code that computer can understand and execute. The executable code depends upon the computer operating system that we use to execute our program. It is machine dependent.

Explain different layout manager in Java.

- Some of the components like Button, Checkbox, Lists, Scrollbars, Text Fields, and text area are positioned by the default layout manager.

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

1. Border Layout : Five areas for holding components: north, east, west, south and center.

2. Flow Layout : Default layout manager, lays out the components from left to right.

3. Card Layout : Different components at different times are laid out, Controlled by a combo box.

4. Grid Layout : Group of components are laid out I equal size and displays them in certain rows and columns.

5. Grid Bag Layout : Flexible layout for placing components within a grid of cells.

What is the difference between Stream classes and Reader writer classes?

Stream Classes :

1. Hierarchy is a byte oriented.

2. Unicode characters are not supported.

3. 8-bit streams are supported.

4. The streams supports filtering data into primitive types using DataOutputStream and DataInputStream.

5. Object serialization supports byte oriented stream.

6. Data over network passes a stream of bytes.

7. Available since JDK 1.0.

Reader and Writer Classes :

1. Hierarchy is character oriented.

2. They never support byte streams.

3. Supports 16-bit Unicode characters.

4. Supports to read a group of characters at once.

5. Available since JDK 1.1.

Explain the use of RandomAccessFile classes.

RandomAccessFile :

- It enables us to perform read and write operations on file.

- In this we use the file pointer to points the positions from where the reading or writing operation is performed.

- It defines operation modes (read / write).

1. r mode : Open for reading only.

2. rw mode : Open for reading and writing.

3. seek(file.length()) method : It jumps the file pointer at the specified location.

4. rand.close() method : It closes the random access file stream.

5. writeBytes( ) method : It simply writes the content into the file.

6. readByte() method : It reads a single byte from the file.

7. readLine() method : It reads the line from the file.

What is object Serialization? Explain the use of Persisting object.

- Serialization is the process of saving the state of object to a byte stream. This enables us to save the state of object. So that we can use this value to again restart our program using Deserialization Process. This value can be stored in file.

- Serialization allows the objects to move from one computer to another by maintaining their state.

- It implements java.io.Serialization interface with few lines of code.

- The following is the class declaration to serialize an object Public class UserData implements java.io.Serializable:

1. When an application uses objects, it cannot use all objects at once.
2. The required objects can be desterilized and then it handles.
3. Later another object is handled, allowing the memory to conserved space for better performance.

What is the difference between procedural and object-oriented programs?

- The difference between procedural and object oriented programming are:

1. Procedural programming creates a step by step program that guides the application through a sequence of instructions where as object oriented programming is analogous to human brain, multiple programming at a time.

2. In procedural, each instruction is executed in order whereas in object oriented programming each program is made up of many entities called objects.

3. Procedural programming also focuses that all algorithms are executed with functions and data that the programmer has access to and is able to change bit in object oriented, Objects become the fundamental units and have behavior.

4. In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible within the object and which in turn assures the security of the code.

What are inner class and anonymous class?

Inner class :

- Classes that are defined within other classes.

- The nesting is a relationship performed between two different classes.

- An inner class can access private members and data.

- Inner classes have clearly two benefits:
1. Name control
2. Access control.

Anonymous class :

- Anonymous class is a class defined inside a method without a name.

- It is instantiated and declared in the same method.

- It does not have explicit constructors.

What is multithreading and what is the class in which these methods are defined?

Multithreading is the mechanism which allows us to do many things simultaneously. A multithreaded enable us to executed two or more program at same time which are totally independent of each other. Each part of such a program is called a thread. Each thread defines a separate path of execution inside the program. To communicated between two threads we use methods like wait (), notify () and notifyAll() and these methods are in Object class.wait().

What is the difference between applications and applets?

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

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

2. Application starts execution with its main method whereas applet starts execution with its init method.

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

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

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

What is adapter class?

An adapter class is a class that enables a dummy or empty implementation for an interface.

1. We can use the adapter class when we don’t know how to implement interface.

2. After getting the interface we can override those methods which are required in our programming.

3. It is useful when we want to receive and process only some of the events that are handled by a particular event listener interface.

4. We can create a new class which can act as a listener by extending the adapter classes and implementing only those events which is required.

What is JavaDoc utility?

- Javadoc is a java tool.

- It is used to parse the declaration comments and documentation comments available in a set of java source files.

- Javadoc produces a group of HTML pages with information about classes, interfaces, constructors, methods and fields.

- Syntax :
javadoc [options] [packagenames] [sourcefiles] [@files]
- Arguments can be in any order.

1. Options : Command-line options that is doc title, window title, header, bottom etc.

2. Packagenames : A series of names of packages, separated by spaces. You must separately specify each package we want to document.

3. Sourcefiles : A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*).

4. @files : One or more files that contain PackageNames and Sourcefiles in any order, one name per line.

What are the advantages of Java layout managers?

- In Java Button, Checkbox, Lists, Scrollbars, Text Fields, and Text Area etc. positioned by the default layout manager. Using algorithm layout manager automatically arranges the controls within a window.

- In Windows environment, we can control layout manually. But we do not do it manual because of following two reasons:

1. It is very tedious to manually lay out a large number of components.
2. Sometimes the width and height information is not available when you need to arrange some control, because the native toolkit components have not been realized. This is a chicken-and-egg situation.

- Java uses layout managers to lay out components in a consistent manner across all windowing platforms.

Explain Marker Interface.

- Marker interface in Java is interfaces with no field or methods.

- Features of Marker Interfaces are following:

1. We use Marker interface to tell java complier to add special behavior to the class implementing it.

2. Java marker interface has no members in it.

3. It is implemented by classes in get some functionality.

- Example: when we want to save the state of an object then we implement Serializable interface.

What is the difference between Process and Thread?

- The major difference between threads and processes is:

1. Threads share the address space of the process that created it whereas processes have their own address.

2. Threads can directly access to the data segment of its process whereas processes have their own copy of the data segment of the parent process.

3. Threads communicate directly with other threads of its process whereas processes use inter-process communication to communicate with child processes.

4. Threads have almost no overhead whereas processes have considerable overhead.

5. New threads are easily created whereas new processes require duplication of the parent process.

6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.

7. Changes to the main thread affect the behavior of the other threads of the process whereas changes to the parent process do not affect child processes.

How do you declare a class as private?

- We can declare a private class as an inner class.

- For example :
class MyPrivateClass
{
   private static class MyKey
   {
       String key = "91234";
   }
   public static void main(String[] args)
   {
       System.out.println(new MyKey().key);//prints 91234
   }
}

What is the drawback of inheritance?

- Main disadvantage of using inheritance are:

1. Coupling : Two classes (base and inherited class) get tightly coupled.

2. Maintenance : Adding new features, involves both base and inherited derived classes are required to be changed.

3. Time and Effort : It takes more time and effort to perform change in any of the class. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method.

4. Understanding of code : It make programming code more complex which makes it difficult to understand the code.

What is the difference between notify() and notifyAll()?

The notify() method wakes up a single thread waiting on the object and passes the control of the monitor to it. If the wait set of the object is non-empty then a thread from the set is arbitrarily chosen, removed and is re-enabled for thread scheduling. The notifyAll() says that it will wake up all the threads waiting on the object and will select a thread to pass control to it. Using notify() is preferable when only one blocked thread can benefit from the change. notifyAll() is necessary if multiple threads should resume.

Why are there no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables because the global variable breaks the referential transparency and also a global variable creates collisions in namespace. As JAVA is pure object oriented language so there are no global variables because each variable is to be declared in a class and object of a class must be initialized to use its variables and functions when we add one variable. We limit the use of your program to one instance. What we thought was global. Someone else might think of as local, they may want to run two copies of program at once.

Explain in brief transient modifiers and volatile modifiers.

- When serializable interface is declared, the compiler knows that the object has to be handled so as so be able to serialize it. However, if you declare a variable in an object as transient, then it doesn’t get serialized.

Volatile : Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all.

- Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

Define daemon threads and explain its purposes.

- Threads that work in the background to support the runtime environment are called daemon threads. For example: garbage collector threads.

- When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

- You cannot create a daemon method but you can use 'public final void setDaemon(boolean isDaemon)' method to turn it into one.

Can you explain JAVAdoc utility.

- Javadoc utility enables you to keep the code and the documentation in sync easily.

- The javadoc utility lets you put your comments right next to your code, inside your ".java" source files.

- All you need to do after completing your code is to run the Javadoc utility to create your HTML documentation automatically.

StringBuilder class vs. StringBuffer class.

- StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder.

- StringBuilder is more efficient than StringBuffer.

Can you explain semaphore and monitors in java threading?

- A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process.

- The drawback of semaphores is that there is no control or guarantee of proper usage.

- A Monitor defines a lock and condition variables for managing concurrent access to shared data.

- The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time.

- A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once.

Describe synchronization in respect to multithreading.

Multithreading occurs asynchronously, meaning one thread executes independently of the other threads. In this way, threads don’t depend on each other’s execution. In contrast, processes that run synchronously depend on each other. That is, one process waits until the other process terminates before it can execute.

What are Checked and UnChecked Exception?

- The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions non runtime exceptions and runtime exceptions.

- Non runtime exceptions are called checked exceptions and the unchecked exceptions are runtime exceptions.

- Runtime Exceptions occur when the code is not robust and non runtime exceptions occur due to the problems is environment, settings, etc.

In which scenario LazyInitilizationException will occur in Hibernate ? How to overcome it?

- When we are loading the data from the data base use load() method of Session. And we are getting the data from bean after session has been closed.

- In such scenerio LazyInitilizationException will occur.

- For example :
Session sess=factory.openSession();
Transaction trans=sess.beginTransaction();
SampleEntity se=(SampleEntity)sess.load(SampleEntity.class,11);
trans.commit(); sess,close();
System.out.println(se.getName());
- To overcome this problem use initialize() of Hibernate i.e
Session sess=factory.openSession();
Transaction trans=sess.beginTransaction();
SampleEntity se=(SampleEntity)sess.load(SampleEntity.class,11);
Hibernate.initialize(se);
trans.commit(); sess,close();
System.out.println(se.getName());

Is it recommended to handle NumberFormatException?

- NumberFormatException is Unchecked Exception.

- It is not recommended to handle unchecked exception. So, we have to prevent it without raising that Exception. We can prevent it by using regular expression i.e
public boolean isInteger(String str)
{
   return str.matches(“^-?[0-9]+(\\/[0-9]+)?$”);
}

What is Singleton pattern? How can we implements this pattern in Java and Spring?

Singleton pattern allows us to create only one instantiation of a class to one object.

- We can achieve this in Java by using private class Constructor i.e
Public Class Singleton
{
   private static Singleton sing;
   private Singleton(){}
   public static Singleton getObject()
   {
       sign=new Singleton();
   }
}
- In spring, by default all beans are Singleton . To change we have to define a tag called scope for latest version and for old version we have to use tag called singleton.

- New Version : <bean id='sampleid” class=”example.sample” scope=”singleton”>

- Old Version : <bean id='sampleid” class=”example.sample” singleton=”true”>
Advanced Java Interview Questions - Senior Level Java Interview
Advanced java interview questions - Can we compare String using equality operator (==) operator?What is intern() method in Java?When is class garbage collected?What is the difference between a Choice and a List?.......
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.....
Post your comment
Discussion Board
post with 200 interview questions on Java.
Nice Post. Here's another post with 200 interview questions on Java.

http://www.buggybread.com/2013/07/java-interview-questions-and-answers.html
vinay 12-2-2013