You are on page 1of 14



JDK is an acronym for Java Development Kit.It physically exists. It contains JRE +
development tools.

JRE is an acronym for Java Runtime Environment.It is used to provide runtime

environment.It is the implementation of JVM. It physically exists. It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
Just-In-Time(JIT) compiler is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation.Here the term compiler refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.
The classloader is a subsystem of JVM that is used to load classes and interfaces.There
are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System
classloader, Plugin classloader etc.
2. List some features of Java
Some features include Object Oriented, Platform Independent, Robust, Interpreted,
3. Why is Java Architecture Neutral?
Its compiler generates an architecture-neutral object file format, which makes the
compiled code to be executable on many processors, with the presence of Java runtime
4. What is a platform and why is Java Platform Independent?
A platform is basically the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides
software-based platform.
Platform independence means that execution of your program does not dependent on type
of operating system(it could be any : Linux, windows, Mac ..etc). So compile code only
once and run it on any System (In C/C++, we need to compile the code for every machine
on which we run it). Java is both compiler(javac) and interpreter(jvm) based lauguage.
Your java source code is first compiled into byte code using javac compiler. This byte
code can be easily converted to equivalent machine code using JVM. JVM(Java Virtual
Machine) is available in all operating systems we install. Hence, byte code generated by
javac is universal and can be converted to machine code on any operating system, this is
the reason why java is platform independent.
5. What is the philosophy of Java?
Write once and run anywhere
6. Name some popular Java IDEs
Netbeans, Eclipse, etc.
7. What are different OOPS concepts in Java?
OOPs stands for Object Oriented Programming. The concepts in oops are similar to any
other programming languages. Basically, it is program agnostic.

The different OOPS concepts are:


8. What is a Class?
A class is a blue print from which individual objects are created. A class can contain
fields and methods to describe the behavior of an object.
9. What is an Object?
Object is a runtime entity and its state is stored in fields and behavior is shown via
methods. Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication.

10. What are Access Modifiers in Java?

These are the modifiers which are used to restrict the visibility of a class or a field or a
method or a constructor. Java supports 4 access modifiers.
a) private : private fields or methods or constructors are visible within the class in which
they are defined.
b) protected : Protected members of a class are visible within the package but they can
be inherited to sub classes outside the package.
c) public : public members are visible everywhere.
d) default or No-access modifiers : Members of a class which are defined with no
access modifiers are visible within the package in which they are defined.

Accessible to: Public protected package private
Defining class Yes Yes Yes Yes
Class in same package Yes Yes Yes No
Subclass in different package Yes Yes No No
Non-subclass different package Yes No No No

11. Can a top level class be private or protected?

Top level classes in java cant be private or protected, but inner classes in java can. The
reason for not making a top level class as private is very obvious, because nobody can see
a private class and thus they can not use it. Declaring a class as protected also doesnt
make any sense. The only difference between default visibility and protected visibility is
that we can use it in any package by inheriting it. Since in java there is no such concept of
package inheritance, defining a class as protected is no different from default.

12. What are Local Variables, Instance Variables, and Class Variables?
Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and it will be destroyed when
the method has completed.
Instance variables are variables within a class but outside any method. These variables
are instantiated when the class is loaded.
Class Variables are declared with in a class, outside any method, with the static keyword.

13. What is the difference between static and instance methods?

Instance method belongs to the instance of a class therefore it requires an instance before
it can be invoked, whereas static method belongs to the class itself and not to any class
instance so it doesnt need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early)
When the JVM invokes a class instance method, it selects the method to invoke based on
the type of the object reference, which is always known at run-time. On the other hand,
when the JVM invokes a static method, it selects the method to invoke based on the
actual class of the object, which may only be known at compile time.
14. Why static methods cannot access non static variables or methods?
A static method cannot access non static variables or methods because static methods
doesnt need the object to be accessed. So if a static method has non static variables or non
static methods which has instantiated variables they will no be intialized since the object
is not created and this could result in an error.

15. What is Inheritance?

Inheritance allows a Child class to inherit properties from its parent class. In Java this is
achieved by using extends keyword. Only properties with access modifier public and
protected can be accessed in child class.
public class Parent {
public String parentName;
public String familyName;

protected void printMyName() {

System.out.println( My name is + chidName+ +familyName);
public class Child extends Parent {
public String childName;
public int childAge;
protected void printMyName() {
System.out.println( My child name is + chidName+ +familyName);

In above example the child has inherit its family name from the parent class just by
inheriting the class. When child object is created printMyName() present in child class is

16. Polymorphism
Polymorphism in Java has two types: Compile time polymorphism (static binding) and
Runtime polymorphism (dynamic binding). Method overloading is an example of static
polymorphism, while method overriding is an example of dynamic polymorphism.
An important example of polymorphism is how a parent class refers to a child class
object. In fact, any object that satisfies more than one IS-A relationship is polymorphic
in nature.
For instance, lets consider a class Animal and let Cat be a subclass of Animal. So,
any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its
super class Animal.
Note: Its also legal to say every object in Java is polymorphic in nature, as each one
passes an IS-A test for itself and also for Object class.
Static Polymorphism:
In Java, static polymorphism is achieved through method overloading. Method
overloading means there are several methods present in a class having the same name but
different types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method
signatures. So, this is called compile time polymorphism or static binding. The
concept will be clear from the following example:
class DemoOverload{

public int add(int x, int y){ //method 1

return x+y;
public int add(int x, int y, int z){ //method 2
return x+y+z;
public int add(double x, int y){ //method 3
return (int)x+y;
public int add(int x, double y){ //method 4
return x+(int)y;
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
In the above example, there are four versions of add methods. The first method takes
two parameters while the second one takes three. For the third and fourth methods there
is a change of order of parameters. The compiler looks at the method signature and
decides which method to invoke for a particular method call at compile time.
Dynamic Polymorphism:
Suppose a sub class overrides a particular method of the super class. Lets say, in the
program we create an object of the subclass and assign it to the super class reference.
Now, if we call the overridden method on the super class reference then the sub class
version of the method will be called.
Have a look at the following example.
class Vehicle{
public void move(){
System.out.println(Vehicles can move!!);
class MotorBike extends Vehicle{
public void move(){
System.out.println(MotorBike can move and accelerate too!!);
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
vh=new Vehicle();
vh.move(); // prints Vehicles can move!!

It should be noted that in the first call to move(), the reference type is Vehicle and
the object being referenced is MotorBike. So, when a call to move() is made, Java
waits until runtime to determine which object is actually being pointed to by the
reference. In this case, the object is of the class MotorBike. So, the move() method
of MotorBike class will be called. In the second call to move(), the object is of the
class Vehicle. So, the move() method of Vehicle will be called.
As the method to call is determined at runtime, this is called dynamic binding or late

An object in Java that passes more than one IS-A tests is polymorphic in nature

Every object in Java passes a minimum of two IS-A tests: one for itself and one for Object

Static polymorphism in Java is achieved by method overloading

Dynamic polymorphism in Java is achieved by method overriding

17. What is Multiple Inheritance and does Java support it?
If a child class inherits the property from multiple classes is known as multiple
inheritance. Java does not allow to extend multiple classes. The problem with with
multiple inheritance is that if multiple parent classes has a same method name, the at
runtime it becomes diffcult for compiler to decide which method to execute from the
child class. To overcome this problem it allows to implement multiple Interfaces.
18. What is an abstraction?
Abstraction is a way of converting real world objects in terms of class. Its a concept of
defining an idea in terms of classes or interface. For example creating a class Vehicle and
injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
19. What is Encapsulation?
The encapsulation is achieved by combining the methods and attribute into a class. The
class acts like a container encapsulating the properties. The users are exposed mainly
public methods. The idea behind is to hide how thinigs work and just exposing the
requests a user can do.
20. What is Data Hiding?
It means hiding the data from the outside world. Making the instance variable private, it
can only be accessed via interfaces provided in the class (i.e. getter and setter methods).

21. What is difference between abstract class and interface?

A class is called abstract when it is declared with keyword abstract. Abstract class may
contain abstract method. It can also contain n numbers of concrete method. Interface can
only contain abstract methods.

Interface can have only abstract methods. Abstract class can have concerete and
abstract methods.
The abstract class can have public, private, protected or default variables and also
constants. In interface the variable is by default public final. In nutshell the
interface doesnt have any variables it only has constants.
A class can extend only one abstract class but a class can implement multiple
interfaces. Abstract class doesn't support multiple inheritance whereas abstract
class does.
If an interface is implemented its mandatory to implement all of its methods but if
an abstract class is extended its mandatory to implement all abstract methods.
The problem with an interface is, if you want to add a new feature (method) in its
contract, then you MUST implement those method in all of the classes which
implement that interface. However, in the case of an abstract class, the method can
be simply implemented in the abstract class and the same can be called by its

22. Explain with example to describe when to use abstract class and interface?
Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class
will be used and a default implementaion for tyres will be provided.
public abstract class Car {
private final static TOTAL_TYRES = 4;
public abstract String getCarName();
public final int getNoOfTyres() {
Consider a scenario where Cars can have any number of tyres and other features can also
be different. In this case interface will be created.
public interface Car {
public abstract String getCarName();
public abstract int getNoOfTyres();

23. What is the difference between StringBuffer and String class ?

A string buffer implements a mutable sequence of characters. A string buffer is like a
String, but can be modified. At any point in time it contains some particular sequence of
characters, but the length and content of the sequence can be changed through certain
method calls. The String class represents character strings. All string literals in Java
programs, such as "abc" are constant and implemented as instances of this class; their
values cannot be changed after they are created.

24. Difference between StringBuffer and StringBuilder ?

StringBuffer is synchronized whereas StringBuilder is not.

25. Explain the scenerios to choose between String , StringBuilder and StringBuffer
If the Object value will not change in a scenario use String Class because a String object is

If the Object value can change and will only be modified from a single thread, use a
StringBuilder because StringBuilder is unsynchronized(means faster).

If the Object value may change, and can be modified by multiple threads, use a
StringBuffer because StringBuffer is thread safe(synchronized).

26. Which of the two "StringBuilder" or "StringBuffer" is faster and Why ?,

Ans: StringBuilder is not synchronized and hence faster than StringBuffer.

27. What is an Exception?

The exception is said to be thrown whenever an exceptional event occurs in java which
signals that something is not correct with the code written and may give unexpected
result. An exceptional event is a occurrence of condition which alters the normal program
flow. Exceptional handler is the code that does something about the exception.

28. Exceptions are defined in which java package?

All the exceptions are subclasses of java.lang.Exception

29. How are the exceptions handled in java?

When an exception occurs the execution of the program is transferred to an appropriate
exception handler. The try-catch-finally block is used to handle the exception.

The code in which the exception may occur is enclosed in a try block, also called as a
guarded region.
The catch clause matches a specific exception to a block of code which handles that

And the clean up code which needs to be executed no matter the exception occurs or not
is put inside the finally block

30. Explain the exception hierarchy in java.

The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions:
Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of
exceptions extends Exception class.

31. What is Runtime Exception or unchecked exception?

Runtime exceptions represent problems that are the result of a programming problem.
Such problems include arithmetic exceptions, such as dividing by zero; pointer
exceptions: such as trying to access an object through a null reference; and indexing
exceptions: such as attempting to access an array element through an index that is too
large or too small.

Runtime exceptions need not be explicitly caught in try catch block as it can occur
anywhere in a program, and in a typical one they can be very numerous. Having to add
runtime exceptions in every method declaration would reduce a program's clarity. Thus,
the compiler does not require that you catch or specify runtime exceptions (although you
can). The solution to rectify is to correct the programming logic where the exception has
occurred or provide a check.
32. What is checked exception?
Checked exception are the exceptions which forces the programmer to catch them
explicitly in try-catch block. It is a subClass of Exception. Example: IOException.

33. What is difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.
These JVM errors you can not repair them at runtime.Though error can be caught in catch
block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the
cases it is possible to recover from an exception (probably by giving user a feedback for
entering proper values etc.)

34. Once the control switches to the catch block does it return back to the try block
to execute the balance code?
No. Once the control jumps to the catch block it never returns to the try block but it goes
to finally block(if present).

35. Where is the clean up code like release of resources is put in try-catch-finally
block and why?
The code is put in a finally block because irrespective of try or catch block execution the
control will flow to finally block. Typically finally block contains release of connections,
closing of result set etc.

36. Is it valid to have a try block without catch or finally?

NO. This will result in a compilation error. The try block must be followed by a catch or
a finally block. It is acceptable to omit the either catch or the finally block but not both.

37. How do you get the descriptive information about the Exception occurred
during the program execution?
All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method as it
works its way down the call stack from the top.

38. Why is not considered as a good practice to write a single catch all handler to
catch all the exceptions?
You can write a single catch block to handle all the exceptions thrown during the
If you use the Superclass Exception in the catch block then you will not get the valuable
information about each of the exception thrown during the execution, though you can
find out the class of the exception occurred. Also it will reduce the readability of the code
as the programmer will not understand what is the exact reason for putting the try-catch

39. What is exception matching?

Exception matching is the process by which the the jvm finds out the matching catch
block for the exception thrown from the list of catch blocks. When an exception is
thrown, Java will try to find by looking at the available catch clauses in the top down
manner. If it doesn't find one, it will search for a handler for a supertype of the exception.
If it does not find a catch clause that matches a supertype for the exception, then the
exception is propagated down the call stack. This process is called exception matching.

40. What happens if the handlers for the most specific exceptions is placed above the
more general exceptions handler?
Compilation fails. The catch block for handling the most specific exceptions must always
be placed above the catch block written to handle the more general exceptions.
//The code below will not compile.
try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only

// The code below will compile successfully

try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only

41. Does the order of the catch blocks matter if the Exceptions caught by them are
not subtype or supertype of each other?
No. If the exceptions are siblings in the Exception classs hierarchy i.e. If one Exception
class is not a subtype or supertype of the other, then the order in which their
handlers(catch clauses) are placed does not matter.
42. What is a Thread?
In Java, "thread" means two different things:

An instance of class java.lang.Thread.

A thread of execution.

An instance of Thread is justan object. Like any other object in Java, it has variables
and methods, and lives and dies on the heap. But a thread of execution is an individual
process (a "lightweight" process) that has its own call stack. In Java, there is one thread
per call stackor, to think of it in reverse, one call stack per thread. Even if you don't
create any new threads in your program, threads are back there running.

The main() method, that starts the whole ball rolling, runs in one thread, called
(surprisingly) the main thread. If you looked at the main call stack (and you can, any time
you get a stack trace from something that happens after main begins, but not within
another thread), you'd see that main() is the first method on the stack the method at the
bottom. But as soon as you create a new thread, a new stack materializes and methods
called from that thread run in a call stack that's separate from the main() call stack.

43. What is difference between a thread and a process?

Threads share the address space of the process that created it; processes have their
own address.
Threads have direct access to the data segment of its process; processes have their
own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes
must use interprocess communication to communicate with sibling processes.
Threads have almost no overhead; processes have considerable overhead.
New threads are easily created; new processes require duplication of the parent
Threads can exercise considerable control over threads of the same process;
processes can only exercise control over child processes.
Changes to the main thread (cancellation, priority change, etc.) may affect the
behavior of the other threads of the process; changes to the parent process do not
affect child processes.

44. What are the advantages or usage of threads?

Threads support concurrent operations. For example,
Multiple requests by a client on a server can be handled as an individual client thread.
Long computations or high-latency disk and network operations can be handled in the
background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.

In sequential programming, updating multiple displays normally requires a big while-
loop that performs small parts of each display update. Unfortunately, this loop basically
simulates an operating system scheduler. In Java, each view can be assigned a thread to
provide continuous updates.
Programs that need to respond to user-initiated events can set up service routines to
handle the events without having to insert code in the main routine to look for these

Threads provide a high degree of control.

Imagine launching a complex computation that occasionally takes longer than is
satisfactory. A "watchdog" thread can be activated that will "kill" the computation if it
becomes costly, perhaps in favor of an alternate, approximate solution. Note that
sequential programs must muddy the computation with termination code, whereas, a Java
program can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.

A computer with multiple CPUs can literally execute multiple threads on different
functional units without having to simulating multi-tasking ("time sharing").
On some computers, one CPU handles the display while another handles computations
or database accesses, thus, providing extremely fast user interface response times.