Google News
logo
Java Interview Questions
Java is an object-oriented programming language developed by Sun Microsystems and released in 1995. Java was originally developed by James Gosling at Sun Microsystems (which has since merge into Oracle Corporation).
1)  Pointers lead to confusion for a programmer.
2) Pointers may crash a program easily, for example, when we add two pointers, the program crashes immediately. The same thing could also happen when we forgot to free the memory allotted to a variable and reallot it to some other variable.
3) Pointers break security. Using pointers, harmful programs like virus and other hacking programs can be developed.
Because of the above reasons, pointers have been eliminated from java.
Class loader sub system of JVM will allocate the necessary memory needed by the java program.
Garbage collector uses many algorithms but the most commonly used algorithm is mark & sweep.
Garbage collector is automatically invoked when the program is being run, it can be also called by calling gc() method of Runtime class or system class in java. 
HotJava is the first browser, having the capabilities of executing the applets.
oak is the initial name given to java programming language
JIT compiler is the part of JVM which increases the speed of execution of a java program.
JVM is the heart of entire java program.
#include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’s time.

import statement makes the JVM go to the java standard library, execute the code there, and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time. So, import is an efficient mechanism than #include
When main() method is written without String args[] as :
 public static void main()
The code will compile but JVM cannot run the code because it cannot recognize the main() method as the method from where it should start execution of the java program. 

Remember JVM always looks for main() method with string type array as parameter.
Both methods are used to display the results on the monitor. Print() method displays the result and then retains the cursor in the same line, next to the result. 

Println() displays the result and then throws the cursor to the next line.
No. It is by default loaded internally by the JVM.
No the program fails to compile. The compiler says that the main method is already defined in the class.
Program compiles and runs properly.
Program compiles. But at runtime throws an error "NoSuchMethodError".
The program compiles properly but at runtime it will give "Main method not public." message.
Yes, a .java file contains more than one java classes, provided at the most one of them is a public class.
unicode system is an encoding standard that provides a unique number for every character, no matter what the platform, program, or language is. Unicode uses 2  bytes to represent a single character.
float can represent up to 7 digits accurately after decimal point, whereas double can represent up to 15 digits accurately after decimal point.
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false.
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them  explicitly, the java compiler will not compile the code. It will complain about the local variable not being initialized.
In declaration we just mention the type of the variable and its name. We do not initialize it. But defining means declaration + initialization. e.g. String s; is just  a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
The = operator is right associative.
Yes, a double value can be cast to a byte.
Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to-right or right-to-left.
• A boolean type may not be converted to non-boolean type.
• That is you cannot assign a boolean value to non-boolean type and vice versa.
• A non-boolean type may be converted to non-boolean type provided that the conversion is widening.
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.
The Bitwise operators can also be used in Boolean operations. If applied to boolean it uses true or false which are equivalent to 1 and 0.
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The &&  operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution. They are useful to write better and complex programs.
a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop
In a do…while loop the statements are executed without testing the condition, the first time. From the second time the condition is observed. This means that the programmer does not have control right from the beginning of its execution. In a while loop, the condition is tested first and then only the statements are executed. 

This means it provides better control right from the beginning. Hence, while loop is more efficient than do…while loop.

goto statements lead to confusion for a programmer. Especially, in a large program, if several goto statements are used, the programmer would be perplexed while understanding the flow from where to where the control is jumping.
return statement is used inside a method to come out of it. System.exit(0) is used in any method to come out of the program. 
System.exit(0) terminates the program normally, whereas System.exit(1) terminates the program because of some error encountered in the program.
The break keyword halts the execution of the current loop and forces control out of the loop. 
Continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.
System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages.
A stream is required to accept input from the keyboard. A stream represents flow of data from one place to another place.
In java there are 2 ways to read data from keyboard.
1. BufferedReader class.
2.Scanner class.
Scanner class is used to break the input into tokens, which by defaultly takes space as a delimiter.
BufferedReader class have two methods.
1. read() and 
2. readLine() methods.
Scanner class introduced in Java 1.5 for reading Data Stream from the input device. 
To read character value from the keyboard by using sc.next.charAt(0) method.
To read character value from the keyboard by using br.read() or br.readLine().charAt(0) method.
Arrays created on dynamic memory by JVM. There is no question of static memory in Java: everything (variable, array, object etc.) is created on dynamic memory only.
No, we can’t re-size an array after its creation. But in case of re initialization, whatever data that is stored in the array before re initialization will be lost.
You can declare an array in Java by either prefixing or suffixing [] with variable. There is not much difference between them if you are not creating more than one variable in one line, but if you do then it creates different types of variables, as shown in following example :

int a[], b; // first is int array, second is just int variable
int[] c, d; // both c and d are integer array
Yes, it is perfectly legal. You can create and initialize array in same line in Java.
By using arrayname.length property to know the size/ length of an array.
No. You can’t pass the negative integer as an array size. If you pass, there will be no compile time error but you will get NegativeArraySizeException at run time.
ArrayIndexOutOfBoundsException is a run time exception which occurs when your program tries to access invalid index of an array i.e negative index or index higher than the size of the array.
ArrayStoreException is a run time exception which occurs when you try to store non-compatible element in an array object. The type of the elements must be compatible with the type of array object. For example, you can store only string elements in an array of strings. if you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.
Yes, you can assign array of 100 elements to an array of 10 elements provided they should be of same type. While assigning, compiler checks only type of the array not the size.

public class MainClass
{
    public static void main(String[] args)
    {
        int[] a = new int[10];
        int[] b = new int[100];
        a = b;      //Compiler checks only type, not the size
    }
}
The main drawback of the arrays is that arrays are of fixed size. You can’t change the size of the array once you create it. Therefore, you must know how many elements  you want in an array before creating it. You can’t insert or delete the elements once you create an array. Only you can do is change the value of the elements.
String is a class in java.lang package. But in Java, all classes are also considered as data types. So we can take String as a data type also. 
Yes, a class is also called ‘user-defined’ data type. This is because a user can create a class.
                        String s = new String("Welcome");
Two objects, one in string constant pool and other in non-pool(heap).
The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. 

So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.

   switch (str.toLowerCase()) // java 7 only!
   {
      case "a":value = 1;
break;
      case "b":value = 2;
        break;
   }
String constant pool is a separate block of memory where the string objects are held by JVM. If a string object is created directly, using assignment operator as: 
String s1= “Hello”, then it is stored in string constant pool.
== operator compares the references of the String objects. It doesn’t compare the contents of the objects. equals() method compares the contents. While comparing the strings, equals() method should be used as it yields the correct results.
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.
In First Statement assignment operator is used to assign the string .In this case Jvm first check the String pool whether the same vale already available in the String container or not and notify if available, if it is not available then it create another reference to it.
In Second case each and every time it creates a new object of string.
All the wapper classes in java are immutable like. Integer, Flot.Double, etc
String class objects are immutable and hence their contents cannot be modified. StringBuffer class objects are mutable, so they can be modified. Moreover the methods that directly manipulate data of the object are not available in String class. Such methods are available in StringBuffer class.
Yes, classes like Character, Byte, Integer, Float, Double, Long... called ‘wrapper classes’ are created as ‘immutable’. Classes like Class, BigInteger, BigDecimal are also immutable.  
StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results. If only one thread is used, StringBuilder is preferred, as it improves execution time.
StringBuilder is not synchronized and hence faster than StringBuffer.
append
insert
delete
reverse
Since string is immutable we cannot perform these operations on String.
Advantage : It given high performance because consumes less memory as all modifications stored in same memory.
Disadvantage: Original value will not be preserved.
Object oriented programming languages follow all the features of Object Oriented Programming System (OOPS). Smalltalk, Simula-67, C++, Java are examples for OOPS languages.

Object based programming languages follow all the features of OOPS, except inheritance. For example, JavaScript and VBScript will come under object based programming languages.
Object oriented approach is a programming methodology to design computer programs using classes and objects.
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.
Object is termed as an instance of a class, and it has its own state, behavior and identity.
A class is a model for creating objects and does not exist physically. An object is anything that exists physically. Both the class & objects contain variables and  methods.
There are four principle concepts upon which object oriented design and programming rest. They are:
Abstraction
Polymorphism
Inheritance
Encapsulation
Abstraction refers to the act of representing essential features without including the background details or explanations.
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.
Hash code is a unique identification number allotted to the objects by JVM. This hash code number is also called reference number which is created based on the location of the object in memory, and is unique for all objects except String objects.
The hashCode() method of ‘Object’ class in java.lang package is useful to find the hash code of an object.

No, if we declare a class as private, then it is not available to java compiler and hence a compile time error occurs. But, inner classes can be declared as private.
yes, that is current class instance (You cannot use return type yet it returns a value).
A constructor is called concurrently when the object creation is going on. JVM first allocates memory for the object and then executes the constructor to initialize the instance variables. By the time, object creation is completed; the constructor execution is also completed.
Writing two or more constructors with same name but difference in the parameters is called constructor overloading. Such constructors are used to perform different tasks.
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.
There are 4 ways of creating objects in java.

1.Using new operator :

Employee obj=new Employee();

Here we are creating Employee class object ‘obj’ using new operator.

2.Using factory methods :

NumberFormat obj=NumberFormat.getNumberInstance();

Here, we are creating NumberFormat class object using factory method getNumberInstance().

3. Using newInstance() method. Here, we should follow two steps, as:

a.First, store the class name ‘Employee’ as a String into a object. For this purpose, factory method forName() of the class ‘Class’ will be useful.

Class c=Class.forName(“Employee”);

b.Next, create another object to the class whose name is in the object c. For this purpose, we need newInstance() method of the class ‘Class’, as:

Employee obj=(Employee)c.newInstance();

4.By cloning a already available object, we can create another object. Creating exact copy of a existing object is called ‘cloning’.

Employee obj1=new Employee();
Employee obj2=(Employee)obj1.clone();
After executing static methods, Jvm creates the objects. So the instance variables are not available to static methods.
Yes, it is possible by using a static block in the java program.
Primitive data types represent single value. Advanced data types represent a group of values. Also, methods are not available to handle the primitive data types. In case of advanced data types, methods are available to perform various operations.
No. abstract class needs sub classes. final keyword represents sub classes which cannot be created. So, both are quite contradictory and cannot be used for same class.
No, we cannot. Implementing an interface means writing body for the methods. This cannot be done again in an interface, since none of the methods of the interface can have body.
An exception is an error which can be handled. It means when an exception happens, the programmer can do something to avoid any harm. But an error is an error which cannot be handled, it happens and the programmer cannot do anything. 
The exceptions detected by java compiler at compilation time are called checked exceptions.

Example : IOException, ClassNotFoundException.

Exception Hierarchy :
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Exception Hierarchy is clearly shown in the figure below.

Throws clause is used when the programmer does not want to handle the exception and throw it out of a method. throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throw and throws are contradictory.
1. They convert primitive datatypes to objects and this id needed on internet to communicate between two applications.
2. The classes in java.util package handle only objects and hence wrapper classes help in this case also.
Converting a primitive datatype into an object is called ‘boxing’.
Converting a object into its primitive datatype is called ‘unboxing’.
Ideally, a string with an integer value should be passed to parseInt() method. So, on passing “Hello” an exception called “NumberFormatException” occurs since the parseInt() method cannot convert the given string “Hello” into an integer value.
A collection object stores references of other objects.
No, Collections store only objects.
Both are useful to retrieve elements from a collection. Iterator can retrieve the elements only in forward direction. But ListIterator can retrieve the elements in  forward and backward direction also. So the ListIterator is preferred to Iterator.
Both are useful to retrieve elements from a collection. Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to remove elements from the collection which is not available in Enumeration. So Iterator is preferred to Enumeration
Converting a primitive data type into an object form automatically is called auto boxing. Auto boxing is done in generic types. 
• A Stack is generally used for the purpose of evaluation of expressions. A LinkedList is used to store and retrieve data.
• Insertion and deletion of elements only from the top of the Stack is possible. Insertion and deletion of elements from anywhere is possible in case of a LinkedList.
•   ArrayList is not synchronized by default hence it should not be used with multiple threads. Vector is synchronized by default hence it can be used with single thread (or) multiple threads.
•   ArrayList works fast while working with single thread whereas Vector works slow while working with single thread.
Yes, we can use synchronizedList() method to synchronize the ArrayList as:
Collections.synchronizedList(new ArrayList());
•  HashMap object is not synchronized by default whereas Hashtable object is synchronized by default.
•  In case of single thread, using HashMap is faster than the Hashtable, whereas in the case of multiple threads, using Hashtable is advisable. With a single thread, Hashtable becomes slow.
•  HashMap allows null keys and null values to be stored Whereas Hashtable does not allow null keys and null values.
Yes, we can make HashMap object synchronized using synchronizedMap() method as shown here :   
Collections.synchrnizedMap(new HashMap());
AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons. The Java Virtual Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating system.
A window is a frame without any borders and title, where as a frame contains borders and title.
Event delegation model represents that when an event is generated by the user on a component, it is delegated to a listener interface and the listener calls a method in response to the event. Finally, the event is handled by the method.
An Adapter class in an implementation class of a listener interface which contains all methods implemented with empty body. WindowAdapter is an adapter class of WindowListener interface. Adapter classes reduce overhead on programming while working with listener interfaces.
Anonymous inner class is an inner class whose name is not mentioned, and for which only one object is created.
set Bounds(). 
Example : TxtName.setBounds(x, y, width, height);
By associating Checkbox objects with a CheckboxGroup.
Choice : A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. 
List :  A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
No. Adding a component to a container automatically removes it from any previous parent (container).
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
When button is clicked an action event is fired which can be captured by implementing ActionListener interface and actionPerformed(ActionEvent ae) method. You can then call button.setEnable(false) to disable this button.
The Container class has three major subclasses. They are : 

• Window 
• Panel 
• ScrollPane 
A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.
An applet represents java byte code embedded in a web page.
Applets are executed by a program called applet engine which is similar to virtual machine that exists inside the web browser at client side.
An applet is born with init() method and starts functioning with start() method. To stop the applet, the stop() method is called and to terminate the applet completely from memory, the destroy() method is called. Once the applet is terminated, we should reload the HTML page again to get the applet start once again from init() method. 

This cyclic way of executing the methods is called applet life cycle.
HotJava is the first applet-enabled browser developed in java to support running of applets.
<Applet> tag is used to insert an applet into HTML page.
When an applet begins, the AWT calls the following methods, in this sequence:
  1. init()
  2. start()
  3. paint()
When an applet is terminated, the following sequence of method calls takes place :
  4. stop()
  5. destroy()
Applets are small programs transferred through Internet, automatically installed and run as part of web-browser. Applet implements functionality of a client. Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java-capable browser. We don’t have the concept of Constructors in Applets. Applets can be invoked either through browser or through Appletviewer utility provided by JDK. 
To display the message at the bottom of the browser when applet is started.