Javainterview Questions
Javainterview Questions
Javainterview Questions
Example:
1 public class Addition{
2 public static void main(String[] args){
3 Addion add = new Addition();//Object creation
4}
5}
The above code creates the object for the Addition class.
Example:
1 Super class:
2 public class Manupulation(){
3}
4 Sub class:
5 public class Addition extends Manipulation(){
6}
Inheritance is applicable for public and protected members only. Private members can’t be
inherited.
get A(){
.........
For encapsulation, we need to make all the instance variables as private and create setter
and getter for those variables. Which in turn will force others to call the setters rather than
access the data directly.
Example:
1 Public class Manipulation(){ //Super class
2 public void add(){
3}
4}
5 public class Addition extends Manipulation(){ // Sub class
6 public void add(){
7}
8 public static void main(String args[]){
Example:
public class Manipulation{ //Super class
………………
………..
}
addition.add() method calls the add() method in the Sub class and not the parent class. So
it overrides the Super class method and is known as Method Overriding.
Q #14) What is meant by Overloading?
Ans: Method overloading happens for different classes or within the same class.
For method overloading, subclass method should satisfy the below conditions with
the Super class method (or) methods in the same class itself:
Same method name
Different argument type
May have different return types
Example:
public class Manipulation{ //Super class
………………
………..
addition.add();
Here the add() method having different parameters in the Addition class is overloaded in the
same class as well as with the super class.
Example:
1 Public abstract interface IManupulation{ //Interface declaration
2 Public abstract void add();//method declaration
3 public abstract void subtract();
4}
All the methods in the interface are internally public abstract void.
All the variables in the interface are internally public static final that is constants.
Classes can implement the interface and not extends.
The class which implements the interface should provide an implementation for all
the methods declared in the interface.
1 public class Manupulation implements IManupulation{ //Manupulation class uses
the interface
2 Public void add(){
3 ……………
4}
5 Public void subtract(){
6 …………….
7}
8}
Q #16) What is meant by Abstract class?
Ans: We can create the Abstract class by using “Abstract” keyword before the class name.
An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a
concrete class.
Abstract method:
The method which has only the declaration and not the implementation is called the
abstract method and it has the keyword called “abstract”. Declarations are the ends with a
semicolon.
Example:
1 public abstract class Manupulation{
2 public abstract void add();//Abstract method declaration
3 Public void subtract(){
4}
5}
An abstract class may have a Non- abstract method also.
The concrete Subclass which extends the Abstract class should provide the
implementation for abstract methods.
Q #17) Difference between Array and Array List.
Ans: The Difference between Array and Array List can be understood from the below
table:
Array
Array List
Size should be given at the time of array declaration. Size may not be required. It changes the size
dynamically.
String[] name = new String[2]
ArrayList name = new ArrayList
String Buffer:
Here string values are stored in a stack. If the values are changed then the new
value replaces the older value.
The string buffer is synchronized which is thread-safe.
Performance is slower than the String Builder.
Example:
String Buffer name =”book”;
Once the name value has been changed to “pen” then the “book” is erased in the stack.
String Builder:
This is same as String Buffer except for the String Builder which is not threaded safety that
is not synchronized. So obviously performance is fast.
Public members in Class A are visible to Class B (Same package) as well as Class C
(Different package).
Private:
Private members are visible in the same class only and not for the other classes in the
same package as well as classes in the outside packages.
Private members in class A is visible only in that class. It is invisible for class B as well as
class C.
So Class A members are visible to the Class B and invisible to the Class C.
Protected:
.
Protected is same as Default but if a class extends then it is visible even if it is outside the
package.
Class A members are visible to Class B because it is inside the package. For Class C it is
invisible but if Class C extends Class A then the members are visible to the Class C even if
it is outside the package.
Iterator is used to iterate the values Enumerator is used to iterate the values
Allows one null key and multiple null values Doesn’t allow anything that is null
HashMap HashTable
Inserted elements are in random order Maintains the elements in the sorted order
Q #25) What are all the Classes and Interfaces that are available in the collections?
Ans: Given below are the Classes and Interfaces that are available in Collections:
Interfaces:
Collection
List
Set
Map
Sorted Set
Sorted Map
Queue
Classes:
Lists:
Array List
Vector
Linked List
Sets:
Hash set
Linked Hash Set
Tree Set
Maps:
Hash Map
Hash Table
Tree Map
Linked Hashed Map
Queue:
Priority Queue
Q #26) What is meant by Ordered and Sorted in collections?
Ans:
Ordered:
It means the values that are stored in a collection is based on the values that are added to
the collection. So we can iterate the values from the collection in a specific order.
Sorted:
Sorting mechanism can be applied internally or externally so that the group of objects
sorted in a particular collection is based on properties of the objects.
names.add (“apple”);
names.add (“cherry”);
names.add (“kiwi”);
names.add (“banana”);
names.add (“cherry”);
System.out.println (names);
Output:
[Apple, cherry, kiwi, banana, cherry]
From the output, Array List maintains the insertion order and it accepts the duplicates. But
not sorted.
Vector:
It is same as Array List.
names.add (“cherry”);
names.add (“apple”);
names.add (“banana”);
names.add (“kiwi”);
names.add (“apple”);
System.out.println (“names”);
}
Output:
[cherry,apple,banana,kiwi,apple]
Vector also maintains the insertion order and accepts the duplicates.
Linked List:
Elements are doubly linked to one another.
Performance is slow than Array list.
Good choice for insertion and deletion.
In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
Example:
public class Fruit {
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
Output
[ banana,cherry,apple,kiwi,banana]
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
Output:
[banana, cherry, kiwi, apple]
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
Output:
[banana, cherry, apple, kiwi]
Maintains the insertion order in which they have been added to the Set. Duplicates are not
allowed.
Tree Set:
It is one of the two sorted collections.
Uses “Read-Black” tree structure and guarantees that the elements will be in an
ascending order.
We can construct a tree set with the constructor by using comparable (or)
comparator.
Example:
public class Fruits{
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in an ascending order. And duplicates are not allowed.
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
}
Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}
Hash Table:
Like vector key, methods of the class are synchronized.
Thread safety and therefore slows the performance.
Doesn’t allow anything that is null.
Example:
public class Fruit{
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
TreeMap:
Sorted Map.
Like Tree set, we can construct a sort order with the constructor.
Example:
public class Fruit{
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
Output:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}
It is sorted in ascending order based on the key. Duplicate keys are not allowed.
It includes:
Arithmetic Exception
ArrayIndexOutOfBounds Exception
Q #33) What are the different ways to handle exceptions?
Ans: Two different ways to handle exception are explained below:
#1) Using try/catch:
A risky code is surrounded by try block. If an exception occurs, then it is caught by the catch
block which is followed by the try block.
Example:
1 class Manipulation{
2 public static void main(String[] args){
3 add();
4}
5 Public void add(){
6 try{
7 addition();
8 }catch(Exception e){
9 e.printStacktrace();
10 }
11 }
12 }
#2) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.
Example:
1 class Manipulation{
2 public static void main(String[] args){
3 add();
4}
5 public void add() throws Exception{
6 addition();
7}
8}
Q #34) What are the Advantages of Exception handling?
Ans: Given below are the advantages:
The normal flow of the execution won’t be terminated if exception got handled
We can identify the problem by using catch declaration
Q #35) What are Exception handling keywords in Java?
Ans: Given below are the two Exception Handling Keywords:
try:
When a risky code is surrounded by a try block. An exception occurring in the try block is
caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any
one of the blocks is mandatory.
catch:
This is followed by try block. Exceptions are caught here.
finally:
This is followed either by try block (or) catch block. This block gets executed regardless of
an exception. So generally clean up codes are provided here.
Example:
1 public class Manipulation{
2 public static void main(String[] args){
3 add();
4}
5 public void add(){
6 addition();
7}
From the above example, the stack looks like as shown below:
If an exception occurred in the addition() method is not caught, then it moves to the
method add(). Then it is moved to the main() method and then it will stop the flow of
execution. It is called Exception Propagation.
Q #37) What is the final keyword in Java?
Ans:
Final variable:
Once a variable is declared as final, then the value of the variable could not be changed. It
is like a constant.
Example:
final int = 12;
Final method:
A final keyword in a method that couldn’t be overridden. If a method is marked as a final,
then it can’t be overridden by the subclass.
Final class:
If a class is declared as final, then the class couldn’t be subclassed. No class can extend
the final class.
Example:
1 Public class Addition extends Thread {
2 public void run () {
3}
4}
The disadvantage of using a thread class is that we cannot extend any other classes
because we have already extend the thread class. We can overload the run () method in
our class.
Example:
1 Public class Addition implements Runnable {
2 public void run () {
3}
4}
Q #40) Explain about join () method.
Ans: Join () method is used to join one thread with the end of the currently running thread.
Example:
1 public static void main (String[] args){
2 Thread t = new Thread ();
3 t.start ();
4 t.join ();
5}
From the above code, the main thread started the execution. When it reaches the
code t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between
the main thread and ‘thread t’.
Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task,
then only main thread started the execution.
It is a non-static method. Join () method has overloaded version. So we can mention the
time duration in join () method also “.s”.
Example:
1 public static void main (String[] args){
2 Thread t = new Thread ();
3 t.start ();
4}
5 public void run(){
6 Thread.yield();
7}
8}
Q #42) Explain about wait () method.
Ans: wait () method is used to make the thread to wait in the waiting pool. When a wait ()
method is executed during a thread execution then immediately the thread gives up the lock
on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given
amount of time.
Then the thread will wake up after notify () (or) notify all () method is called.
Wait() and the other above-mentioned methods do not give the lock on the object
immediately until the currently executing thread completes the synchronized code. It is
mostly used in synchronization.
Example:
1 public static void main (String[] args){
2 Thread t = new Thread ();
3 t.start ();
4 Synchronized (t) {
5 Wait();
6}
7}
Q #43) Difference between notify() method and notifyAll() method in Java.
Ans: Given below are few differences between notify() method and notifyAll() method
notify() notifyAll()
This method is used to send a signal to wake up a This method sends the signal to wake up all the
single thread in the waiting pool. threads in a waiting spool.
Q #44) How to stop a thread in java? Explain about sleep () method in a thread?
Ans: We can stop a thread by using the following thread methods.
Sleeping
Waiting
Blocked
Sleep:
Sleep () method is used to sleep the currently executing thread for the given amount of
time. Once the thread is wake up it can move to the runnable state. So sleep () method is
used to delay the execution for some period.
It is a static method.
Example:
Thread. Sleep (2000)
So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted
exception, hence we need to surround the block with try/catch.
Once the execution reaches, t.start () line then a new thread is created and the new stack
for the thread is also created. Now JVM switches to the new thread and the main thread are
back to the runnable state.
The two stacks look as shown below.
Now, the user thread executed the code inside the run() method.
Once the run() method has completed, then JVM switches back to the main thread and the
User thread has completed the task and the stack was disappeared.
JVM switches between each thread until both the threads are completed. This is called
Multi-threading.
New:
In New state, Thread instance has been created but start () method is not yet invoked. Now
the thread is not considered alive.
Runnable:
The Thread is in runnable state after invocation of the start () method, but before the run ()
method is invoked. But a thread can also return to the runnable state from waiting/sleeping.
In this state the thread is considered alive.
Running:
The thread is in running state after it calls the run () method. Now the thread begins the
execution.
Non-Runnable(Blocked):
The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return
to runnable state after some time.
Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can
access a synchronized method only if the thread can get the key to the objects lock.
Example:
public class ExampleThread implements Runnable{
t.start ();
synchronized(object){
Q #53) Which methods are used during Serialization and Deserialization process?
Ans: ObjectOutputStream and ObjectInputStream classes are higher level java.io. package.
We will use them with lower level classes FileOutputStream and FileInputStream.
ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a
file.
ObjectInputStream.readObject —> Reads the file and deserializes the object.
To be serialized, an object must implement the serializable interface. If superclass
implements Serializable, then the subclass will automatically be serializable.
Serialization is the process which is used to Deserialization is the opposite process of serialization
convert the objects into byte stream where we can get the objects back from the byte stream.