Java Interview Questions
Java Interview Questions
Java Interview Questions
OOPS
Can we declare main methid as final?
What is the difference between instanceof operator and isInstance() method in
Java?
Polymorphism
Can we override a non-static method as static in Java?
Can we change the return type of overriding method from Number type to Integer
type?
How do compiler differentiate overloaded methods from duplicate methods?
Inheritance
You know that all classes in java are inherited from java.lang.Object class. Are
interfaces also inherited from Object class.?
Strings
What are wrapper classes? Is String a wrapper class ?
Which is the final class in these three classes String, StringBuffer and
StringBuilder?
Exception Handli
Is it necessary that each try block must be followed by a catch block?
Is there a case when finally will not be executed?
Java I/O
What is the difference between write(100) and print(100) of PrintWriter class?
Why does serialization NOT save the value of static class attributes? Why static
variables are not serialized?
Java Enums
Design patterns
What are the rules for creating Sngleton class
Can you replace Singleton with Static Class in Java?
Packages
Static import
Can I import same package/class twice? Will the JVM load the package twice at
runtime?
Can you instantiate Math class?
Threads
When to use Runnable and Thread?
int i=1;
float f =2.0f;
i += f; //ok, the cast is done automatically by the cpmpiler
I = I + f; //error
package com.instanceofjava;
public class B{
B b= new B();
B b= new B();
b.show();
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
at com.instanceofjava.B.<init>(B.java:3)
at com.instanceofjava.B.<init>(B.java:5)
at com.instanceofjava.B.<init>(B.java:5)
package com.instanceofjava;
class A
{
void method(int i)
{
}
}
class B extends A
{
@Override
void method(Integer i)
{
}
}
Write a program to find the missing number from the list of sorted numbers from
1N with less complexity
Answer
OOPS
Yes.
1. Both isInstance() method and instanceof operator (type comparison operator) are used to check
if an object is of a particular class or interface type
2. The right-hand-operand of instanceof operator must be evaluated to a type (class or interface),
which is known at compile time.
3. There may be chances when you don't know the type name at compile time and you want to
pass it as an argument that will be resolved at run time.
4. In those circumstances you won't be able to use instanceof operator because instanceof does
not work for types evaluated at run time.
5. The isInstance() method, which is dynamic equivalent of the Java language instanceof operator
does type checking at run time.
6. The public boolean isInstance(Object obj) method determines if the specified Object is
assignment-compatible with the object represented by this Class. This method returns true if the
specified Object argument is non-null and can be casted to the reference type represented by this
Class object without raising a ClassCastException. It returns false otherwise.
A class can be marked by the "private" access specifier only
if its a nested member of another class.
Top level classes cannot be marked as "private". Hence you
can have private classes in a java file but they must be
nested inside another class.
Polymorphism
No, its not possible to define a non-static method of same name as static method in parent class,
its compile time error in Java. See here to learn more about overriding static method in Java.
Yes. You can change as Integer is a sub class of Number type.
Compiler uses method signature to check whether the method is overloaded or duplicated.
Duplicate methods will have same method signatures i.e same name, same number of arguments
and same types of arguments. Overloaded methods will also have same name but differ in number
of arguments or else types of arguments.
Yes. Compiler checks only method signature for overloading of methods not the visibility of
methods.
you can very well throw super class of RuntimeException in overridden method but you can not do
same if its checked Exception.
Collections
You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique.
HashSet uses Maps this feature to ensure uniqueness of elements. In HashSet class, a map
declaration is as below:
private transient HashMap<E,Object> map;
//This is added as value for each key
private static final Object PRESENT = new Object();
java.util.Collection is the root interface in the hierarchy of Java Collection framework.
The JDK does not provide any classes which directly implements java.util.Collection interface, but
it provides classes such as ArrayList, LinkedList, vector, HashSet, EnumSet, LinkedHashSet,
TreeSet, CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentSkipListSet which implements
more specific subinterfaces like Set and List in java.
java.util.Collections is a utility class which consists of static methods that operate on or return
Collection in java.
java.util.Collections provides method like >
reverse method for reversing List in java.
shuffle method for shuffling elements of List in java.
unmodifiableCollection, unmodifiableSet, unmodifiableList, unmodifiableMap methods for making
List, Set and Map unmodifiable in java.
min method to return smallest element in Collection in java.
max method to return smallest element in Collection.
sort method for sorting List.
synchronizedCollection, synchronizedSet, synchronizedList, synchronizedMap methods for
synchronizing List, Set and Map respectively in java.
You should first try to find another alternative iterator which are fail-safe. For example if you are
using List and you can use ListIterator. If it is legacy collection, you can use enumeration.
If above options are not possible then you can use one of three changes:
If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList
classes. It is the recommended approach.
You can convert the list to an array and then iterate on the array.
You can lock the list while iterating by putting it in a synchronized block.
Inheritance
No, only classes in java are inherited from Object class. Interfaces in java are not inherited from
Object class. But, classes which implement interfaces are inherited from Object class.
Strings
a (primitive) wrapper class in Java is one of those eight classes that wrap a (=one) primitive value.
String wraps a char[] so according to this it is not a (primitive) wrapper class.
String is not designed to wrap or decorate a character array. String has been designed to model a
string, a character sequence and the current implementation uses an internal char[]
All three are final
Exception Handling
It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block or finally block. And whatever exceptions are likey to be thrown should be
declared
inexits
the throws
clause of
method.a fatal eror that causes the process to abort.
If program
System.exit()
or the
by causing
Java I/O
n the case of write(100) the corresponding character d will be written in to the file where as
print(100) is written int value 100.
The Java variables declared as static are not considered part of the state of an object since they
are shared by all instances of that class. Saving static variables with each serialized object would
have following problems
It will make redundant copy of same variable in multiple objects which makes it in-efficient.
The static variable can be modified by any object and a serialized copy would be stale or not in
All standard implementations of collections List, Set and Map interface already implement
java.io.Serializable. All the commonly used collection classes like java.util.ArrayList,
java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do
implement Serializable. This means you do not really need to write anything specific to serialize
collection objects. However you should keep following things in mind before you serialize a
collection object - Make sure all the objects added in collection are Serializable. - Serializing the
collection can be costly therefore make sure you serialize only required data isntead of serializing
Java Enums
Design patterns
Packages
By using static imports, we can import the static members from a class rather than the classes
from a given package. For example, Thread class has static sleep method, below example gives an
idea: import static java.lang.Thread; public class MyStaticImportTest { public static void
main(String[] a) { try{ sleep(100); } catch(Exception ex){ } } } - See more at:
http://www.java2novice.com/java_interview_questions/java-static-import/#sthash.1ECg7rjl.dpuf
One can import the same package or same class multiple times. Neither compiler nor JVM
complains anything about it. And the JVM will internally load the class only once no matter how
many
times you
import the same
class.
No. It cannot
be instantited.
The class
is final and its constructor is private. But all the methods are
static, so we can use them without instantiating the Math class.
Threads
Java doesn't support multiple inheritance, which means you can only extend one class in Java so
once you extended Thread class you lost your chance and can not extend or inherit another class
in Java.
In Object oriented programming extending a class generally means adding new functionality,
modifying or improving behaviors. If we are not making any modification on Thread than use
Runnable interface instead.
Runnable interface represent a Task which can be executed by either plain Thread or Executors or
any other means. so logical separation of Task as Runnable than Thread is good design decision.
by extending Thread, each of your threads has a unique object associated with it, whereas
implementing Runnable, many threads can share the same object instance.
A class that implements Runnable is not a thread and just a class.For a Runnable to become a
Thread, You need to create an instance of Thread and passing itself in as the target.
use a BlockingQueue for this. You define a single BlockingQueue such as the
LinkedBlockingQueue. Your listener class then calls queue.take() which will wait for your server to
call queue.put(). It leaves all of the synchronization, waits, notifies, etc. to the Java class instead of
your own code.
The compound assognment operators automatically include cast operations in their behaviors.
Exaplanation:
Whenever we create the object of any class constructor will be called first and memory allocated
for all non static variables
Here B b= new B(); variable is object and assigned to new object of same class
B b= new B(); statement leads to recursive execution of constructor will create infinite objects so
at run time an exception will be raised
Exception in thread "main" java.lang.StackOverflowError
The common cause for a stack overflow exception is a bad recursive call. Typically this is caused
when your recursive functions doesn't have the correct termination condition
Pasted from <http://www.instanceofjava.com/2015/05/10-tricky-core-java-interview-coding.html>
n (n+1)/2