0% found this document useful (0 votes)
7 views

Java Review Q&As

Uploaded by

myhealth632
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Review Q&As

Uploaded by

myhealth632
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

JAVA KEYWORDS

Q1) What are different types of access modifiers in Java?

A1) There are four different types of modifiers:

Modifer Accessible in the same package Accessible in different package


Private No No
Protected Yes Yes, only if the class extends the main class
Default Yes No
Public Yes Yes

Q2) What is the use of final keyword?

A2) The final keyword can be assigned to:

• Class level variable


• method
• class
• Objects

If a final is assigned to a variable, the variable behaves as a constant. It means that


value of the variable once set cannot be changed.

final int i = 1; i = 5; // error

If a final is assigned to a method then it cannot be overridden in its child class.

class Parent {
final void print() {
System.out.println("Inside");}
}
class Child extends Parent {
public final void print() {
// error cannot override final method
System.out.println("Inside");}
}

If a class is made as final, then no other class can extend it and make it as parent class.
E.g. String Class cannot be extended.

Final objects are instantiated only once. i.e

final Map map = new HashMap();


map.put("key";,"value");
map = new HashMap(); // error
Q3) What is the use of synchronized keyword?

A3) This keyword is helps to prevent concurrent access of a block of code or


modifying objects. Synchronized keyword can be applied to static/non-static methods
or a block of code. Only one thread at a time can access synchronized methods and if
there are multiple threads trying to access the same method then other threads have to
wait for the execution of method by one thread. Synchronized keyword provides a
lock on the object and thus prevents race condition. E.g.

public void synchronized simpleMethod() {}


public void synchronized staticMethod() {}
public void myMethod() {
synchronized (this) {
// synchronized keyword on block of code }
}

Q4) What is a volatile keyword?

A4) In general each thread has its own copy of a variable, such that one thread is not
concerned with the value of the same variable in the other thread. But sometimes this
may not be the case. Consider a scenario in which the count variable is holding the
number of times a method is called for a given class irrespective of any thread calling,
in this case, irrespective of thread access the count has to be increased and value
needs to be consistent across all the threads. In this case the count variable is declared
as volatile. The copy of a volatile variable is stored in the main memory, so every
time a thread access the variable even for reading purpose the local copy is updated
each time from the main memory. The volatile variable may have performance issues.

Q5) What is a transient variable?

A5) If some of the properties of a class are not required to be serialized then the
variables are marked as transient. When an object is deserialized the transient
variables retains the default value depending on the data type of variable and will
loose its original value.

Q6) What is a strictfp modifier?

A6) Only variables can be marked as strictfp. It is used to restrict floating point
calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is
specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point
specification ) and returns the consistent value independent of the platform. That is, if
you want the answers from your code (which uses floating point values) to be
consistent across all then platforms, then you need to specify the strictfp modifier.
Q7) What is a static variable?

A7) Static keyword can be used with the variables and methods but not with the class.
Anything declared as static is related to class and not objects.

Static variable: Multiples objects of a class shares the same instance of a static
variable. Consider the example:

public class Counter {


private static int count=0;
private int nonStaticcount=0;
public void incrementCounter() {
count++;
nonStaticcount++; }
public static int getCount() {
return count; }
public int getNonStaticcount() {
return nonStaticcount; }
public static void main(String args[]) {
Counter countObj1 = new Counter();
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj2.incrementCounter();
System.out.println("Static count for Obj1:
"+countObj1.getCount());
System.out.println("NonStatic count for Obj1:
"+countObj1.getNonStaticcount());
System.out.println("Static count for Obj2:
"+countObj2.getCount())
System.out.println("NonStatic count for Obj2:
"+countObj2.getNonStaticcount()) }

Output:
Static count for Obj1: 2
NonStatic count for Obj1: 1
Static count for Obj2: 2
NonStatic count for Obj2: 1

In the above program obj1 and obj2 share the same instance of static variable count
hence if the value is incremented by one object , the incremented value will be
reflected for obj1 and obj2.
Q8) What is a static method?

A8) A static method can be accessed without creating the objects. Just by using the
Class name the method can be accessed. Static method can call only static methods
but not non-static methods. But non-static methods can call static methods. Static
method can only access static variables and not local or global non-static variables.
For eg:

public class Test{


public static void printMe() {
System.out.println("Hello World"); }
}
public class MainClass {
public static void main(String args[]) {
Test.printMe() }
}

Output:
Hello World

Q9) Why static methods cannot access non static variables or methods?

A9) A static method cannot access non static variables or methods because static
methods can be accessed without instantiating the class, so if the class is not
instantiated the variables are not intialized and thus cannot be accessed from a static
method.

Q10) What is a static class?

A10) A class cannot be declared static except inner class. But a class can be said a
static class if all the variables and methods of the class are static and the constructor is
private. Making the constructor private will prevent the class to be instantiated. So the
only possibility to access is using Class name only

Q11) How is throw keyword used?

A11) Throw keyword is used to throw the exception manually. It is mainly used when
the program fails to satisfy the given condition and it wants to warn the
application.The exception thrown should be a subclass of Throwable.

public void parent() {


try {
child(); }
catch(MyCustomException e) {
//oops error is here }
}
public void child() throws MyCustomException {
if(2%2 == 0) {
throw new MyCustomException("exception using throw
keyword"); }
}
Q12) What is the use of throws keyword?

A12) Throws clause is used to throw the exception from a method to the calling
method which could decide to handle the exception or throw to its calling method in a
class.

public void parent(){


try {
child(); }
catch(MyCustomException e) { }
}
public void child throws MyCustomException {
//put some logic so that the exception occurs.}
KEY CONCEPTS IN JAVA:

Q1) Why is main() method static?

A1) To access a static method class object is not needed. The method can be accessed
directly with the help of ClassName. So when a program is started the jvm search for
the class with main method and calls it without creating an object of the class.

Q2) What is the difference between static and instance methods?

A2) instance method belongs to the instance of a class and requires an instance to be
invoked, whereas static method belongs to the class itself and not to any class instance
so it doesn’t need a class instance to be invoked. Instance methods use dynamic (late)
binding, whereas static methods use static (early) binding. 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 be invoked based on the actual class
of the object, which may only be known at compile time.

Q3) Does java supports pass by value or pass by reference?

A3) Java supports only pass by value. The arguments passed as a parameter to a
method is mainly primitive data types or objects. For the data type the actual value is
passed. Java passes the references by value just like any other parameter. The pointer
to the object is passed as value. Thus, method manipulation will alter the objects but
will not intialize the new object. Consider the example:

public void tricky(Point arg1, Point arg2) {


arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp; }
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }

Output:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0

The method successfully alters the value of pnt1, even though it is passed by value;
however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the
main() method, pnt1 and pnt2 are nothing more than object references. When you
pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like
any other parameter. This means the references passed to the method are actually
copies of the original references.

Q4) Can static block throw exception?

A4) Yes, static block can throw only Runtime exception or can use a try-catch block
to catch checked exception. Typically scenario will be if JDBC connection is created
in static block and it fails then exception can be caught, logged and application can
exit. If System.exit() is not done, then application may continue and next time if the
class is referred JVM will throw NoClassDefFounderror since the class was not
loaded by the Classloader.

Q5) What is the difference between abstract class and interface ?

A5) A class is called abstract when it is declared with the keywordabstract. Abstract
class contains at least one abstract method. It can also contain n numbers of concrete
method. An interface can only contain abstract methods.

i. An interface can have only abstract methods. Abstract class can have concrete
and abstract methods.
ii. 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 doesn't have any variables it only has constants.
iii. A class can extend only one abstract class but a class can implement multiple
interfaces. Abstract class doesn't support multiple inheritance whereas interface
does.
iv. 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.
v. The problem with an interface is, if you want to add a new feature (method) in its
contract, then you MUST implement the new method(s) 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
subclass.

Q6) Explain with an example to describe when to use abstract class and
interface?

A6) Cars are meant for driving but each car has its own driving technique(4 wheel
drive etc). Consider a class Drive which can have the drive method as an abstract with
child class implementing the drive method.

public abstract class Drive {


public abstract void drive(); }
public class 4WD extends Drive {
public void drive() { // 4wd drive } }
public class 2WD extends Drive {
public void drive() { //2wd drive } }
The 4WD or 2WD can be of type Car or Truck etc. Here to define type of drive for a
Car or Truck, Car and Truck are good candidate of an interface.

public interface Car { }


public interface Truck { }
public Car4WD extends Drive implements Car { }
public Truck4WD extends Drive implements Truck { }

Q7) Does java support multiple inheritance? Why?

A7) Java doesn't support multiple inheritance but it provides a way through which it
can be enacted. Consider the scenario in C++

Class A {
public void add() { // some text } }
Class B {
public void add() { // some text } }
Class C extends A,B {
public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and can’t
decide to call Class A or B method
}

In the above code the compiler doesn't know which class add() method should be
called. This problem is called Diamond problem. This problem in java is resolved
with the use of interfaces A Java interface is a bit like a class, except a Java interface
can only contain method signatures and fields. A Java interface cannot contain an
implementation of the methods(until Java8), only the signature (name, parameters and
exceptions) of the method. You can use interfaces in Java as a way to achieve
polymorphism.

In Java similar problem would look like:


interface A { void add(); }
interface B { void add(); }
class C implements A,B { void add()
{ // doesnt matter which interface it belong to } }

Q8) Can this keyword be assigned null value?

A8) No

Q9) What are the different types of references in java?

A9) Java has a more expressive system of reference than most other garbage-collected
programming languages, which allows for special behavior for garbage collection. A
normal reference in Java is known as a strong reference. The java.lang.ref package
defines three other types of references—soft, weak and phantom references. Each type
of reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable
by a strong reference (that is, not strongly reachable) but is referenced by a soft
reference is called softly reachable. A softly reachable object may be garbage
collected at the discretion of the garbage collector. This generally means that softly
reachable objects will only be garbage collected when free memory is low, but again,
it is at the discretion of the garbage collector. Semantically, a soft reference means
"keep this object unless the memory is needed."

A WeakReference is used to implement weak maps. An object that is not strongly or


softly reachable, but is referenced by a weak reference is called weakly reachable. A
weakly reachable object will be garbage collected during the next collection cycle.
This behavior is used in the class java.util.WeakHashMap. A weak map allows the
programmer to put key/value pairs in the map and not worry about the objects taking
up memory when the key is no longer reachable anywhere else. Another possible
application of weak references is the string intern pool. Semantically, a weak
reference means "get rid of this object when nothing else references it."

A PhantomReference is used to reference objects that have been marked for garbage
collection and have been finalized, but have not yet been reclaimed. An object that is
not strongly, softly or weakly reachable, but is referenced by a phantom reference is
called phantom reachable. This allows for more flexible cleanup than is possible with
the finalization mechanism alone. Semantically, a phantom reference means "this
object is no longer needed and has been finalized in preparation for being collected."

Q10) How to change the heap size of a JVM?

A10) The old generation's default heap size can be overridden by using the -Xms and
-Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program

Q11) What is the difference between instanceof and isInstance(Object obj)?

A11) Differences are as follows:

i) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of


java.lang.Class.

ii) instanceof is used to identify whether the object is of a particular class type or its
subclass but isInstance(obj) is used to identify object of a particular class.

Q12) What is a memory leak?

A12) A memory leak is where an unreferenced object that will never be used again
still hangs around in memory and doesn't get garbage collected.
Q13) What is the difference between equals() and ==?

A13) == operator is used to compare the references of the objects.


public boolean equals(Object o) is the method provided by the Object class. The
default implementation uses == operator to compare two objects. But since the
method can be overridden like for String class. equals() method can be used to
compare the values of two objects.

String str1 = "MyName";


String str2 = new String("MyName");
String str3 = str2; if (str1 == str2) {
System.out.println("Objects are equal"); }
else { System.out.println("Objects are not equal"); }
if (str1.equals(str2)) {
System.out.println("Objects are equal"); }
else { System.out.println("Objects are not equal"); }

Output1:
Objects are not equal
Objects are equal

String str2 = "MyName";


String str3 = str2; if (str2 == str3) {
System.out.println("Objects are equal"); }
else { System.out.println("Objects are not equal"); }
if (str3.equals(str2)) {
System.out.println("Objects are equal"); }
else { System.out.println("Objects are not equal"); }

Output2:
Objects are equal
Objects are equal

Q14) Can an abstract class have a static method?

A14) Yes an abstract class have a static method and it can be accessed by any other
class(even not a concrete class).

Q15) Can an abstract class have a constructor?

A15) Yes an abstract class have a default and parameterized constructors.

Q16) Why static methods cannot access non static variables or methods?

A16) 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.
Q17) What is difference between stringbuffer and stringbuilder?

A17) The only difference between StringBuffer and StringBuilder is that


StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the
application needs to be run only in a single thread then it is better to use
StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among StringBuffer and StringBuilder

- If your text can change and will only be accessed from a single thread, use a
StringBuilder because StringBuilder is unsynchronized.
- If your text can change, and will be accessed from multiple threads, use a
StringBuffer because StringBuffer is synchronous.

Q18) Consider a scenario in which the admin want to sure that if some one has
written System.exit() at some part of application then before system shutdown all
the resources should be released. How is it possible?

A18) This is possible using Runtime.getRuntime().addShutdownHook(Thread


hook).

Straight from Java Spec:

This method registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

i. The program exits normally, when the last non-daemon thread exits or when the
exit (equivalently, System.exit) method is invoked.
ii. The virtual machine is terminated in response to a user interrupt, such as typing
^C, or a system-wide event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual
machine begins its shutdown sequence it will start all registered shutdown hooks in
some unspecified order and let them run concurrently. When all the hooks have
finished it will then run all uninvoked finalizers if finalization-on-exit has been
enabled. Finally, the virtual machine will halt. Note that daemon threads will continue
to run during the shutdown sequence, as will non-daemon threads if shutdown was
initiated by invoking the exit method. Once the shutdown sequence has begun it can
be stopped only by invoking the halt method, which forcibly terminates the virtual
machine.
Q19) What is the difference between final, finally and finalize() in Java?

A19)

final - A final variable act as constant, a final class is immutable and a final method
cannot be ovrriden.

finally - handles exception. The finally block is optional and provides a mechanism to
clean up regardless of what happens within the try block (except System.exit(0) call).
Use the finally block to close files or to release other system resources like database
connections, statements etc.

finalize() - method helps in garbage collection. A method that is invoked before an


object is discarded by the garbage collector, allowing it to clean up its state. Should
not be used to release non-memory resources like file handles, sockets, database
connections etc because Java has only a finite number of these resources and you do
not know when the garbage collection is going to kick in to release these non-memory
resources through the finalize() method.

Q20) How does Java allocate stack and heap memory?

A20) Each time an object is created in Java it goes into the part of memory known as
heap. The primitive variables like int and double are allocated in the stack, if they are
local method variables and in the heap if they are member variables (i.e. fields of a
class). In Java methods local variables are pushed into stack. When a method is
invoked and stack pointer is decremented when a method call is completed.

In a multi-threaded application each thread will have its own stack but will share the
same heap. This is why care should be taken in your code to avoid any concurrent
access issues in the heap space. The stack is threadsafe (each thread will have its own
stack) but the heap is not threadsafe unless guarded with synchronisation through
your code.

Q21) Explain re-entrant, recursive and idempotent methods/functions?

A21)

A method in stack is re-entrant allowing multiple concurrent invocations that do not


interfere with each other.

A function is recursive if it calls itself. Given enough stack space, recursive method
calls are perfectly valid in Java though it is tough to debug. Recursive functions are
useful in removing iterations from many sorts of algorithms.

All recursive functions are re-entrant but not all re-entrant functions are recursive.
Idempotent methods are methods, which are written in such a way that repeated
calls to the same method with the same arguments yield same results. For example
clustered EJBs, which are written with idempotent methods, can automatically
recover from a server failure as long as it can reach another server.
Q22) Can a private variable or method of a class can be accessed?

A22) Yes its possible using reflection.

Q23) What is difference between static block and the init block?

A23) The static block is loaded when the class is loaded by the JVM for the 1st time
only whereas init {} block is loaded every time class is loaded. Also first the static
block is loaded then the init block.

public class LoadingBlocks {


static { System.out.println("Inside static"); }{
System.out.println("Inside init"); }
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks(); } }

Output:
Inside static
Inside init
Inside init
Inside init

Q24) Why inner class can access only final variable?

A24) Local classes can most definitely reference instance variables. The reason they
cannot reference non final local variables is because the local class instance can
remain in memory after the method returns. When the method returns the local
variables go out of scope, so a copy of them is needed. If the variables weren't final
then the copy of the variable in the method could change, while the copy in the local
class didn't, so they'd be out of synch.

Anonymous inner classes require final variables because of the way they are
implemented in Java. An anonymous inner class (AIC) uses local variables by
creating a private instance field which holds a copy of the value of the local variable.
The inner class isn't actually using the local variable, but a copy. It should be fairly
obvious at this point that a "Bad Thing"™ can happen if either the original value or
the copied value changes; there will be some unexpected data synchronization
problems. In order to prevent this kind of problem, Java requires you to mark local
variables that will be used by the AIC as final (i.e., unchangeable). This guarantees
that the inner class' copies of local variables will always match the actual values.

Q25) What is fully abstract class?

A25) An abstract class which has all methods as abstract and all fields are public
static final.
Q26) What is dynamic binding and static binding?

A26) Method invocation - The Java programming language provides two basic kinds
of methods: instance methods and class (or static) methods. The differences are:
1. Instance methods require an instance before they can be invoked, whereas class
methods do not.
2. Instance methods use dynamic (late) binding, whereas class methods use static
(early) binding.

When the Java virtual machine invokes a class method, it selects the method to invoke
based on the type of the object reference, which is always known at compile-time. On
the other hand, when the virtual machine invokes an instance method, it selects the
method to invoke based on the actual class of the object, which may only be known at
run time.

Q27) What is Java Reflection?

A27) Reflection is commonly used by programs which require the ability to examine
or modify the runtime behavior of applications running in the Java virtual machine.

Drawbacks of Reflection: Reflection is powerful, but should not be used


indiscriminately. If it is possible to perform an operation without using reflection,
then it is preferable to avoid using it. The following concerns should be kept in mind
when accessing code via reflection.

Performance Overhead: Because reflection involves types that are dynamically


resolved, certain Java virtual machine optimizations can not be performed.
Consequently, reflective operations have slower performance than their non-reflective
counterparts, and should be avoided in sections of code which are called frequently in
performance-sensitive applications.

Security Restrictions: Reflection requires a runtime permission which may not be


present when running under a security manager. This is in an important consideration
for code which has to run in a restricted security context, such as in an Applet.

Exposure of Internals: Since reflection allows code to perform operations that would
be illegal in non-reflective code, such as accessing private fields and methods, the use
of reflection can result in unexpected side-effects, which may render code
dysfunctional and may destroy portability. Reflective code breaks abstractions and
therefore may change behavior with upgrades of the platform.

Q28) When an obj is passed through a function , one can set the properties but
cannot set a new memory location?

A28) It is because when u pass an object the address value is passed and stored in
some new address . like if address 1234 is passed , it is stored in 4567 location. So if u
change in the value of an object it will take the address from 4567 and do
1234.setXXX(). If u set the object to null it will set 4567=null.
JAVA OOP CONCEPTS:

OOPs stands for Object Oriented Programming. OOPs is a programming


paradigm formulated around Objects which can hold attributes defining it behavior.
The data of the objects can be modified by the methods. Concepts of OOPS include
Abstraction, Polymorphism, Inheritance, Encapsulation.

The two building blocks of OOPs are Class and Object.

Class: can be defined as a collections of attributes and methods defining the


behaviour of an object.

Object: Instance of a class having the values assigned to the properties of the
class.Each object is said to be an instance of a particular class. Procedures in object-
oriented programming are known as methods; variables are also known as fields,
members, attributes, or properties.

Common terminology used in OOPs

Class variables - belong to the class as a whole; there is only one copy of each
one.
Instance variables or attributes - data that belongs to individual objects; every
object has its own copy of each one.
Member variables - refers to both the class and instance variables that are
defined by a particular class
Class methods - belong to the class as a whole and have access only to class
variables and inputs from the procedure call.
Instance methods - belong to individual objects, and have access to instance
variables for the specific object they are called on, inputs, and class variables.

Q1) What are different oops concept in java?

A1) The different OOP concepts are : Polymorphism, Inheritance, Abstraction,


Encapsulation, Aggregation, Composition, and Association

Q2) What is polymorphism?

A2) The ability to identify a function to run is called Polymorphism. In java, c++
there are two types of polymorphism: compile time polymorphism (overloading) and
runtime polymorphism (overriding).

Method overriding: Overriding occurs when a class method in a child class has the
same name and signature as a method in the parent class. When you override
methods, JVM determines the proper method to call at the program’s run time, not at
the compile time.
Overloading: Overloading is determined at the compile time. It occurs when several
methods have same names with:

Different method signature and different number or type of parameters.


Same method signature but the different number of parameters.
Same method signature and same number of parameters but of different type

Example of Overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //error conflict with the method int
add(int a)

class BookDetails {
String title;
setBook(String title){} }
class ScienceBook extends BookDetails {
setBook(String title){} //overriding
setBook(String title, String publisher,float price){}
//overloading }

Q3) What is inheritance?

A3) 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; //inheritance
protected void printMyName() {
System.out.println(“ My child name is “+ chidName+” “
+familyName); } }

In a example above the child has inherited its family name from the parent class just
by inheriting the class. When a child object is created the method printMyName()
present in the child class is called.
Q4) What is multiple inheritance and does java support?

A4) 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 the
multiple inheritance is that if multiple parent classes have methods with same name,
then at runtime it becomes difficult for the compiler to decide which method to
execute from the child class. To overcome this problem java allows to implement
multiple Interfaces. The problem is commonly referred as Diamond Problem.

Q5) What is the difference between polymorphism and inheritance?

A5)

- Inheritance defines parent-child relationship between two classes,


polymorphism takes advantage of that relationship to add dynamic behavior in
your code.
- Inheritance encourages code reusability by allowing child class to inherit
behavior from the parent class. On the other hand Polymorphism allows child
to redefine already defined behaviour inside the parent class. Without
Polymorphism it's not possible for a child to execute its own behaviour while
represented by a Parent reference variable, but with Polymorphism it can be
done.
- Java doesn't allow multiple inheritance of classes, but allows multiple
inheritance of Interface, which is actually required to implement
Polymorphism. For example, a class can be Runnable, Comparator and
Serializable at the same time because all three are interfaces. This makes them
pass around in code e.g. you can pass an instance of this class to a method
which accepts Serializable, or to Collections.sort() which accepts a
Comparator.

Both Polymorphism and Inheritance allow Object oriented programs to evolve. For
example, by using Inheritance you can define new user types in an Authentication
System and by using Polymorphism you can take advantage of already written
authentication code. Since, Inheritance guarantees minimum base class behaviour, a
method depending upon super class or super interface can still accept an object of the
base class and can authenticate it.

Q6) What is an abstraction?

A6) Abstraction is a way of converting real world objects in terms of class. It's 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; }
Q7) What is Encapsulation?

A7) 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 things work and just
exposing the requests a user can do.

Q8) What is Association?

A8) Association is a relationship where all object have their own lifecycle and there is
no owner. Let's take an example of Teacher and Student. Multiple students can
associate with a single teacher and single student can associate with multiple teachers
but there is no ownership between the objects and both have their own lifecycle. Both
can create and delete independently.

Q9) What is Aggregation?

A9) Aggregation is a specialized form of Association where all objects have their own
lifecycle but there is ownership and child object can not belongs to another parent
object. Let's take an example of Department and teacher. A single teacher cannot
belong to multiple departments, but if we delete the department teacher object will not
destroy. We can think about "has-a" relationship.

Q10) What is Composition?

Ans) Composition is specialized form of Aggregation and we can call this as a


"death" relationship. It is a strong type of Aggregation. Child object does not have
their lifecycle and if parent object deletes all child object will also be deleted. Let's
take again an example of a relationship between House and rooms. House can contain
multiple rooms there is no independent life of room and any room can not belongs to
two different house if we delete the house room will automatically delete.
JAVA COLLECTIONS:

Collections in Java offer some of the most comprehensive suites of built-in Data
structures. Often this is the most common topic amongst interviewers. Good
foundation and understanding of java collections help developer in building efficient
programs.

Q1) What is the difference between an ArrayList and a vector?

A1)

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In


Vector class each method like add(), get(int i) is surrounded with a synchronized
block, thus making Vector class thread-safe.

Data growth - Internally, both the ArrayList and Vector hold onto their contents
using an Array. This means that the collection is of fixed size. When the
collection is coming to near it's max capacity it dynamically resizes itself. A
Vector defaults to doubling the size of its array, while the ArrayList increases its
array size by 50 percent.

Performance - Since Vector is thread-safe, the performance is slower than


ArrayList.

Q2) How can an ArrayList be synchronized without using Vector?

A2) ArrayList can be synchronized using:

Collections.synchronizedList(List list)
//Other collections can be synchronized:
Collections.synchronizedMap(Map map)
Collections.synchronizedCollection(Collection c)

Q3) If an Employee class is present and its objects are added in an ArrayList.
Now I want the list to be sorted on the basis of the employeeID of Employee
class. What are the steps?

A3) One way to achieve is by using Comparable interface. Implement Comparable


interface to the Employee class and override the compareTo(Object obj) method in
which compare the employeeID.

class Employee implements Comparable<Employee> {


private int id;
private String name;
public int compareTo(Employee e1) {
return this.id == e1.id; } }

Now call Collections.sort() method and pass the list as an argument.


Now consider that Employee class is a jar file.

Since Comparable interface cannot be implemented, create Comparator and override


the compare(Object obj, Object obj1) method.

Call Collections.sort() on the list and pass comparator as an argument.

class EmployeeComparator implements Comparator<Employee>


{
public int compare(final Employee e1, final Employee e2)
{
return this.e1.id == e2.id; } }
//some class
List<Employee> employees = new ArrayList();
//add employee to employees
//sort the employees
Collections.sort(employess, new EmployeeComparator());

Q4) What is the difference between HashMap and HashTable?

A4) Both collections implements Map. Both collections store value as key-value
pairs. The key differences between the two are:

Hashmap is not synchronized in nature but hashtable is(thread-safe). This means that
in a multithreaded application, only one thread can get access to a hashtable object
and performs an operation on it. Hashmap doesn't guarantee such behavior and is not
used in multithreaded environment.

Hashmap is traversed using an iterator, hashtable can be traversed by enumerator or


iterator.

Iterator in hashmap and hashtable is fail fast but enumerator in hashtable is fail safe.

HashMap permits null values and only one null key, while Hashtable doesn't allow
key or value as null.

Since hashtable is synchronized, it is relatively slower in performance than hashmap

Q5) What are the classes implementing the List interface?

A5) There are three implementations of the List interface:

ArrayList : It is a resizable array implementation. The size of the ArrayList can be


increased dynamically also operations like add, remove and get can be formed once
the object is created. It also ensures that the data is retrieved in the manner it was
stored. The ArrayList is not thread-safe.
Vector: It is the thread-safe implementation of ArrayList. The methods are wrapped
around a synchronized block.
LinkedList: the LinkedList implements Queue interface too and provide FIFO (First
In First Out) which mean than element is always removed from the head of the list
and element is added at the end of the list. It is faster than ArrayList for add and
remove operation as time complexity is O(1). But for searching or getting an element
the average time complexity is O(n) where n is the size of the list.

Q6) Which all classes implement the Set interface ?

A6) A Set is a collection that contains no duplicate elements. More formally, a set
contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null
element. HashSet, SortedSet and TreeSet are the commonly used class which
implements Set interface.

SortedSet - It is an interface which extends Set. As the name suggests, the interface
allows the data to be iterated in the ascending order or sorted on the basis of
Comparator or Comparable interface. All elements inserted into the interface must
implement Comparable or Comparator interface.

TreeSet - It is the implementation of SortedSet interface. This implementation


provides guaranteed log(n) time cost for the basic operations (add, remove and
contains). The class is not synchronized. The class uses Red-Black tree data structure.

HashSet: This class implements the Set interface, backed by a hash table (actually a
HashMap instance). It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant over time. This
class permits the null element. This class offers constant time performance for the
basic operations (add, remove, contains and size), assuming the hash function
disperses the elements properly among the buckets

Q7) What is the difference between List and a Set?

A7) A list can contain duplicate values but Set doesn't allow duplicates. A list allows
retrieval of data to be in same order of insertion but Set doesn't ensures the order in
which the elements can be retrieved.(Except HashSet)

Q8) What is the difference between Arrays and ArrayList ?

A8) Arrays are created of fix size whereas ArrayList is dynamic in nature and can
vary its length. Also the size of an array cannot be incremented or decremented. But
ArrayList has the ability to dynamically increase its capacity and insert more
elements.

Once the array is created elements cannot be added or deleted from it. But with
ArrayList the elements can be added and deleted at runtime.

List list = new ArrayList();


list.add(1);
list.add(3);
list.remove(0) //will remove the element from the
1st location.
ArrayList is one-dimensional but an array can be multidimensional.

int[][][] intArray= new int[3][2][1]; // 3


dimensional array

An Array can contain objects of a single data type or class. ArrayList if not used with
generic can contain objects of different class types.

Q9) When to use ArrayList or LinkedList ?

A9)

Insertion: Adding new elements is pretty fast for either type of list. Inserting an
element to the start of end of the ArrayList takes O(1). Inserting in middle of an
ArrayList is operation of O(n). Inserting an element in Linkedlist takes O(1).

Access: For the ArrayList, getting an element from the index i is faster O(1) because
each element has an index and can be accessed directly with an index but for
LinkedList lookup time complexity isO(n). It's slow because elements are accessed in
an sequential manner and always access starts from the head of the list.

Deletion:Time complexity of deletion in arraylist is O(n). This is because all


remaining elements in the underlying array of Object instances must be shifted to the
left after each remove operation. Linkedlist has time complexity of O(1) because
deletion can be done by updating the pointers of prev and next elements.

So an ArrayList works best for cases where you're doing random access on the list
and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Q10) What data structure is used to implement HashSet?

A10) HashSet implements Hashmap internally to store the data. The data passed to
hashset is stored as a key in hashmap with null as value. This can be summarized as
HashMap with keys and null value is a hashset.

Q11) What is a ConcurrentHashMap?

A11) A concurrentHashMap is a thread-safe implementation of Map interface. In this


class put and remove methods are synchronized but not get method. This class is
different from Hashtable in terms of locking; it means that hashtable use object level
lock but this class uses bucket level lock thus having better performance. The allowed
concurrency among update operations is guided by the optional concurrencyLevel
constructor argument (default 16), which is used as a hint for internal sizing. The
table is internally partitioned to try to permit the indicated number of concurrent
updates without contention. Because placement in hash tables is essentially random,
the actual concurrency will vary. Ideally, you should choose a value to accommodate
as many threads as will ever concurrently modify the table. Using a significantly
higher value than you need can waste space and time, and a significantly lower value
can lead to thread contention. But overestimates and underestimates within an order
of magnitude do not usually have much noticeable impact. A value of one is
appropriate when it is known that only one thread will modify and all others will only
read. Also, resizing this or any other kind of hash table is a relatively slow operation,
so, when possible, it is a good idea to provide estimates of expected table sizes in
constructors.

Q12) What is the difference between iterator access and index access?

A12) Index based access allows access of the element directly on the basis of index.
The cursor of the data structure can directly goto the 'nth' location and get the
element. It does not have to traverse through n-1 elements.

In Iterator based access, the cursor has to traverse through each element to get the
desired element. So to reach the 'nth' element it needs to traverse through n-1
elements.

Insertion, updation or deletion will be faster for iterator based access if the operations
are performed on elements present in middle of the data structure.

Insertion, updation or deletion will be faster for index based access if the operations
are performed on elements present at the end of the data structure.

Traversal or search in index based data structure is faster.

ArrayList is index access and LinkedList is iterator access.

Q13) How to sort a list in reverse order?

A13) To sort the elements in the reverse natural order of the strings, get a reverse
Comparator from the Collections class with reverseOrder(). Then, pass the reverse
Comparator to the sort() method.

List list = new ArrayList();


Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)

Q14) Can a null element be added to a Treeset or HashSet?

A14) A null element can be added only if the set is of size 1 because when a second
element is added then as per set definition a check is made to check duplicate value
and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

Q15) What are advantages of iterating a collection using iterator?

A15) For loop does not allow updating the colection(add or remove) whereas Iterator
does allow modifying the collection. Also Iterator can be used where there is no clue
what type of collections will be used because all collections implement Iterator
interface.
Q16) How to sort a list of strings - case insensitive ?

A16) Collections.sort(list,
String.CASE_INSENSITIVE_ORDER);

Q17) How to make a List (ArrayList,Vector,LinkedList) read only ?

A17) A list implemenation can be made read only using


Collections.unmodifiableList(list). This method returns a new list. If a user tries to
perform add operation on the new list; UnSupportedOperationException is thrown.
EXCEPTIONS IN JAVA:

Q1) What is an Exception?

A1) 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 an occurrence of a condition which alters
the normal program flow. Exceptional handler is the code that does something about
the exception.

Q2) Explain the exception hierarchy in java.

A2) 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 types of exception extends Exception class.

Q3) How are the exceptions handled in java?

A3) 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 exception. And the cleanup code which needs to be
executed no matter the exception occurs or not is put inside the finally block

Q4) What is Runtime Exception or unchecked exception?

A4) 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.

Q5) What is checked exception?

A5) Checked exception are the exceptions which force the programmer to catch them
explicitly in try-catch block. It is a subClass of Exception. Example: IOException.

Q6) What is the difference between Error and Exception?

A6) An error is an irrecoverable condition occurring at runtime. Such as


OutOfMemory error. These JVM errors you can not repair them at runtime, 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.)

Q7) What is the difference between ClassNotFoundException and


NoClassDefFoundError?

A7) A ClassNotFoundException is thrown when the reported class is not found by the
ClassLoader in the CLASSPATH. It could also mean that the class in question is
trying to be loaded from another class which was loaded in a parent classloader and
hence the class from the child classloader is not visible.

Consider if NoClassDefFoundError occurs which is something like

java.lang.NoClassDefFoundError

src/com/TestClass does not mean that the TestClass class is not in the CLASSPATH.
It means that the class TestClass was found by the ClassLoader but when trying to
load the class, it ran into an error reading the class definition. This typically happens
when the class in question has static blocks or members which use a Class that's not
found by the ClassLoader. So to find the culprit, view the source of the class in
question (TestClass in this case) and look for code using static blocks or static
members.
Q8) What is a throw keyword?

A8) Throw keyword is used to throw the exception manually. It is mainly used when
the program fails to satisfy the given condition and it wants to warn the
application.The exception thrown should be subclass of Throwable.

public void parent(){


try { child(); }
catch(MyCustomException e){ } }
public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using
throw keyword"); } }

Q9) What is the use of throws keyword?

A9) If the function is not capable of handling the exception then it can ask the calling
method to handle it by simply putting the throws clause at the function declaration.

public void parent() {


try { child(); }
catch(MyCustomException e) { } }
public void child throws MyCustomException{
//put some logic so that the exception occurs
}

Q10) What are the possible combination to write try, catch finally block?

A10)
1 try {
//lines of code that may throw an exception }
catch(Exception e){
//lines of code to handle the exception thrown in try
block }
finally {
//the clean code which is executed always no matter the
exception occurs or not }
2 try{} finally{}
3 try {} catch(Exception e) {
//lines of code to handle the exception thrown in try
block }

The catch blocks must always follow the try block. If there are more than one catch
blocks they all must follow each other without any block in between. The finally
block must follow the catch block if one is present or if the catch block is absent the
finally block must follow the try block.
Q11) How to create a custom Exception?

A11) To create you own exception extend the Exception class or any of its subclasses.

class New1Exception extends Exception { } //this will


create Checked Exception

class NewException extends IOExcpetion { } //this will


create Checked exception

class NewException extends NullPonterExcpetion { } //this


will create UnChecked exception

Q12) When to make a custom checked Exception or unchecked Exception?

A12) Checked excepton forces to handle the exception using a try-catch block,
unchecked exception doesn't allow explicit handle of exception.

Q13) What is StackOverflowError?

A13) The StackOverFlowError is an Error Object thorwn by the Runtime System


when it Encounters that your application/code has ran out of the memory. It may
occur in case of recursive methods or a large amount of data is fetched from the
server and stored in some object. This error is generated by JVM.

Q14) Why did the designers decide to force a method to specify all uncaught
checked exceptions that can be thrown within its scope?

A14) Any Exception that can be thrown by a method is part of the method's public
programming interface. Those who call a method must know about the exceptions
that a method can throw so that they can decide what to do about them. These
exceptions are as much a part of that method's programming interface as its
parameters and return value.

Q15) Once the control switches to the catch block does it return back to the try
block to execute the balance code?

A15) No. Once the control jumps to the catch block it never returns to the try block
but it goes to finally block(if present).

Q16) Where is the clean up code like release of resources is put in try-catch-
finally block and why?

A16) 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.
Q17) Is it valid to have a try block without catch or finally?

A17) 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.

Q18) How do you get the descriptive information about the Exception occurred
during the program execution?

A18) 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.

Q19) Why is not considered as a good practice to write a single catch all handler
to catch all the exceptions?

A19) You can write a single catch block to handle all the exceptions thrown during
the program. 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 block.

Q20) What is exception matching?

A20) 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.
Q21) What happens if the handler for the most specific exceptions is placed
above the more general exceptions handler?

A21) 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) {//handles
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){
//handles FileNotFoundException only }

Q22) Does the order of the catch blocks matter if the Exceptions caught by them
are not subtype or supertype of each other?

A22) No. If the exceptions are siblings in the Exception class’s 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.

Q23) What happens if a method does not throw an checked Exception directly
but calls a method that does? What does 'Ducking' the exception mean?

A23) If a method does not throw an checked Exception directly but calls a method
that throws an exception then the calling method must handle the throw exception or
declare the exception in its throws clause. If the calling method does not handle and
declares the exception, the exceptions is passed to the next method in the method
stack. This is called as ducking the exception down the method stack.

e.g. The code below will not compile as the getCar() method has not declared the
CarNotFoundException which is thrown by the getColor () method.

void getCar() {
getColor(); }
void getColor() {
throw new CarNotFoundException(); }

//Fix for the above code is


void getCar() throws CarNotFoundException {
getColor(); }
void getColor() { throw new CarNotFoundException(); }
Q24) Is an empty catch block legal?

A24) Yes you can leave the catch block without writing any actual code to handle the
exception caught

Q25) Can a catch block throw the exception caught by itself?

A25) Yes. This is called rethrowing of the exception by catch block.

e.g. the catch block below catches the FileNotFound exception and rethrows it again.

void checkEx() throws FileNotFoundException {


try{
//code that may throw the FileNotFoundException }
catch(FileNotFound eFnf) {
throw FileNotFound(); } }

You might also like