You are on page 1of 14

20 Important Java Programming

Interview Questions

Java Programming Interview Questions


Powered by













Contents

Q1. What is the difference between creating String as new() and literal? ........................ 3
Q2. What is difference between String, StringBuffer and StringBuilder in Java? ............ 3
Q3. What is Singleton? Is it better to make whole method synchronized or only
critical section synchronized? ................................................................................................ 5
Q4. What will happen if you call return statement or System.exit on try or catch
block? Will finally block execute? ........................................................................................... 6
Q5. Can you override private or static method in Java? ..................................................... 6
Q6. What are the differences between == and .equals()? ................................................... 7
Q7. What is the difference between final, finally and finalize? What do you
understand by the java final keyword? ................................................................................. 8
Q 8 When is static variable loaded? Is it at compile time or runtime? When
exactly a static block is loaded in Java? ............................................................................... 8
Q 9 What is reflection API? How are they implemented? ................................................... 8
Q 10 What is difference between String and StringTokenizer? .......................................... 9
Q 11 What is the Difference between JDK and JRE? .......................................................... 9
Q 12 Explain the difference between ITERATOR AND ENUMERATION
INTERFACE with example. .................................................................................................. 10
Q 13 What is the use of the SimpleDateFormat and how can you use it to
display the current system date in yyyy/MM/DD HH:mm:ss format? .......................... 11
Q.14 Why insertion and deletion in ArrayList is slow compared to LinkedList? ............ 11
Q.15 What is the Comparable interface? ........................................................................... 11
Q.16 What is an Iterator? What differences exist between Iterator and
ListIterator? ........................................................................................................................... 12
Q.17 How HashMap works in Java? .................................................................................. 12
Q.18 What if when two different keys have the same hashcode? .................................. 12
Q.19 How will you measure the performance of HashMap? ........................................... 13
Q.20 Difference between throw and throws? .................................................................... 13




Q1. What is the difference between creating String as new() and
literal?

Ans: When we create string with new() Operator, its created in heap and not
added into string pool while String created using literal are created in
String pool itself which exists in PermGen area of heap.

String s = new String("Test");

Does not put the object in String pool, we need to call String.intern() method which
is used to put them into String pool explicitly. Its only when you create String
object as String literal

E.g. String s = "Test;

Java automatically put that into String pool.
Q2. What is difference between String, StringBuffer and
StringBuilder in Java?

String

String is immutable (once created cannot be changed) object. The object created
as a String is stored in the Constant String Pool.
Every immutable object in Java is thread safe that implies String is also thread
safe. String cannot be used by two threads simultaneously. String once assigned
cannot be changed.

String demo = "hello;
// The above object is stored in constant string pool and its value cannot be
modified.


demo="Bye"; //new "Bye" string is created in constant pool and referenced by
the demo variable
// "hello" string still exists in string constant pool and its value is not overrided but
we lost reference to the "hello string

StringBuffer

StringBuffer is mutable means one can change the value of the object. The object
created through StringBuffer is stored in the heap. StringBuffer has the same
methods as the StringBuilder, but each method in StringBuffer is
synchronized that is StringBuffer is thread safe.

Due to this it does not allow two threads to simultaneously access the same
method. Each method can be accessed by one thread at a time.



But being thread safe has disadvantages too as the performance of the
StringBuffer hits due to thread safe property. Thus StringBuilder is faster than the
StringBuffer when calling the same methods of each class.

StringBuffer value can be changed, it means it can be assigned to the new value.
Nowadays its a most common interview question, the differences between the
above classes.
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello");
// The above object stored in heap and its value can be changed.
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the
StringBuffer.

StringBuilder

StringBuilder is same as the StringBuffer that is it stores the object in heap and it
can also be modified. The main difference between the StringBuffer and
StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe.


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the
StringBuilder.

--------------------------------------------------------------------------------------------------------
String StringBuffer StringBuilder
--------------------------------------------------------------------------------------------------------
Storage Area | Constant String Pool Heap Heap
Modifiable | No (immutable) Yes(mutable) Yes(mutable )
Thread Safe | Yes Yes No
Performance | Fast Very slow Fast
--------------------------------------------------------------------------------------------------------




Q3. What is Singleton? Is it better to make whole method
synchronized or only critical section synchronized?

Ans: Singleton in Java is a class with just one instance in whole Java application,
for example java.lang.Runtime is a Singleton class.
The easiest implementation consists of a private constructor and a field to hold
its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more
simply, using an initializer. The getInstance( ) method (which must be public) then
simply returns this instance:



























This would produce the following result:

demoMethod for singleton


public class Singleton {

private static Singleton singleton = new Singleton();
/*
* A private Constructor prevents any other class from
instantiating.
*/
private Singleton() {
}

/* Static 'instance' method */
public static Singleton getInstance() {
return singleton;
}

/* Other methods protected by singleton-ness */
protected static void demoMethod() {
System.out.println("demoMethod for singleton");
}
}

Here is the main program file where we will create singleton object:
// File Name: SingletonDemo.java
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}



Q4. What will happen if you call return statement or System.exit
on try or catch block? Will finally block execute?

This is a very popular tricky Java question and its tricky because many programmer
think that finally block always executed. This question challenge that concept by
putting return statement in try or catch block or calling System.exit from try or
catch block. Answer of this tricky question in Java is that finally block will execute
even if you put return statement in try block or catch block but finally block won't
run if you call System.exit form try or catch.

Q5. Can you override private or static method in Java?

You can not override private or static method in Java, if you create similar method
with same return type and same method arguments that's called method hiding.



Q6. What are the differences between == and .equals()?
The == operator compares two objects to determine if they are the same object in
memory i.e. present in the same memory location. It is possible for two String
objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public
boolean equals(Object obj) is provided by the Object class and can be overridden.
The default implementation returns true only if the object is compared with itself,
which is equivalent to the equality operator == being used to compare aliases to
the object. String, BitSet, Date, and File override the equals() method. For two
String objects, value equality means that they contain the same character
sequence. For the Wrapper classes, value equality means that the primitive values
are equal.























public class EqualsTest {

public static void main(String[] args) {

String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));
System.out.println("== comparison : " + s3 == s4);
System.out.println("Using equals method : " + s3.equals(s4));
}
}

Output
== comparison : true
== comparison : true
Using equals method: true
false
Using equals method : true




Q7. What is the difference between final, finally and finalize?
What do you understand by the java final keyword?
final declare constant
finally handles exception
finalize helps in garbage collection
Variables defined in an interface are implicitly final. A final class cant be extended
i.e., final class may not be subclassed. This is done for security reasons with basic
classes like String and Integer. It also allows the compiler to make some
optimizations, and makes thread safety a little easier to achieve. A final method
cant be overridden when its class is inherited. You cant change value of a final
variable (is a constant). finalize() method is used just before an object is
destroyed and garbage collected. Finally, a keyword used in exception handling
and will be executed whether or not an exception is thrown. For example, closing
of open connections is done in the finally method.
Q 8 When is static variable loaded? Is it at compile time or
runtime? When exactly a static block is loaded in Java?

Static variable are loaded when classloader brings the class to the JVM. It is not
necessary that an object has to be created. Static variables will be allocated
memory space when they have been loaded. The code in a static block is
loaded/executed only once i.e. when the class is first initialized. A class can have
any number of static blocks. Static block is not member of a class, they do not
have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.

Q 9 What is reflection API? How are they implemented?

Reflection is the process of introspecting the features and state of a class at
runtime and dynamically manipulate at run time. This is supported using
Reflection API with built-in classes like Class, Method, Fields, Constructors etc.
Example: Using Java Reflection API we can get the class name, by using the
getName method.




Q 10 What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer(Hello World);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World
Q 11 What is the Difference between JDK and JRE?
Ans: The JDK is the Java Development Kit. I.e., the JDK is bundle of software
that you can use to develop Java based software.
The JRE is the Java Runtime Environment. I.e., the JRE is an implementation of
the Java Virtual Machine which actually executes Java programs.
Typically, each JDK contains one (or more) JREs along with the various
development tools like the Java source compilers, bundling and deployment tools,
debuggers, development libraries, etc.




Q 12 Explain the difference between ITERATOR AND
ENUMERATION INTERFACE with example.

Ans:
Iterators allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics.
Iterator actually adds one method that Enumeration doesnt have:
remove ().


Whereas in case of Enumeration:





Q 13 What is the use of the SimpleDateFormat and how can you
use it to display the current system date in yyyy/MM/DD
HH:mm:ss format?
SimpleDateFormat is one such concrete class which is widely used by Java
developers for parsing and formatting of dates. This is also used to convert
Dates to String and vice-versa.
Literally every Enterprise level Java Application invariably uses the
SimpleDateFormat for handling user dates. We of course arent expecting Java
interviewees to be absolutely spectacular with the syntaxes. But a basic know-
how of this class is mandatory.










Q.14 Why insertion and deletion in ArrayList is slow compared to
LinkedList?

ArrayList internally uses and array to store the elements, when that array gets
filled by inserting elements a new array of roughly 1.5 times the size of the original
array is created and all the data of old array is copied to new array.
During deletion, all elements present in the array after the deleted elements have
to be moved one step back to fill the space created by deletion. In linked list data
is stored in nodes that have reference to the previous node and the next node so
adding element is simple as creating the node an updating the next pointer on the
last node and the previous pointer on the new node. Deletion in linked list is fast
because it involves only updating the next pointer in the node before the deleted
node and updating the previous pointer in the node after the deleted node.
Q.15 What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using
the Collections.sort() and java.utils.Arrays.sort() methods respectively. The
objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
Interface Comparable<T>

where T is the name of the type parameter.

public class CurrentSystemDate {
public static void main(String[] args) {
SimpleDateFormat sysForm = new
SimpleDateFormat("yyyy/MM/DD HH:mm:ss");
Date curdate = new Date();
System.out.println(sysForm.format(curdate));
}
}



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)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
Q.16 What is an Iterator? What differences exist between Iterator
and ListIterator?

The Iterator interface provides a number of methods that are able to iterate over
any Collection. Each Java Collection contains the iterator method that returns
an Iterator instance. Iterators are capable of removing elements from the
underlying collection during the iteration.
The differences of these elements are listed below:
An Iterator can be used to traverse the Set and List collections, while
the ListIterator can be used to iterate only over Lists.
The Iterator can traverse a collection only in forward direction, while
the ListIterator can traverse a List in both directions.
The List Iterator implements the Iterator interface and contains extra
functionality, such as adding an element, replacing an element, getting the
index position for previous and next elements, etc.
Q.17 How HashMap works in Java?

A HashMap in Java stores key-value pairs. The HashMap requires a hash function
and useshashCode and equals methods, in order to put and retrieve elements to
and from the collection respectively. When the put method is invoked,
the HashMap calculates the hash value of the key and stores the pair in the
appropriate index inside the collection. If the key exists, its value is updated with
the new value. Some important characteristics of a HashMap are its capacity, its
load factor and the threshold resizing.
Q.18 What if when two different keys have the same hashcode?

Solution equals() method comes to rescue. Here candidate gets puzzled. Since
bucket is one and we have two objects with the same hashcode .Candidate
usually forgets that bucket is a simple linked list.

The bucket is the linked list effectively. Its not a LinkedList as in a
java.util.LinkedList - It's a separate (simpler) implementation just for the map.

So we traverse through linked list, comparing keys in each entries using
keys.equals() until it return true. Then the corresponding entry object Value is
returned.




Q.19 How will you measure the performance of HashMap?

An instance of HashMap has two parameters that affect its performance: initial
capacity and load factor.

The capacity is the number of buckets in the hash table (HashMap class is
roughly equivalent to Hashtable, except that it is unsynchronized and permits
nulls.), and the initial capacity is simply the capacity at the time the hash table is
created.

The load factor is a measure of how full the hash table is allowed to get before its
capacity is automatically increased. When the number of entries in the hash table
exceeds the product of the load factor and the current capacity, the hash table is
rehashed (that is, internal data structures are rebuilt) so that the hash table has
approximately twice the number of buckets.

In HashMap class, the default value of load factor is (.75)

Q.20 Difference between throw and throws?
Throw is used to trigger an exception whereas throws is used in declaration of
exception.
Without throws, checked exception cannot be handled whereas checked
exception can be propagated with throws.







Study on the go; get high quality complete
preparation courses now on your mobile!

You might also like