Professional Documents
Culture Documents
Static blocks or static initializers are used to initialize static fields in java. we declare static blocks when we
want to intialize static fields in our class. Static blocks gets executed exactly once when the class is loaded
. Static blocks are executed even before the constructors are executed.
2|Page
6) Difference between abstract class and interface ?
3|Page
12) Difference between this() and super() in java ?
this() is used to access one constructor from another with in the same class while super() is used to
access superclass constructor. Either this() or super() exists it must be the first statement in the
constructor.
If we see the above class when we compile JVM loads the FirstClass and generates a .class
file(FirstClass.class). When we run the program we are running the class and then executes the main
method.
4|Page
Through encapsulation we can hide and protect the data stored in java objects.Java supports
encapsulation through access control. There are four access control modifiers in java public , private
,protected and default level.
For example take a car class , In car we have many parts which is not required for driver to know what all
it consists inside. He is required to know only about how to start and stop the car. So we can expose
what all are required and hide the rest by using encapsulation.
public : “public” is an access specifier which can be used outside the class. When main method is declared
public it means it can be used outside class.
static : To call a method we require object. Sometimes it may be required to call a method without the
help of object. Then we declare that method as static. JVM calls the main() method without creating
object by declaring keyword static.
void : void return type is used when a method does’nt return any value . main() method does’nt return
any value, so main() is declared as void.
length() : In String class we have length() method which is used to return the number of characters in
string.
Ex : String str = “Hello World”;
System.out.println(str.length());
Str.length() will return 11 characters including space.
length : we have length instance variable in arrays which will return the number of values or objects in
array.
For example :
String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”};
Will return 6 since the number of values in days array is 6.
21) What is ASCII Code?
ASCII stands for American Standard code for Information Interchange. ASCII character range is 0 to 255.
We can’t add more characters to the ASCII Character set. ASCII character set supports only English. That
5|Page
is the reason, if we see C language we can write c language only in English we can’t write in other
languages because it uses ASCII code.
6|Page
3) Constant names are usually nouns.
Ex:MAX_VALUE, MIN_VALUE, MAX_PRIORITY, MIN_PRIORITY
31) Difference between overriding and overloading in java?
Overriding Overloading
In overriding method names must be same In overloading method names must be same
Argument List must be same Argument list must be different atleast order of
arguments.
Return type can be same or we can return covariant Return type can be different in overloading.
type. From 1.5 covariant types are allowed
We cant increase the level of checked exceptions. In overloading different exceptions can be thrown.
No restrictions for unchecked exceptions
A method can only be overridden in subclass A method can be overloaded in same class or
subclass
Private,static and final variables cannot be Private , static and final variables can be
overridden. overloaded.
In overriding which method is called is decided at In overloading which method to call is decided at
runtime based on the type of object referenced at compile time based on reference type.
run time
Overriding is also known as Runtime polymorphism, Overloading is also known as Compile time
dynamic polymorphism or late binding polymorphism, static polymorphism or early
binding.
38) What all access modifiers are allowed for top class ?
For top level class only two access modifiers are allowed. public and default. If a class is declared as
public it is visible everywhere.
If a class is declared default it is visible only in same package.
If we try to give private and protected as access modifier to class we get the below compilation error.
Illegal Modifier for the class only public,abstract and final are permitted.
40) Can we have more than one package statement in source file ?
We can’t have more than one package statement in source file. In any java program there can be atmost
only 1 package statement. We will get compilation error if we have more than one package statement in
source file.
41) Can we define package statement after import statement in java?
We can’t define package statement after import statement in java. package statement must be the first
statement in source file. We can have comments before the package statement.
8|Page
A class, method or variable can be accessed is determined by the access modifier. There are three types
of access modifiers in java. public,private,protected. If no access modifier is specified then it has a default
access.
44) What is the difference between access specifiers and access modifiers in java?
In C++ we have access specifiers as public,private,protected and default and access modifiers as static,
final. But there is no such divison of access specifiers and access modifiers in java. In Java we have
access modifiers and non access modifiers.
Access Modifiers : public, private, protected, default
Non Access Modifiers : abstract, final, stricfp.
private : When a method is declared as private it can be accessed only in that class.
It cannot be accessed in
1) Same package subclass
2) Same package non subclass
3) Different package subclass
4) Different package non subclass.
9|Page
2) In the same package subclass
3) In the same package nonsubclass
4) In the different package subclass
5) In the different package non subclass.
private : When a variables is declared as private it can be accessed only in that class.
It cannot be accessed in
1) Same package subclass
2) Same package non subclass
3) Different package subclass
4) Different package non subclass.
10 | P a g e
Though we cannot instantiate abstract classes we can create object references . Through superclass
references we can point to subclass.
11 | P a g e
59) Explain try and catch keywords in java?
In try block we define all exception causing code. In java try and catch forms a unit. A catch block catches
the exception thrown by preceding try block. Catch block cannot catch an exception thrown by another try
block. If there is no exception causing code in our program or exception is not raised in our code jvm
ignores the try catch block.
Syntax :
try
{
}
Catch(Exception e)
{
}
63) Can we have any code between try and catch blocks?
We shouldn’t declare any code between try and catch block. Catch block should immediately start after try
block.
try{
//code
}
System.out.println(“one line of code”); // illegal
catch(Exception e){
//
}
64) Can we have any code between try and finally blocks?
We shouldn’t declare any code between try and finally block. finally block should immediately start after
catch block.If there is no catch block it should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
finally{
//
}
65) Can we catch more than one exception in single catch block?
From Java 7, we can catch more than one exception with single catch block. This type of handling reduces
the code duplication.
Note : When we catch more than one exception in single catch block , catch parameter is implicity final.
We cannot assign any value to catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
{
12 | P a g e
}
In the above example e is final we cannot assign any value or modify e in catch statement.
66) What are checked Exceptions?
1) All the subclasses of Throwable class except error,Runtime Exception and its subclasses are checked
exceptions.
2) Checked exception should be thrown with keyword throws or should be provided try catch block, else
the program would not compile. We do get compilation error.
Examples :
1) IOException,
2) SQlException,
3) FileNotFoundException,
4) InvocationTargetException,
5) CloneNotSupportedException
6) ClassNotFoundException
7) InstantiationException
13 | P a g e
70) Explain throw keyword in java?
Generally JVM throws the exception and we handle the exceptions by using try catch block. But there are
situations where we have to throw userdefined exceptions or runtime exceptions. In such case we use
throw keyword to throw exception explicitly.
Syntax : throw throwableInstance;
Throwable instance must be of type throwable or any of its subclasses.
After the throw statement execution stops and subsequent statements are not executed. Once exception
object is thrown JVM checks is there any catch block to handle the exception. If not then the next catch
statement till it finds the appropriate handler. If appropriate handler is not found ,then default exception
handler halts the program and prints the description and location of exception.
In general we use throw keyword for throwing userdefined or customized exception.
71) Can we write any code after throw statement?
After throw statement jvm stop execution and subsequent statements are not executed. If we try to write
any statement after throw we do get compile time error saying unreachable code.
14 | P a g e
78) Can we nested try statements in java?
Yes try statements can be nested. We can declare try statements inside the block of another try
statement.
15 | P a g e
1) Process based multitasking
2) Thread based multitasking
Process based multitasking : It allows to run two or more programs concurrently. In process
based multitasking a process is the smallest part of code .
Example : Running Ms word and Ms powerpoint at a time.
Thread based multitasking : It allows to run parts of a program to run concurrently.
Example : Formatting the text and printing word document at same time .
Java supports thread based multitasking and provides built in support for multithreading.
88) What are the benefits of multithreaded programming?
Multithreading enables to use idle time of cpu to another thread which results in faster execution of
program. In single threaded environment each task has to be completed before proceeding to next task
making cpu idle.
16 | P a g e
// Starting point of Execution
}
}
5) Dead State : A thread is in dead state when thread’s run method execution is complete. It dies
automatically when thread’s run method execution is completed and the thread object will be garbage
collected.
98) Can we restart a dead thread in java?
If we try to restart a dead thread by using start method we will get run time exception since the thread is
not alive.
17 | P a g e
moment the thread has to wait until another thread releases the lock on shared resource. To lock an
object we use synchronization in java.
A lock protects section of code allowing only one thread to execute at at a time.
To execute synchronized method first lock has to be acquired on that object. Once synchronized method
is called lock will be automatically acquired on that method when no other thread has lock on that
method. once lock has been acquired then synchronized method gets executed. Once synchronized
method execution completes automatically lock will be released. The prerequisite to execute a
synchronized method is to acquire lock before method execution. If there is a lock already acquired by
any other thread it waits till the other thread completes.
109) When a thread is executing synchronized methods , then is it possible to execute other
synchronized methods simultaneously by other threads?
No it is not possible to execute synchronized methods by other threads when a thread is inside a
synchronized method.
110) When a thread is executing a synchronized method , then is it possible for the same
thread to access other synchronized methods of an object ?
Yes it is possible for thread executing a synchronized method to execute another synchronized method of
an object.
public synchronized void methodName()
{
}
To execute synchronized method first lock has to be acquired on that object. Once synchronized method
is called lock will be automatically acquired on that method when no other thread has lock on that
method. once lock has been acquired then synchronized method gets executed. Once synchronized
method execution completes automatically lock will be released. The prerequisite to execute a
synchronized method is to acquire lock before method execution. If there is a lock already acquired by
any other thread it waits till the other thread completes.
111) What are synchronized blocks in java?
Synchronizing few lines of code rather than complete method with the help of synchronized keyword are
called synchronized blocks.
Signature :
Synchronized (object reference){// code}
112) When do we use synchronized blocks and advantages of using synchronized blocks?
If very few lines of code requires synchronization then it is recommended to use synchronized blocks. The
main advantage of synchronized blocks over synchronized methods is it reduces the waiting time of
threads and improves performance of the system.
18 | P a g e
113) What is class level lock ?
Acquiring lock on the class instance rather than object of the class is called class level lock. The difference
between class level lock and object level lock is in class level lock lock is acquired on class .class instance
and in object level lock ,lock is acquired on object of class.
118) How to change the priority of thread or how to set priority of thread?
Thread class has a set method to set the priority of thread and get method to get the priority of the
thread.
Signature : final void setPriority(int value);
The setPriority() method is a request to jvm to set the priority. JVM may or may not oblige the request.
We can get the priority of current thread by using getPriority() method of Thread class.
final int getPriority()
{
}
119) If two threads have same priority which thread will be executed first ?
We are not guaranteed which thread will be executed first when there are threads with equal priorities in
the pool. It depends on thread scheduler to which thread to execute. The scheduler can do any of the
following things :
1) It can pick any thread from the pool and run it till it completes.
2) It can give equal opportunity for all the threads by time slicing.
Signature :
public static native void yield()
{
122) Is it possible for yielded thread to get chance for its execution again ?
Yield() causes current thread to sleep for specified amount of time giving opportunity for other threads of
equal priority to execute. Thread scheduler decides whether it get chance for execution again or not. It all
depends on mercy of thread scheduler.
Signature :
public static native void sleep(long millis) throws InterruptedException
{
20 | P a g e
125) Assume a thread has lock on it, calling sleep() method on that thread will release the
lock?
Calling sleep() method on thread which has lock does’nt affect. Lock will not be released though the
thread sleeps for a specified amount of time.
126) Can sleep() method causes another thread to sleep?
No sleep() method causes current thread to sleep not any other thread.
128) Explain about interthread communication and how it takes place in java?
Usually threads are created to perform different unrelated tasks but there may be situations where they
may perform related tasks. Interthread communication in java is done with the help of following three
methods :
1) wait()
2) notify()
3) notifyAll()
130) Explain why wait() , notify() and notifyAll() methods are in Object class rather than in
thread class?
First to know why they are in object class we should know what wait(), notify(), notifyAll() methods do.
wait() , notify(), notifyAll() methods are object level methods they are called on same object.wait(),
notify(), notifyAll() are called on an shared object so to they are kept in object class rather than thread
class.
131) Explain IllegalMonitorStateException and when it will be thrown?
IllegalMonitorStateException is thrown when wait(), notify() and notifyAll() are called in non synchronized
context. Wait(), notify(),notifyAll() must always be called in synchronized context other wise we get this
run time exception.
132) when wait(), notify(), notifyAll() methods are called does it releases the lock or holds
the acquired lock?
wait(), notify(), notifyAll() methods are always called in synchronized context. When these methods are
called in synchronized context.
So when they enter first in synchronized context thread acquires the lock on current object. When wait(),
notify(), notifyAll() methods are called lock is released on that object.
133) Explain which of the following methods releases the lock when yield(),
join(),sleep(),wait(),notify(), notifyAll() methods are executed?
Method Releases lock (Yes or No)
yield() No
sleep() No
join() No
wait() Yes
21 | P a g e
Notify() Yes
notifyAll() Yes
140) What are inner classes or non static nested classes in java?
Nested classes without any static keyword declaration in class definition are defined as non static nested
classes. Generally non static nested classes are referred as inner classes.
There are three types of inner classes in java :
1) Local inner class
2) Member inner class
3) Anonymous inner class
23 | P a g e
150) How to instantiate member inner class?
OuterClassName.InnerclassName inner=new OuterClassReference.new InnerClassName();
We cannot instantiate inner class without outer class reference
151) How to do encapsulation in Java?
Make instance variables private.
Define getter and setter methods to access instance variables .
153) Will the compiler creates a default constructor if I have a parameterized constructor in
the class?
No compiler won’t create default constructor if there is parameterized constructor in the class. For
example if I have a class with no constructors, then compiler will create default constructor.
For Example :
public classCar {}
In the above Car class there are no constructors so compiler creates a default constructor.
public classCar {Car(String name) {
In this example compiler won’t create any default constructor because already there is one constructor in
the Car class.
24 | P a g e
Object cannot be assigned to other object and object cannot be passed as an argument to a method.
Reference is a variable which is used to access contents of an object. A reference can be assigned to other
reference ,passed to a method.
25 | P a g e
Int can be assigned directly to long .Automatic type conversion takes place if int is assigned to long
because long is larger datatype than int.
Widening Conversion comes under Automatic type conversion.
175) Explain the scope or life time of class variables or static variables?
Static variables do not belong to instances of the class. We can access static fields even before
instantiating the class. Static variable remain in memory till the life time of application.
176) Explain scope or life time of local variables in java?
Local variables are variables which are defined inside a method. When the method is created local
variables gets created in stack memory and this variable gets deleted from memory once the method
execution is done.
177) Explain about static imports in java?
From Java 5.0 we can import static variables in to source file. Importing static member to source file is
referred as static import. The advantage of static import is we can access static variables without class or
interface name.
Syntax : import static packagename.classname.staticvariablename;
Ex : import static com.abc.Employee.eno;
To import all static variables from a class in to our source file we use *.
import static com.abc.Employee.*
26 | P a g e
178) Can we define static methods inside interface?
We can’t declare static methods inside interface. Only instance methods are permitted in interfaces.only
public and abstract modifiers are permitted for interface methods. If we try to declare static methods
inside interface we get compilation error saying
“Illegal modifier for the interface method Classname.methodName(); only public & abstract are
permitted”.
27 | P a g e
186) Explain where variables are created in memory?
When we declare variables variables are created in stack. So when the variable is out of scope those
variables get garbage collected.
28 | P a g e
3) Polymorphism
194) Explain what is encapsulation?
Encapsulation is the process of wrapping of code and behaviour in a single unit called class and preventing
from misuse is called encapsulation. Encapsulation exposes only part of object which are safe to exposed
and remaining part of object is kept secured.
Encapsulation is supported through access control in java. There are four types of access control
specifiers(public,private, protected, default) in java which supports encapsulation.
For example tv manufacturers exposes only buttons not all the thousands of electronic components which
it is made up of.
195) What is inheritance ?
Inheritance is one of the important feature of object oriented language. Inheriting is the process of
acquiring features of others. For example a child acquires the features of their parents.
In java inheritance is the process of inheriting member of existing classes by extending their functionality.
The original class is called base class, parent class or super class. The new class derived from parent is
called child class, sub class, and derived class.
We use extends keyword in java to extend a class in java. All java classes extend java.lang.Object since
object class is the super class for all classes in java.
When we create a new class by using inheritance ‘is-a’ relationship is formed.
A doSomeThing()
{
return new A();
}
}
Example : Class B
{
B doSomeThing()
{
return new B();
}
}
From java 1.5 return type for doSomeThing() in Class B is valid . We get compile time error in 1.4 and
earlier.
Collection Framework interview questions
198) What is collections framework ?
A framework is set of classes and interfaces to build a functionality. Java collections framework provides
set of interfaces and classes for storing and manipulating collections. Collection framework contains
classes and interfaces in java.util package and java.util.concurrent packages.
Advantages or benefits of Collections framework :
1) High performance
2) Using this framework we can create different types of collections
29 | P a g e
3) We can create our own collection and we can extend a collection.
4) Reduces programming effort.
5) Increases speed and quality : Collections framework provides high performance, implementations of
useful data structures and algorithms.
30 | P a g e
Some of the operations we can perform on List :
1) Adding an element at specified index.
2) Removing an element at specified index.
3) To get the index of element
List contains some specific methods apart from Collection interface methods.
From java 1.4 ArrayList implements RandomAccess interface which is a marker interface which supports
fast and random access.
Advantages :
1) Faster and easier access.
2) Used for Random access of elements.
Drawbacks :
1) We cannot insert or delete elements from middle of list.
31 | P a g e
array. If we try to put element in index which is
out of range we get ArrayIndexOutOfBounds
Exception
3) Arrays are static 3) ArrayList is dynamic
4) We can store objects and primitives 4) We can store only primitives prior to 1.5 . From
1.5 we can store even objects also.
5) We have to manually write logic for inserting 5) Just a method call would add or remove
and removing elements. elements from list.
6) Arrays are faster 6) Arraylist is slower.
7) Arraylist is implemented using arrays.
208) What is vector?
Vector is similar to arraylist used for random access.
Vector is a dynamic array like arraylist.
vector size increases or decreases when elements are added and removed .
Vector is synchronized .
vector and Hashtable are the only collections since 1.0.
Rest of the collections are added from 2.0.
public class Vector<E>extends AbstractList<E>implements List<E>,
RandomAccess, Cloneable, java.io.Serializable
2) public E getLast() :
getLast() returns the last element in the list.
3) public E removeFirst() :
removeFirst() method removes the first element in the list.
4) public E removeLast() :
32 | P a g e
removeLast() method removes the last element in the list.
Note : If we call next() on last element it will throw java.util.NoSuchElementException. So before calling
next() first we should call hasNext() whether it has elements or not. If there is next element we can call
next() so that we can avoid exception.
Signature :
public interface ListIterator<E> extends Iterator<E> {
}
ListIterator methods :
Method Description
33 | P a g e
Void add(E obj) Inserts element in to the list infront of the element returned by call to next() and
after the element returned by call to next().
boolean hasNext(); Returns true if there are more elements in the list instead of throwing exception if
there are no elements.
E next(); Returns the next element . NoSuchElementException is thrown if there is no next
element.
boolean Returns true if there are elements when iterating list in reverse direction.
hasPrevious();
E previous(); Returns the previous element in the list.
int nextIndex(); Returns the index of the element returned by next() method. If there are no
elements it returns the size of the list.
int Returns the index of the element returned by previous() method. If there are no
previousIndex(); elements it returns the size of the list. Returns -1 if the iterator is at beginning of
list.
void remove(); Removes the element that was returned by calling next() or previous(). An Illegal
state Exception will be thrown if remove() is called before next() or previous().
void set(E e); This method replaces an element in the list with the specified element.
35 | P a g e
collection framework. framework.
36 | P a g e
The advantage of using copyOnWriteArrayList is no need to synchronize list explicitly. So when we use
copyOnWriteArrayList when a thread modifies the list while the other thread was iterating it does n ot
modify original list but creates a copy of list with modified contents so that the iterator won’t know the
modifications made to original list.
37 | P a g e
237) What happens if we don’t define serial version UID ?
If we don’t define serial version UID JVM will create one suid for us. But it is recommended to have suid
rather than JVM creating because at run time JVM has to compute the hashcode of all the properties of
class. This process makes serialization low. We can’t serialize static fields one exception to this is suid
where suid gets serialized along with the object.
Ex :private static final long serialVersionUID = -5885568094444284875L;
239) When we serialize an object does the serialization mechanism saves its references too?
When we serialize an object even the object it refers must implement serializable then the reference
objects also get serialized. If we don’t make reference objects serializable then we get
NotSerializableException.
240) If we don’t want some of the fields not to serialize How to do that?
If we don’t want to serialize some fields during serialization we declare those variables as transient.
During deserialization transient variables are initialized with default values for primitives and null for
object references.
38 | P a g e