Tuesday, 13 August 2019

Core Java Interview Questions and Answers


What are static blocks and static initalizers in Java ?

Static blocks or static initializers are used to initialize static fields in java.
we declare static blocks when we want to initialize static fields in our class.
Static blocks gets executed exactly once when the class is loaded.
Static blocks are executed even before the constructors are executed.


How to call one constructor from the other constructor ?

With in the same class if we want to call one constructor from other we use this() method.
Based on the number of parameters we pass appropriate this() method is called.
Restrictions for using this method :
a) this must be the first statement in the constructor
b)we cannot use two this() methods in the constructor


What is method overriding in java ?

If we have methods with same signature (same name, same signature, same return type) in super class
and subclass then we say subclass method is overridden by super class.

When to use overriding in java - If we want same method with different behavior in super class and subclass then we go for overriding.
When we call overridden method with subclass reference subclass method is called hiding the super class method.


What is super keyword in java ?

Variables and methods of super class can be overridden in subclass . In case of overriding , a subclass
object call its own variables and methods. Subclass cannot access the variables and methods of
super class because the overridden variables or methods hides the methods and variables of super class. But still java provides a way to access super class members even if its members are overridden. Super is used to access super class variables, methods, constructors.
Super can be used in two forms :
a) First form is for calling super class constructor.
b) Second one is to call super class variables,methods.
Super if present must be the first statement.


What is the difference between method overloading and method overriding in java ?

Method Overloading Method Overriding
1) Method Overloading occurs with in the same class
    Method Overriding occurs between two classes superclass and subclass
2) Since it involves with only one class inheritance is not involved.
    Since method overriding occurs between superclass and subclass inheritance is involved.
3) In overloading return type need not be the same 
    In overriding return type must be same.
4) Parameters must be different when we do overloading
    Parameters must be same.
5) Static polymorphism can be achieved using method overloading
    Dynamic polymorphism can be achieved using method overriding.
6) In overloading one method can’t hide the another.
    In overriding subclass method hides that of the superclass method.



What is the difference between abstract class and interface ?

1) Interface contains only abstract methods
1) Abstract class can contain abstract methods,concrete methods or both

2) Access Specifiers for methods in interface must be public
2) Except private we can have any access specifier for methods in abstract class.

3) Variables defined must be public , static , final
3) Except private variables can have any access specifiers

4) Multiple Inheritance in java is implemented using interface
4)We cannot achieve multiple inheritance using abstract class.

5) To implement an interface we use implements keyword
5)To implement an abstract class we use extends keyword.



Why java is platform independent?

The most unique feature of java is platform independent. In any programming language source code is compiled in to executable code . This cannot be run across all platforms. When javac compiles a java program it generates an executable file called .class file.
                           class file contains byte codes. Byte codes are interpreted only by JVM’s . Since these JVM’s are made available across all platforms by Sun Microsystems, we can execute this byte code in any platform. Byte code generated in windows environment can also be executed in linux environment. This makes java platform independent.



What is method overloading in java ?

A class having two or more methods with same name but with different arguments then we say that those methods are overloaded.
Static polymorphism is achieved in java using method overloading.
Method overloading is used when we want the methods to perform similar tasks but with different inputs or values. When an overloaded method is invoked java first checks the method name, and the number of arguments ,type of arguments; based on this compiler executes this method.
Compiler decides which method to call at compile time. By using overloading static polymorphism or static binding can be achieved in java.
Note : Return type is not part of method signature. we may have methods with different return types but return type alone is not sufficient to call a method in java.



What is JIT (Just In Time) compiler ?

JIT compiler compiles byte code in to executable code .
JIT a part of JVM .JIT cannot convert complete java program in to executable code it converts as and
when it is needed during execution.



What is bytecode in java ?

When a javac compiler compiler compiles a class it generates .class file. This .class file contains set of instructions called byte code. Byte code is a machine independent language and contains set of
instructions which are to be executed only by JVM. JVM can understand this byte codes.



What is the difference between this() and super() in java ?

this() is used to access one constructor from another with in the same class while super() is used to
access super class constructor from another class (termed as child class).
Either this() or super() exists it must be the first statement in the constructor.



What is a class ?

Classes are fundamental or basic unit in Object Oriented Programming .A class is kind of blueprint or
template for objects. Class defines variables, methods. A class tells what type of objects we are creating.
For example take Department class tells us we can create department type objects. We can create any
number of department objects.
All programming constructs in java reside in class. When JVM starts running it first looks for the class when we compile. Every Java application must have at least one class and one main method.
Class starts with class keyword. A class definition must be saved in class file that has same as class name.
File name must end with .java extension.

public class FirstClass
{
  public static void main(String[] args)
  {
     System.out.println(“My First class”);
  }
}

If we see the above class when we compile JVM loads the FirstClass and generates a .class
file(FirstClass.class). When we run the program we are running the class and then executes the main
method.



14) What is an object ?

An Object is instance of class. A class defines type of object. Each object belongs to some class.Every object contains state and behavior. State is determined by value of attributes and behavior is called method. Objects are also called as an instance.

To instantiate the class we declare with the class type.

public classFirstClass
{
  public static voidmain(String[] args)
   {
      FirstClass f=new FirstClass();
      System.out.println(“My First class”);
   }
}

To instantiate the FirstClass we use this statement

FirstClass f=new FirstClass();

f is used to refer FirstClass object.



What is difference between length and length() method in java ?

length() : In String class we have length() method which is used to return the number of characters in
string.
Ex : String str = “Hello World”;
        System.out.println(str.length());
        str.length()  will return 11 characters including space.

length : we have length instance variable in arrays which will return the number of values or objects in array.
For example :
         String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”};
         Will return 6 since the number of values in days array is 6.


What is ASCII Code?

ASCII stands for American Standard code for Information Interchange.
ASCII character range is 0 to 255.
We can’t add more characters to the ASCII Character set.
ASCII character set supports only English. That



What is Unicode ?

Unicode is a character set developed by Unicode Consortium. To support all languages in the world Java supports Unicode values. Unicode characters were represented by 16 bits and its character range is 0-65535
Java uses ASCII code for all input elements except for Strings,identifiers, and comments. If we want to use bhojpuri we can use bhojpuri characters for identifiers.We can enter comments in bhojpuri.



What is the difference between Character Constant and String Constant in java ?

Character constant is enclosed in single quotes. String constants are enclosed in double quotes. Character constants are single digit or character. String Constants are collection of characters.
Ex :’2’, ‘A’
Ex : “Hello World”



What is the difference between ‘>>’ and ‘>>>’ operators in java?

>> is a right shift operator shifts all of the bits in a value to the right to a specified number of times.
int a =15;
a= a >> 3;
The above line of code moves 15 three characters right.

>>> is an unsigned shift operator used to shift right. The places which were vacated by shift are filled
with zeroes.



What is ‘IS-A ‘ relationship in java? (also known as inheritance)

‘is a’ relationship is also known as inheritance. We can implement ‘is a’ relationship or inheritance in java using extends keyword. The advantage or inheritance or is a relationship is re-usability of code instead of duplicating the code.
Ex : Motor cycle is a vehicle
Car is a vehicle Both car and motorcycle extends vehicle.



What is ‘HAS A’’ relationship in java? (also known for composition and aggregation)

‘Has a ‘ relationship is also known as “composition or Aggregation”. As in inheritance we have ‘extends’ keyword we don’t have any keyword to implement ‘Has a’ relationship in java. The main advantage of ‘Has-A‘ relationship in java code re-usability. Has a relationship we use new keyword.




Explain about instanceof operator in java?

Instanceof operator is used to test the object is of which type.
Syntax : <reference expression> instanceof <destination type>

Instanceof returns true if reference expression is subtype of destination type.
Instanceof returns false if reference expression is null.

Example :

public classInstanceOfExample
{
   public static voidmain(String[] args)
    {
       Integer a = newInteger(5);
       if (a instanceof java.lang.Integer)
       {
          System.out.println(true);
       } else {
          System.out.println(false);
       }
  }
}

Since a is integer object it returns true.
There will be a compile time check whether reference expression is sub-type of destination type.
If it is not a sub-type then compile time error will be shown as Incompatible types



What does null mean in java?

When a reference variable doesn’t point to any value it is assigned null.
Example : Employee employee;
In the above example employee object is not instantiate so it is pointed no where



Can we have multiple classes in single file ?

Yes we can have multiple classes in single file but it people rarely do that and not recommended.
We can have multiple classes in File but only one class can be made public. If we try to make two classes in File
public we get following compilation error.
“The public type must be defined in its own file”.



What all access modifiers are allowed for top class ?
For top level class only two access modifiers are allowed.
public and default.
If a class is declared as public it is visible everywhere.
If a class is declared default it is visible only in same package.

If we try to give private and protected as access modifier to class we get the below compilation error.
Illegal Modifier for the class only public,abstract and final are permitted.



What is the difference between access specifiers and access modifiers in java?

In C++ we have access specifiers as public,private,protected and default and
access modifiers as static,final.

But there is no such division of access specifiers and access modifiers in java.
In Java we have access modifiers and non access modifiers.
Access Modifiers : public, private, protected, default
Non Access Modifiers : abstract, final, stricfp.



Explain what access modifiers can be used for methods?

We can use all access modifiers public, private,protected and default for methods.


What is final access modifier in java?

final access modifier can be used for class, method and variables.

The main advantage of final access modifier is security no one can modify our classes, variables and methods.

The main disadvantage of final access modifier is we cannot implement oops concepts in java. Ex : Inheritance, polymorphism.

final class : A final class cannot be extended or subclassed. We are preventing inheritance by marking a class as final. But we can still access the methods of this class by composition.
Ex: String class

final methods: Method overriding is one of the important features in java. But there are situations where we may not want to use this feature. Then we declared method as final which will print overriding. To allow a method from being overridden we use final access modifier for methods.

final variables : If a variable is declared as final ,it behaves like a constant . We cannot modify the value of final variable. Any attempt to modify the final variable results in compilation error. The error is as follows “final variable cannot be assigned.”


Explain about abstract classes in java?

Sometimes we may come across a situation where we cannot provide implementation to all the methods in a class. We want to leave the implementation to a class that extends it. In such case we declare a class as abstract.To make a class abstract we use key word abstract. Any class that contains one or more abstract methods is declared as abstract. If we don’t declare class as abstract which contains abstract methods we get compile time error. We get the following error.
“The type <class-name> must be an abstract class to define abstract methods.”

Signature ; abstract class <class-name>
{
}

For example if we take a vehicle class we cannot provide implementation to it because there may be two wheeler , four wheeler's etc. At that moment we make vehicle class abstract. All the common features of vehicles are declared as abstract methods in vehicle class. Any class which extends vehicle will provide its method implementation. It’s the responsibility of subclass to provide implementation.

The important features of abstract classes are :
1) Abstract classes cannot be instantiated.
2) An abstract classes contains abstract methods, concrete methods or both.
3) Any class which extends abstract class must override all methods of abstract class.
4) An abstract class can contain either 0 or more abstract methods.
5) we cannot instantiate abstract classes we can create object references . Through superclass
references we can point to subclass.


Can we create constructor in abstract class ?

We can create constructor in abstract class , it doesn't give any compilation error. But when we cannot
instantiate class there is no use in creating a constructor for abstract class.



What are abstract methods in java?

An abstract method is the method which does’nt have any body. Abstract method is declared with
keyword abstract and semicolon in place of method body.
Signature : public abstract void <method name>();
Ex : public abstract void getDetails();
It is the responsibility of subclass to provide implementation to abstract method defined in abstract class.




What is an exception in java?

In java, Exception is an object. Exceptions are created when an abnormal situations are arised in our
program. Exceptions can be created by JVM or by our application code. All Exception classes are defined in java.lang. In other-words we can say Exception as run time error.

Some situations where exceptions arise in java :
1) Accesing an element that does not exist in array.(ArrayIndexOutOfBoundException)
2) Invalid conversion of number to string and string to number.(NumberFormatException)
3) Invalid casting of class(Class cast Exception)
4) Trying to create object for interface or abstract class(Instantiation Exception)



What is Exception handling in java?

Exception handling is a mechanism what to do when some abnormal situation arises in program. When an exception is raised in program it leads to termination of program when it is not handled properly. The significance of exception handling comes here in order not to terminate a program abruptly and to continue with the rest of program normally. This can be done with help of Exception handling.


What is an error in Java?

Error is the subclass of Throwable class in java. When errors are caused by our program we call that as Exception, but some times exceptions are caused due to some environment issues such as running out of memory. In such cases we can’t handle the exceptions. Exceptions which cannot be recovered are called as errors in java. Ex : Out of memory issues.



What are advantages of Exception handling in java?

1) Separating normal code from exception handling code to avoid abnormal termination of program.

2) Categorizing in to different types of Exceptions so that rather than handling all exceptions with
Exception root class we can handle with specific exceptions. It is recommended to handle exceptions with specific Exception instead of handling with Exception root class.

3) Call stack mechanism : If a method throws an exception and it is not handled immediately, then that exception is propagated or thrown to the caller of that method. This propagation continues till it finds an appropriate exception handler ,if it finds handler it would be handled otherwise program terminates abruptly.



How many ways we can do exception handling in java?

We can handle exceptions in either of the two ways :
1) By specifying try catch block where we can catch the exception.
2) Declaring a method with throws clause .



Explain try and catch keywords in java?

In try block we define all exception causing code. In java try and catch forms a unit. A catch block catches the exception thrown by preceding try block. Catch block cannot catch an exception thrown by another try block. If there is no exception causing code in our program or exception is not raised in our code jvm ignores the try catch block.

Syntax :
try
{
  // causing code
}
Catch(Exception e)
{
   // catching code
}


Can we have try block without catch block?

Each try block requires at-least one catch block or finally block. A try block without catch or finally will result in compiler error. We can skip either of catch or finally block but not both.


Can we have multiple catch block for a try block?

In some cases our code may throw more than one exception. In such case we can specify two or more
catch clauses, each catch handling different type of exception. When an exception is thrown jvm checks each catch statement in order and the first one which matches the type of exception is execution and remaining catch blocks are skipped.
Try with multiple catch blocks is highly recommended in java.
If try with multiple catch blocks are present the order of catch blocks is very important and the order
should be from child to parent.


Explain importance of finally block in java?

Finally block is used for cleaning up of resources such as closing connections, sockets etc. if try block executes with no exceptions then finally is called after try block without executing catch block. If there is exception thrown in try block finally block executes immediately after catch block.
If an exception is thrown,finally block will be executed even if the no catch block handles the exception.


Can we have any code between try and catch blocks?

We shouldn’t declare any code between try and catch block. Catch block should immediately start after try block.

try{
//code
}
System.out.println(“one line of code”); // illegal
catch(Exception e){
//
}



Can we have any code between try and finally blocks?

We shouldn’t declare any code between try and finally block. finally block should immediately start after catch block.If there is no catch block it should immediately start after try block.

try{
//code
}
System.out.println(“one line of code”); // illegal
finally{
//
}


Can we catch more than one exception in single catch block?
From Java 7, we can catch more than one exception with single catch block. This type of handling reduces the code duplication.
Note : When we catch more than one exception in single catch block , catch parameter is implicitly final. We cannot assign any value to catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
{
   // handled code
}
In the above example e is final we cannot assign any value or modify e in catch statement.



What are checked Exceptions?

1) All the subclasses of Throwable class except error, Runtime Exception and its subclasses are checked exceptions.
2) Checked exception should be thrown with keyword throws or should be provided try catch block, else the program would not compile. We do get compilation error.
Examples :
1) IOException,
2) SQlException,
3) FileNotFoundException,
4) InvocationTargetException,
5) CloneNotSupportedException
6) ClassNotFoundException
7) InstantiationException



What are unchecked exceptions in java?

All subclasses of RuntimeException are called unchecked exceptions. These are unchecked exceptions because compiler does not checks if a method handles or throws exceptions.
Program compiles even if we do not catch the exception or throws the exception.
If an exception occurs in the program,program terminates . It is difficult to handle these exceptions
because there may be many places causing exceptions.
Examples :
1) Arithmetic Exception
2) ArrayIndexOutOfBoundsException
3) ClassCastException
4) IndexOutOfBoundException
5) NullPointerException
6) NumberFormatException
7) StringIndexOutOfBounds
8) UnsupportedOperationException



What is default Exception handling in java?

When JVM detects exception causing code, it constructs a new exception handling object by including the following information.
1) Name of Exception
2) Description about the Exception
3) Location of Exception.

After creation of object by JVM it checks whether there is exception handling code or not. If there is
exception handling code then exception handles and continues the program. If there is no exception
handling code JVM give the responsibility of exception handling to default handler and terminates
abruptly. Default Exception handler displays description of exception,prints the StackTrace and location of exception and terminates the program.
Note : The main disadvantage of this default exception handling is program terminates abruptly.



Explain throw keyword in java?

Generally JVM throws the exception and we handle the exceptions by using try catch block. But there are situations where we have to throw userdefined exceptions or runtime exceptions. In such case we use throw keyword to throw exception explicitly.
Syntax : throw throwableInstance;

Throwable instance must be of type throwable or any of its subclasses.
After the throw statement execution stops and subsequent statements are not executed. Once exception object is thrown JVM checks is there any catch block to handle the exception. If not then the next catch statement till it finds the appropriate handler. If appropriate handler is not found ,then default exception handler halts the program and prints the description and location of exception.
In general we use throw keyword for throwing userdefined or customized exception.



Can we write any code after throw statement?

After throw statement jvm stop execution and subsequent statements are not executed. If we try to write any statement after throw we do get compile time error saying unreachable code.


Explain importance of throws keyword in java?

Throws statement is used at the end of method signature to indicate that an exception of a given type
may be thrown from the method.
The main purpose of throws keyword is to delegate responsibility of exception handling to the caller
methods, in the case of checked exception.
In the case of unchecked exceptions, it is not required to use throws keyword.
We can use throws keyword only for throwable types otherwise compile time error saying incompatible types.
An error is unchecked , it is not required to handle by try catch or by throws.
Syntax :
Class Test
{
    Public static void main(String args[]) throws IE
    {
        // lines of code
    }
}
Note : The method should throw only checked exceptions and subclasses of checked exceptions.
It is not recommended to specify exception super classes in the throws class when the actual exceptions thrown in the method are instances of their subclass.


Explain the importance of finally over return statement?

finally block is more important than return statement when both are present in a program. For example if there is any return statement present inside try or catch block , and finally block is also present first finally statement will be executed and then return statement will be considered.


Explain a situation where finally block will not be executed?

Finally block will not be executed whenever jvm shutdowns. If we use system.exit(0) in try statement
finally block if present will not be executed.


Can we use catch statement for checked exceptions?

If there is no chance of raising an exception in our code then we can’t declare catch block for handling checked exceptions .This raises compile time error if we try to handle checked exceptions when there is no possibility of causing exception.


What are user defined exceptions?

To create customized error messages we use userdefined exceptions. We can create user defined
exceptions as checked or unchecked exceptions.
We can create user defined exceptions that extend Exception class or subclasses of checked exceptions so that userdefined exception becomes checked.
Userdefined exceptions can extend RuntimeException to create userdefined unchecked exceptions.
Note : It is recommended to keep our customized exception class as unchecked,i.e we need to extend
Runtime Exception class but not Excpetion class.


Can we rethrow the same exception from catch handler?

Yes we can rethrow the same exception from our catch handler. If we want to rethrow checked exception from a catch block we need to declare that exception.

Can we nested try statements in java?

Yes try statements can be nested. We can declare try statements inside the block of another try
statement.


Explain the importance of throwable class and its methods?

Throwable class is the root class for Exceptions. All exceptions are derived from this throwable class. The two main subclasses of Throwable are Exception and Error. The three methods defined in throwable class
are :
1) void printStackTrace() :
This prints the exception information in the following format :
Name of the exception, description followed by stack trace.
2) getMessage()
This method prints only the description of Exception.
3) toString():
It prints the name and description of Exception.



Explain when ClassNotFoundException will be raised ?

When JVM tries to load a class by its string name, and couldn’t able to find the class
classNotFoundException will be thrown. An example for this exception is when class name is misspelled and when we try to load the class by string name hence class cannot be found which raises
ClassNotFoundException.



Explain when NoClassDefFoundError will be raised ?

This error is thrown when JVM tries to load the class but no definition for that class is found
NoClassDefFoundError will occur. The class may exist at compile time but unable to find at runtime. This might be due to misspelled classname at command line, or classpath is not specified properly , or the class file with byte code is no longer available.



What is process ?

A process is a program in execution.
Every process have their own memory space.
Process are heavy weight and requires their own address space.
One or more threads make a process.



What is thread in java?

Thread is separate path of execution in program.
Threads are
1) Light weight
2) They share the same address space.
3) creating thread is simple when compared to process because creating thread requires less resources
4) when compared to process, Threads exists in process. A process have atleast one thread.


Difference between process and thread?

1) Program in execution. Separate path of execution in program.
    One or more threads is called as process.
2) Processes are heavy weight Threads are light weight.
3) Processes require separate address space. Threads share same address space.
4) Interprocess communication is expensive.
    Interthread communication is less expensive compared to processes.
5) Context switching from one process to another is costly.
    Context switching between threads is low cost.


What is multitasking ?

Multitasking means performing more than one activity at a time on the computer. Example Using
spreadsheet and using calculator at same time.

Different types of multitasking:

There are two different types of multitasking :

1) Process based multitasking
2) Thread based multitasking

Process based multitasking : It allows to run two or more programs concurrently. In process
based multitasking a process is the smallest part of code .
Example : Running Ms word and Ms powerpoint at a time.

Thread based multitasking : It allows to run parts of a program to run concurrently.
Example : Formatting the text and printing word document at same time .
Java supports thread based multitasking and provides built in support for multithreading.



What are the benefits of multithreaded programming?

Multithreading enables to use idle time of cpu to another thread which results in faster execution of
program. In single threaded environment each task has to be completed before proceeding to next task making cpu idle.



What are the different Java API that supports threads?

java.lang.Thread : This is one of the way to create a thread. By extending Thread class and overriding
run() we can create thread in java.

java.lang.Runnable : Runnable is an interface in java. By implementing runnable interface and overriding run() we can create thread in java.

java.lang.Object : Object class is the super class for all the classes in java. In object class we have three methods wait(), notify(), notifyAll() that supports threads.

java.util.concurrent : This package has classes and interfaces that supports concurrent programming.
Ex : Executor interface, Future task class etc.



Explain about main thread in java?

Main thread is the first thread that starts immediately after a program is started.

Main thread is important because :
1) All the child threads spawn from main thread.
2) Main method is the last thread to finish execution.

When JVM calls main method() it starts a new thread. Main() method is temporarily stopped while the new thread starts running.



In how many ways we can create threads in java?

We can create threads in java by any of the two ways :
1) By extending Thread class
2) By Implementing Runnable interface.



Explain creating threads by implementing Runnable class?

This is first and foremost way to create threads by implementing runnable interface and implementing run() method we can create new thread.

Method signature : public void run()

Run is the starting point for execution for another thread within our program.

Example :
public class MyClass implements Runnable
{
   @Override
    public void run()
    {
        // T
    }
}



Explain creating threads by extending Thread class ?

We can create a thread by extending Thread class. The class which extends Thread class must override the run() method.
Example :
public class MyClass extends Thread
{
  @Override
  public void run()
  {
   // Starting point of Execution
  }
}




Explain the importance of thread scheduler in java?

Thread scheduler is part of JVM use to determine which thread to run at this moment when there are
multiple threads. Only threads in runnable state are chosen by scheduler.
Thread scheduler first allocates the processor time to the higher priority threads. To allocate
microprocessor time in between the threads of the same priority, thread scheduler follows round robin
fashion.


Explain the life cycle of thread?

A thread can be in any of the five states :

1) New : When the instance of thread is created it will be in New state.
Ex : Thread t= new Thread();
In the above example t is in new state. The thread is created but not in active state to make it active we need to call start() method on it.

2) Runnable state : A thread can be in the runnable state in either of the following two ways :
a) When the start method is invoked or
b) A thread can also be in runnable state after coming back from blocked or sleeping or waiting state.

3) Running state : If thread scheduler allocates cpu time, then the thread will be in running state.

4) Waited /Blocking/Sleeping state:
In this state the thread can be made temporarily inactive for a short period of time. A thread can be in
the above state in any of the following ways:
    a) The thread waits to acquire lock of an object.
    b) The thread waits for another thread to complete.
    c) The thread waits for notification of other thread.

5) Dead State : A thread is in dead state when thread’s run method execution is complete. It dies
automatically when thread’s run method execution is completed and the thread object will be garbage
collected.



Can we restart a dead thread in java?

If we try to restart a dead thread by using start method we will get run time exception since the thread is not alive.


Can one thread block the other thread?

No one thread cannot block the other thread in java. It can block the current thread that is running.


Can we restart a thread already started in java?

A thread can be started in java using start() method in java. If we call start method second time once it is started it will cause RunTimeException(IllegalThreadStateException). A runnable thread cannot be restarted.


What happens if we don’t override run method ?

If we don’t override run method .Then default implementation of Thread class run() method will be
executed and hence the thread will never be in runnable state.


Can we overload run() method in java?

We can overload run method but Thread class start method will always cal run method with no
arguments. But the overloaded method will not be called by start method we have to explicitly call this start() method.


What is a lock or purpose of locks in java?

Lock also called monitor is used to prevent access to a shared resource by multiple threads.
A lock is associated to shared resource. Whenever a thread wants to access a shared resource if must first acquire a lock . If already a lock has been acquired by other it can’t access that shared resource. At this moment the thread has to wait until another thread releases the lock on shared resource. To lock an object we use synchronization in java.
A lock protects section of code allowing only one thread to execute at at a time.


In how many ways we can do synchronization in java?

There are two ways to do synchronization in java:
1) Synchronized methods
2) Synchronized blocks
To do synchronization we use synchronize keyword.



What are synchronized methods ?

If we want a method of object to be accessed by single thread at a time we declare that method with
synchronized keyword.
Signature : public synchronized void methodName(){}
To execute synchronized method first lock has to be acquired on that object. Once synchronized method is called lock will be automatically acquired on that method when no other thread has lock on that method. once lock has been acquired then synchronized method gets executed. Once synchronized method execution completes automatically lock will be released. The prerequisite to execute a synchronized method is to acquire lock before method execution. If there is a lock already acquired by any other thread it waits till the other thread completes.



When do we use synchronized methods in java?

If multiple threads tries to access a method where method can manipulate the state of object , in such
scenario we can declare a method as synchronized.



When a thread is executing synchronized methods , then is it possible to execute other
synchronized methods simultaneously by other threads?

No it is not possible to execute synchronized methods by other threads when a thread is inside a
synchronized method.



When a thread is executing a synchronized method , then is it possible for the same
thread to access other synchronized methods of an object ?

Yes it is possible for thread executing a synchronized method to execute another synchronized method of an object.
public synchronized void methodName()
{
   // piece of code
}

To execute synchronized method first lock has to be acquired on that object. Once synchronized method is called lock will be automatically acquired on that method when no other thread has lock on that method. once lock has been acquired then synchronized method gets executed. Once synchronized method execution completes automatically lock will be released. The prerequisite to execute a synchronized method is to acquire lock before method execution. If there is a lock already acquired by any other thread it waits till the other thread completes.


What are synchronized blocks in java?

Synchronizing few lines of code rather than complete method with the help of synchronized keyword are called synchronized blocks.
Signature :    Synchronized (object reference){// code}


When do we use synchronized blocks and advantages of using synchronized blocks?

If very few lines of code requires synchronization then it is recommended to use synchronized blocks. The main advantage of synchronized blocks over synchronized methods is it reduces the waiting time of threads and improves performance of the system.


What is class level lock ?

Acquiring lock on the class instance rather than object of the class is called class level lock. The difference between class level lock and object level lock is in class level lock lock is acquired on class .class instance and in object level lock ,lock is acquired on object of class.


Can we synchronize static methods in java?

Every class in java has a unique lock associated with it. If a thread wants to execute static synchronize method it need to acquire first class level lock. When a thread was executing static synchronized method no other thread can execute static synchronized method of class since lock is acquired on class.
But it can execute the following methods simultaneously :
1) Normal static methods
2) Normal instance methods
3) synchronize instance methods

Signature :   synchronized(Classname.class){}



Can we use synchronized block for primitives?

Synchronized blocks are applicable only for objects if we try to use synchronized blocks for primitives we get compile time error.


What are thread priorities and importance of thread priorities in java?

When there are several threads in waiting, thread priorities determine which thread to run. In java
programming language every thread has a priority. A thread inherits priority of its parent thread. By
default thread has normal priority of 5. Thread scheduler uses thread priorities to decide when each
thread is allowed to run. Thread scheduler runs higher priority threads first.



Explain different types of thread priorities ?

Every thread in java has priorities in between 1 to 10. By default priority is 5
(Thread.NORM_PRIORITY). The maximum priority would be 10 and minimum would be 1.
Thread class defines the following constants(static final variables) to define properties.
Thread. MIN_PRIORITY = 1;
Thread.NORM_PRIORITY=5;
Thread. MAX_PRIORITY=10;



How to change the priority of thread or how to set priority of thread?

Thread class has a set method to set the priority of thread and get method to get the priority of the
thread.
Signature : final void setPriority(int value);

The setPriority() method is a request to jvm to set the priority. JVM may or may not oblige the request. We can get the priority of current thread by using getPriority() method of Thread class.
final int getPriority()
{
   // lines of code
}



If two threads have same priority which thread will be executed first ?

We are not guaranteed which thread will be executed first when there are threads with equal priorities in the pool. It depends on thread scheduler to which thread to execute. The scheduler can do any of the following things :
1) It can pick any thread from the pool and run it till it completes.
2) It can give equal opportunity for all the threads by time slicing.


What all methods are used to prevent thread execution ?

There are three methods in Thread class which prevents execution of thread.
1) yield()
2) join()
3) sleep()


Explain yield() method in thread class ?

Yield() method makes the current running thread to move in to runnable state from running state giving chance to remaining threads of equal priority which are in waiting state. yield() makes current thread to sleep for a specified amount of time.There is no guarantee that moving a current running thread from runnable to running state. It all depends on thread scheduler it doesn’t gurantee anything.

Calling yield() method on thread does not have any affect if object has a lock. The thread does’nt lose
any lock if it has acquired a lock earlier.

Signature :

public static native void yield()
{
    // lines of code
}


Is it possible for yielded thread to get chance for its execution again ?

Yield() causes current thread to sleep for specified amount of time giving opportunity for other threads of equal priority to execute. Thread scheduler decides whether it get chance for execution again or not. It all depends on mercy of thread scheduler.


Explain the importance of join() method in thread class?

A thread can invoke the join() method on other thread to wait for other thread to complete its
execution. Assume we have two threads, t1 and t2 threads . A running thread t1 invokes join() on
thread t2 then t1 thread will wait in to waiting state until t2 completes. Once t2 completes the execution, t1 will continue.
join() method throws Interrupted Exception so when ever we use join() method we should handle
Interrrupted Exception by throws or by using try catch block.

Signature :

public final void join() throws InterruptedException
{
    // lines of code
}

public final synchronized void join(long millis) throws InterruptedException
{
   // lines of code
}

public final synchronized void join(long millis, int nanos) throws InterruptedException
{
    // lines of code
}


Explain purpose of sleep() method in java?

sleep() method causes current running thread to sleep for specified amount of time . sleep() method is
the minimum amount of the time the current thread sleeps but not the exact amount of time.

Signature :
public static native void sleep(long millis) throws InterruptedException
{
    // pieces of code
}

public static void sleep(long millis, int nanos) throws InterruptedException
{
    // lines of code
}



Assume a thread has lock on it, calling sleep() method on that thread will release the lock?

Calling sleep() method on thread which has lock doesn't affect. Lock will not be released though the
thread sleeps for a specified amount of time.


Can sleep() method causes another thread to sleep?

 No sleep() method causes current thread to sleep not any other thread.


Explain about interrupt() method of thread class ?

Thread class interrupt() method is used to interrupt current thread or another thread. It doesnot mean
the current thread to stop immediately, it is polite way of telling or requesting to continue your present work. That is the reason we may not see the impact of interrupt call immediately.
Initially thread has a boolean property(interrupted status) false. So when we call interrupt() method
status would set to true. This causes the current thread to continue its work and does not have impact
immediately.
If a thread is in sleeping or waiting status (i.e thread has executed wait () or sleep() method) thread gets interrupted it stops what it is doing and throws an interrupted exception. This is reason we need to handle interrupted exception with throws or try/ catch block.



Explain about inter thread communication and how it takes place in java?

Usually threads are created to perform different unrelated tasks but there may be situations where they may perform related tasks. Interthread communication in java is done with the help of following three methods :
1) wait()
2) notify()
3) notifyAll()



Explain wait(), notify() and notifyAll() methods of object class ?

wait() : wait() method() makes the thread current thread sleeps and releases the lock until some other
             thread acquires the lock and calls notify().

notify() :notify() method wakes up the thread that called wait on the same object.

notfiyAll() :notifyAll() method wakes up all the threads that are called wait() on the same object.
The highest priority threads will run first.

All the above three methods are in object class and are called only in synchronized context.
All the above three methods must handle InterruptedException by using throws clause or by using try
catch clause.



Explain why wait() , notify() and notifyAll() methods are in Object class rather than in thread class?

First to know why they are in object class we should know what wait(), notify(), notifyAll() methods do. wait() , notify(), notifyAll() methods are object level methods they are called on same object.wait(), notify(), notifyAll() are called on an shared object so to they are kept in object class rather than thread class.




Explain IllegalMonitorStateException and when it will be thrown?

IllegalMonitorStateException is thrown when wait(), notify() and notifyAll() are called in non synchronized context. Wait(), notify(),notifyAll() must always be called in synchronized context other wise we get this run time exception.



When wait(), notify(), notifyAll() methods are called does it releases the lock or holds
the acquired lock?

wait(), notify(), notifyAll() methods are always called in synchronized context. When these methods are called in synchronized context. So when they enter first in synchronized context thread acquires the lock on current object. When wait(), notify(), notifyAll() methods are called lock is released on that object.



Explain which of the following methods releases the lock when yield(), join(),sleep(),wait(),notify(), notifyAll() methods are executed?

Method Releases lock      (Yes or No)
---------------------------------------------
yield()                                 No
sleep()                                 No
join()                                   No
wait()                                  Yes
Notify()                               Yes
notifyAll()                           Yes
----------------------------------------------



What are thread groups?

Thread Groups are group of threads and other thread groups. It is a way of grouping threads so that
actions can be performed on set of threads for easy maintenance and security purposes.
For example we can start and stop all thread groups. We rarely use thread group class. By default all the threads that are created belong to default thread group of the main thread. Every thread belongs to a thread group. Threads that belong to a particular thread group cannot modify threads belonging to
another thread group.



What are thread local variables ?

Thread local variables are variables associated to a particular thread rather than object. We declare
ThreadLocal object as private static variable in a class. Everytime a new thread accesses object by using getter or setter we are accessing copy of object. Whenever a thread calls get or set method of
ThreadLocal instance a new copy is associated with particular object.




What are daemon threads in java?

Daemon threads are threads which run in background. These are service threads and works for the
benefit of other threads. Garbage collector is one of the good example for daemon threads.
By default all threads are non daemon. Daemon nature of a thread can be inherited. If parent thread is
daemon , child thread also inherits daemon nature of thread.




How to make a non daemon thread as daemon?
By default all threads are non daemon. We can make non daemon nature of thread to daemon by using setDaemon() method. The important point to note here we can call setDaemon() only before start() method is called on it. If we call setDaemon() after start() method an IllegalThreadStateException will be thrown.



Can we make main() thread as daemon?

Main thread is always non daemon. We cannot change the non daemon nature of main thread to daemon.



What are nested classes in java?

Class declared with in another class is defined as nested class.

There are two types of nested classes in java.
1) Static nested class
2) Non static nested class
A static nested class has static keyword declared before class definition.



What are inner classes or non static nested classes in java?

Nested classes without any static keyword declaration in class definition are defined as non static nested classes. Generally non static nested classes are referred as inner classes.

There are three types of inner classes in java :
1) Local inner class
2) Member inner class
3) Anonymous inner class


Why to use nested classes in java? (or) What is the purpose of nested class in java?

1) Grouping of related classes
Classes which are not reusable can be defined as inner class instead of creating inner class.
For example : We have a submit button upon click of submit button we need to execute some code. This code is related only to that class and cannot be reused for other class . Instead of creating a new class we can create inner class

2) To increase encapsulation :
Inner class can access private members of outer class.so by creating getter and setter methods for
private variables , outside world can access these variables. But by creating inner class private variables can be accessed only by inner class.

3) Code readable and maintainable :
Rather than creating a new class we can create inner class so that it is easy to maintain.

4) Hiding implementation :
Inner class helps us to hide implementation of class.




Explain about static nested classes in java?

When a static class is defined inside a enclosing class we define that as nested class. Static nested classes are not inner classes. Static nested classes can be instantiated without instance of outer class.
A static nested doesn't have access to instance variables and non static methods of outer class.



How to instantiate static nested classes in java?

We can access static members and static methods of outer class without creating any instance of outer
class. Syntax for instantiating Static nested class :

OuterclassName.StaticNestedClassName ref=new OuterclassName.StaticNestedClassName();


Explain about method local inner classes or local inner classes in java?

Nested classes defined inside a method are local inner classes. We can create objects of local inner class only inside method where class is defined. A local inner classes exist only when method is invoked and goes out of scope when method returns.


Explain about features of local inner class?

1) Local inner class does not have any access specifier.
2) We cannot use access modifiers static for local inner class. But we can use abstract and final for           local inner class.
3) We cannot declare static members inside local inner classes.
4) We can create objects of local inner class only inside method where class is defined.
5) Method local inner classes can only access final variables declared inside a method.
6) Method local inner classes can be defined inside loops(for,while) and blocks such as if etc.


Explain about anonymous inner classes in java?

Inner class defined without any class name is called anonymous inner class. Inner class is declared and instantiated using new keyword.The main purpose of anonymous inner classes in java are to provide interface implementation. We use anonymous classes when we need only one instance for a class. We can use all members of enclosing class and final local variables.

When we compile anonymous inner classes compiler creates two files
1) EnclosingName.class
2) EnclsoingName$1.class



Explain restrictions for using anonymous inner classes?

1) An anonymous inner class cannot have any constructor because there is no name for class.
2) An anonymous inner class cannot define static methods, fields or classes.
3) We cannot define an interface anonymously.
4) Anonymous inner class can be instantiated only once.



Is this valid in java ? can we instantiate interface in java?

Runnable r = new Runnable()
{
@Override
public void run()
{
 // lines of code
}
};

Runnable is an interface.If we see the above code it looks like we are instantiating Runnable interface. But we are not instantiating interface we are instantiating anonymous inner class which is implementation of Runnable interface.



Explain about member inner classes?
Non static class defined with in enclosing class are called member inner class. A member inner class is defined at member level of class. A member inner class can access the members of outer class including private members.

Features of member inner classes :
1) A member inner class can be declared abstract or final.
2) A member inner class can extend class or implement interface.
3) An inner class cannot declare static fields or methods.
4) A member inner class can be declared with public, private, protected or default access.



How to instantiate member inner class?

OuterClassName.InnerclassName inner=new OuterClassReference.new InnerClassName();
We cannot instantiate inner class without outer class reference


How to do encapsulation in Java?

* Make instance variables private.
* Define getter and setter methods to access instance variables .


Can we have a method name same as class name in java?

Yes, we can have method name same as class name it won’t throw any compilation error but it shows a warning message that method name is same as class name.



Can we override constructors in java?

No, Only methods can be overridden in java. Constructors can’t be inherited in java. So there is no point of overriding constructors in java.


Can Static methods access instance variables in java?

No, Instance variables can’t be accessed in static methods. When we try to access instance variable in
static method we get compilation error. The error is as follows:
Cannot make a static reference to the non static field name



Can we override static methods in java?

Static methods can’t be overridden. If we have a static method in super class and subclass with same
signature then we don’t say that as overriding.


Difference between object and reference?

Reference and object are both different. Objects are instances of class that resides in heap memory.
Objects doesn't have any name so to access objects we use references. There is no alternative way to
access objects except through references. Object cannot be assigned to other object and object cannot be passed as an argument to a method. Reference is a variable which is used to access contents of an object. A reference can be assigned to other reference ,passed to a method.



Objects or references which of them gets garbage collected?

Objects get garbage collected not its references.



How many times finalize method will be invoked ? who invokes finalize() method in java?

Finalize () method will be called only once on object. Before the object gets garbage collected garbage collector will call finalize() method to free the resources. Finalize() method will be called only when object is eligible for garbage collection.


Can we able to pass objects as an arguments in java?

Only references can be passed to a method not an object. We cannot pass the objects to a method. The
largest amount of data that can passed as parameters are long or double.


Explain wrapper classes in java?

Converting primitives to objects can be done with the help of wrapper classes. Prior to java 1.5 we use Wrapper classes to convert primitives to objects. From java 1.5 we have a new feature autoboxing which is used to convert automatically primitives to objects but in wrapper classes programmer has to take care of converting primitives to objects.
Wrapper classes are immutable in java. Once a value is assigned to it we cannot change the value.

For every primitive in java we have corresponding wrapper class. Here are list of different types of wrapper classes in java

Primtive                  Wrapper Class
------------------------------------------
boolean                    Boolean
int                             Integer
float                          Float
char                          Character
byte                          Byte
long                          Long
short                         Short
------------------------------------------



Explain about transient variables in java?

To save the state of an object to persistent state we use serialization. If we want a field or variable in the object not to be saved, then we declare that variable or field as transient.

Example :

public Class Car implements serializable
{
    transient int carnumber;
}


Can we serialize static variables in java?

 Static variables cannot be serialized in java.


What is type conversion in java?

Assigning a value of one type to variable of other type is called type conversion.
Example : int a =10;
long b=a;
There are two types of conversion in java:
1) Widening conversion
2) Narrowing conversion



Explain about Automatic type conversion in java?

Java automatic type conversion is done if the following conditions are met :
1) When two types are compatible
Ex : int, float
int can be assigned directly to float variable.
2) Destination type is larger than source type.
Ex : int, long

Int can be assigned directly to long .Automatic type conversion takes place if int is assigned to long
because long is larger datatype than int. Widening Conversion comes under Automatic type conversion.



Explain about narrowing conversion in java?

When destination type is smaller than source type we use narrowing conversion mechanism in java.
Narrowing conversion has to be done manually if destination type is smaller than source type. To do
narrowing conversion we use cast. Cast is nothing but explicit type conversion.
Example : long a;
byte b;
b=(byte)a;
Note : casting to be done only on valid types otherwise ClassCastException will be thrown.



What is the scope or life time of instance variables ?

When object is instantiated using new operator variables get allocated in the memory.instance variables remain in memory till the instance gets garbage collected



Explain the scope or life time of class variables or static variables?

Static variables do not belong to instances of the class. We can access static fields even before
instantiating the class. Static variable remain in memory till the life time of application.


Explain scope or life time of local variables in java?

Local variables are variables which are defined inside a method. When the method is created local
variables gets created in stack memory and this variable gets deleted from memory once the method
execution is done.


Explain about static imports in java?

From Java 5.0 we can import static variables in to source file. Importing static member to source file is referred as static import. The advantage of static import is we can access static variables without class or interface name.
Syntax : import static packagename.classname.staticvariablename;
Ex : import static com.abc.Employee.eno;
To import all static variables from a class in to our source file we use *.
import static com.abc.Employee.*



Can we define static methods inside interface?

We can’t declare static methods inside interface. Only instance methods are permitted in interfaces.only public and abstract modifiers are permitted for interface methods. If we try to declare static methods inside interface we get compilation error saying
“Illegal modifier for the interface method Classname.methodName(); only public & abstract are
permitted”.


What's interface in java? What is the purpose of interface?

Interface is collection of abstract methods and constants. An interface is also defined as pure or 100
percent abstract class.Interfaces are implicitly abstract whether we define abstract access modifier or not. A class implementing interface overrides all the abstract methods defined in interface. Implements keyword is used to implement interface.

                            Interface is a contract . Interface acts like a communication between two objects. When we are defining interface we are defining a contract what our class should do but not how it does. An interface doesn't define what a method does. The power of interface lies when different classes that are unrelated can implement interface. Interfaces are designed to support dynamic method resolution at run time.



Explain features of interfaces in java?

1) All the methods defined in interfaces are implicitly abstract even though abstract modifier is not
declared.
2) All the methods in interface are public whether they are declared as public or not.
3) variables declared inside interface are by default public, static and final.
4) Interfaces cannot be instantiated.
5) we cannot declare static methods inside interface.
6) ‘ implements’ keyword is used to implement interface.
7) Unlike class, interface can extend any number of interfaces.
8) We can define a class inside interface and the class acts like inner class to interface.
9) An interface can extend a class and implement an interface
10) Multiple inheritance in java is achieved through interfaces.



Explain enumeration in java?

Enumeration is a new feature from Java 5.0. Enumeration is set of named constants . We use enum
keyword to declare enumeration. The values defined in enumeration are enum constants.Each enum
constant declared inside a enum class is by default public , static and final.
Example :
package javaexamples;
public enum Days {
SUN,MON,TUE,WED,THU,FRI,SAT;
}
SUN,MON,TUE,WED,THU,FRI,SAT are enum constants.

Different restrictions on using enum :

1) Enums cannot extend any other class or enum.
2) We cannot instantiate an enum.
3) We can declare fields and methods in enum class. But these fields and methods should follow the
enum constants otherwise we get compilation error.



Explain about field hiding in java?

If superclass and subclass have same fields subclass cannot override superclass fields. In this case
subclass fields hides the super class fields. If we want to use super class variables in subclass we use
super keyword to access super class variables.


Explain about Varargs in java?

Beginning with Java 5 has a new feature Varargs which allows methods to have variable number of
arguments. It simplifies creation of methods when there are more number of arguments. Earlier to java 5, Varargs are handled by creating method with array of arguments.
Ex : public static void main(String[] args)
A variable length argument is specified using eclipse with type in signature. main method with var args is written as follows:

public static void main(String … args)
If no arguments are passes we get array with size 0.There is no need for null check if no arguments are passed.


What is covariant return ?

In java 1.4 and earlier one method can override super class method if both methods have same signature and return types.
From Java 1.5 , a method can override other method if argument types match exactly though return
types are different.(Return type must be subtype of other method).
Example :

Class A
{
    A doSomeThing()
     {
        return new A();
     }
}

Example :

Class B
{
     B doSomeThing()
      {
         return new B();
      }
}

From java 1.5 return type for doSomeThing() in Class B is valid . We get compile time error in 1.4 and earlier.



What is collections framework ?

A framework is set of classes and interfaces to build a functionality. Java collections framework provides set of interfaces and classes for storing and manipulating collections. Collection framework contains classes and interfaces in java.util package and java.util.concurrent packages.

Advantages or benefits of Collections framework :

1) High performance
2) Using this framework we can create different types of collections
3) We can create our own collection and we can extend a collection.
4) Reduces programming effort.
5) Increases speed and quality : Collections framework provides high performance, implementations       of useful data structures and algorithms.

What is collection ?

A collection is a container which holds group of objects. Collection provides a way to manage objects
easily. Collections manages group of objects as single unit.
Examples include list of strings, integers etc.
Here are few basic operations we do on collections :
1) Adding objects to collection.
2) Removing or deleting objects from collection.
3) Retrieving object from collection.
4) Iterating collection.


Difference between collection, Collection and Collections in java?

collection : represent group of objects where objects are stored.
Collection : This is one of the core interface which provides basic functionality for collection.
Collections : Collections contains some utility static methods that operate on collections.



Explain about Collection interface in java ?

Collection is the fundamental and root interface in Collections framework.
Collection extends Iterable interface and inherits iterator method which returns Iterator object.

Signature :

public interface Collection<E> extends Iterable<E>
{
   // iterated code
}

List the interfaces which extends collection interface :
1) List
2) Set
3) Queue
4) Deque ( From Java 6)


Explain List interface ?

List interface extends collection interface used to store sequence of elements in collection.
We can even store duplicate elements in list.
We can insert or access elements in list by using index as we do in arrays.
List is an ordered collection.
The main difference between List and non list interface are methods based on position.
Some of the operations we can perform on List :
1) Adding an element at specified index.
2) Removing an element at specified index.
3) To get the index of element



Explain about fail fast iterators in java?

When iterator iterates over collection, collection should not be modified except by that iterator.
Modification means collection cannot be modified by thread when other thread is iterating, if such
modification happens a concurrent modification exception will be thrown.Such kind of iterators are fail fast iterators.
Ex : ArrayList,HashSet,HashMap. Almost all the iterators implemented in collections framework are fail fast.



Explain about fail safe iterators in java?

Fail safe iterators are iterators which does not throw concurrent modification exception, when one thread modifies collection and other thread in the process of iterating the collection.
It does not throw concurrent modification exception because when other thread was iterating it does not modify original list but creates a copy of list with modified contents so that the iterator won’t know the modifications made to original list.
Ex : copyOnWriteArrayList



What is serialization in java?

Serialization is the process of converting an object in to bytes, so that it can be transmitted over the
network,or stored in a flat file and can be recreated later. Serialized object is an object represented as
sequence of bytes that includes objects data, object type, and the types of data stored in the object.

Main purpose of serialization in java :

1) Persistence:
We can write data to a file or database and can be used later by deserializing it.

2) Communication :
To pass an object over network by making remote procedure call.

3) Copying :
We can create duplicates of original object by using byte array.

4) To distribute objects across different JVMs.


What are alternatives to java serialization?

XML based data transfer
JSON based data transfer.

XML based data transfer : We can use JIBX or JAXB where we can marshall our object’s data to xml and transfer data and then unmarshall and convert to object.

JSON based transfer : We can use json to transfer data.



Explain about serializable interface in java?

To implement serialization in java there is an interface defined in java.io package called serializable
interface. Java.io.Serializable interface is an marker interface which doesnot contain any any methods. A class implements Serializable lets the JVM know that the instances of the class can be serialized.

Syntax:
public interface Serializable
{
   // implements your code
}



How to make object serializable in java?

1) Our class must implement serializable interface.If our object contains other objects those class must also implement serializable interface.
2) We use ObjectOutputStream which extends OutputStream used to write objects to a stream.
3) We use ObjectInputStream which extends InputStream used to read objects from stream


What is serial version UID and its importance in java?

Serial version unique identifier is a 64 bit long value .This 64 bit long value is a hash code of the class name,super interfaces and member. Suid is a unique id no two classes will have same suid. Whenever an object is serialized suid value will also serialize with it.
When an object is read using ObjectInputStream, the suid is also read. If the loaded class suid does not match with suid read from object stream, readObject throws an InvalidClassException.



What happens if we don’t define serial version UID ?

If we don’t define serial version UID JVM will create one suid for us. But it is recommended to have suid rather than JVM creating because at run time JVM has to compute the hashcode of all the properties of class. This process makes serialization low. We can’t serialize static fields one exception to this is suid where suid gets serialized along with the object.
Ex :private static final long serialVersionUID = -5885568094444284875L;



Can we serialize static variables in java?

We can’t serialize static variables in java. The reason being static variable are class variables that belongs to a class not to object, but serialization mechanism saves only the object state not the class state.


When we serialize an object does the serialization mechanism saves its references too?

When we serialize an object even the object it refers must implement serializable then the reference
objects also get serialized. If we don’t make reference objects serializable then we get
NotSerializableException.


If we don’t want some of the fields not to serialize How to do that?

If we don’t want to serialize some fields during serialization we declare those variables as transient.
During deserialization transient variables are initialized with default values for primitives and null for
object references.

No comments:

Post a Comment

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...