Monday, 2 January 2017

Home         Core Java          Hibernate            Spring



Ramjeet Mahto
Bird
Bangalore 
9066588013
ramjeet.mahto89@gmail.com
26th December 2016
Dear Interviewer,
These all the questions has been asked in the java Developer interview in a  top MNC and MNC level Company so  be prepared these question  to answer properly.
Q.) Difference among JDK, JRE, JVM?
Answer: - JVM:-
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JRE:-
JRE is an acronym for (Java Runtime Environment). It is used to provide runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.
jre
JDK:-
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

Q.)What is JVM? Are you aware of Heapsize, Stacksize & Garbage Collection? Please share some more light.

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Q.)What is Java ClassLoader?

We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled program and store it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.


There are three types of built-in ClassLoader in Java:
1.   Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes
2.   Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
3.   System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
4.     Lets understand this by executing the below java program:
ClassLoaderTest.java
package com.java.journaldev;

public class ClassLoaderTest {

public static void main(String[] args) {

System.out.println("class loader for HashMap: " + java.util.HashMap.class.getClassLoader());
System.out.println("class loader for DNSNameService: "
                   + sun.net.spi.nameservice.dns.DNSNameService.class.getClassLoader());
System.out.println("class loader for this class: " + ClassLoaderTest.class.getClassLoader());
System.out.println(com.mysql.jdbc.Blob.class.getClassLoader());
     }
}



5.     class loader for HashMap: null
6.     class loader for DNSNameService: sun.misc.Launcher$ExtClassLoader@7c354093
7.     class loader for this class: sun.misc.Launcher$AppClassLoader@64cbbe37
8.     sun.misc.Launcher$AppClassLoader@64cbbe37

Q.) How does Java ClassLoader Work?

When JVM requests for a class, it invokes loadClass function of the ClassLoader by passing the fully classified name of the Class.
loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.
If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.
If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.





Q.) What is Variable How many types of variable in java?
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed.

1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable . It is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be local.

Q.) What are some core concepts of OOPS in java?

Core concepts of OOPs are :
  • Polymorphism
  • Abstraction
  • Encapsulation
  • Inheritance

Abstraction?

Abstraction is a concept of exposing essential information and hiding implementation details.
For example: 
When you see a car, you know it is running but how it running internally, you may not aware of it.
This is Abstraction. You just expose required details.

 

Encapsulation

·         Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
·         Encapsulated code has two features:
·         Instance variables are kept protected (usually with the private modifier).
·         Getter and setter methods provide access to instance variables.
·         The public setName() and getName() methods are the access points of the instance variables

Polymorphism?

Polymorphism means one name many forms. It is concept by which you can perform same action in different ways. Method overloading and method overriding are example of Polymorphism.
·         Polymorphism means “many forms.”
·         A reference variable is always of a single, unchangeable type, but it can refer to a subtype object.
·         A single object can be referred to by reference variables of many different types —as long as they are the same type or a supertype of the object.
·         Polymorphic method invocations apply only to overridden instance methods.

Inheritance?

Inheritance allows use of properties and methods of another class (Parent class), so you can reuse all methods and properties.
·         Inheritance allows a class to be a subclass of a superclass, and thereby inherit public and protected variables and methods of the superclass.
·         Inheritance is a key concept that underlies polymorphismoverridingoverloading and casting.

Q.) What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:
  • By new keyword
  • By newInstance() method of Class class
  • By newInstance method of Constructor class
  • By clone() method
  • By Deserialization
1. Using new keywords: It is the most common and regular way to create an object and a very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parameterized).
o    Employee emp1 = new Employee();
2. Using newInstance() method of Class class:
 We can also use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor to create the object.
o    We can create an object by newInstance() in the following way:

o    Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();
Or:
o    Employee emp2 = Employee.class.newInstance();

3. Using newInstance() method of Constructor class: 
Similar to the newInstance() method of a Class, there is one newInstance() method in the java.lang.reflect.Constructor class, which we can use to create objects. We can also call a parameterized constructor and private constructor by using this newInstance() method. 

o    Constructor<Employee> constructor = Employee.class.getConstructor();
o    Employee emp3 = constructor.newInstance();


4. Using clone() method:
 Whenever we call clone() on any object, the JVM actually creates a new object for us and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor. 
o    To use clone() method on an object we need to implement Cloneable and define the clone() method in it. 
o    Employee emp4 = (Employee) emp3.clone();

5. Using deserialization:
o     Whenever we serialize and deserialize an object, the JVM creates a separate object for us. In deserialization, the JVM doesn’t use any constructor to create the object. 
o    To deserialize an object we need to implement a Serializable interface in our class. 

o    ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
o    Employee emp5 = (Employee) in.readObject();


Q.) What is method overloading in java?


Method overloading : If two or more methods have same name , but different argument then it is called method overloading.

 Rules of Overloading

In terms of constraints between overloaded methods, overloading is more relaxed than overriding, as the only requirement is to change the arguments, in combination of quantity and types. The return types, access modifiers and throws clauses can be freely declared. To summary, the overloaded methods:
·         Must have different arguments list (quantity and types).
·         May have different return types.
·         May have different access modifiers.
·         May throw different exceptions
Method overriding : If subclass is having same method as base class then it is known as method overriding Or in another words, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding.

1.) Overriding
 refers to the ability of a subclass to re-implement an instance method inherited from a superclass. Let’s take a look at the following class diagram:
Overriding concept
Here, Animal is the superclass and Dog is the subclass, thus Dog inherits the move() method from Animal. However, Dogre-implements the move() method for some behaviors which are specific to only dogs (like walk and run). In this respect:
·         The Dog’s move() method is called the overriding method.
·         The Animal’s move() method is called the overridden method.
Basically, the overriding method must have same name and same arguments list as the overridden one. It’s the way by which a subtype extends or re-defines behaviors of its supertype.


2.    What methods can be overridden?

Rule #1: Only inherited methods can be overridden.
Because overriding happens when a subclass re-implements a method inherited from a superclass, so only inherited methods can be overridden, that’s straightforward. That means only methods declared with the following access modifiers: public, protected and default (in the same package) can be overridden. That also means private methods cannot be overridden. Let’s see some examples:
·         The Dog class overrides both the move() (public) and eat() (protected) methods from the Animal class (regardless of packages where the both classes are declared):
1
2
3
4
5
6
7
8
9
10
public class Animal {

    public void move() {
        // animal moving code...
    }

    protected void eat() {
        // animal eating code...
    }
}
1
2
3
4
5
6
7
8
9
10
public class Dog extends Animal {

    public void move() {
        // dog moving code...
    }

    protected void eat() {
        // dog eating code...
    }
}
·         In the following example, the Dog class perfectly overrides the move() method which is declared with default access modifier in the Animal class, as long as both the classes are in the same package:
1
2
3
4
5
6
7
8
package net.codejava.core;

public class Animal {

    void move() {
        // Animal moving code...
    }
}
1
2
3
4
5
6
7
8
package net.codejava.core;

public class Dog extends Animal {

    void move() {
        // Dog moving code...
    }
}
·         In the following example, the Dog and Animal classes are in different packages. Thus it isn’t considered an overriding because the Dog class does not inherit the Animal’s move() method:
1
2
3
4
5
6
7
8
package net.codejava.animal;

public class Animal {

    void move() {
        // Animal moving code...
    }
}

1
2
3
4
5
6
7
8
9
10
package net.codejava.dog;

import net.codejava.core.animal.Animal;

public class Dog extends Animal {

    void move() {
        // Dog moving code...
    }
}
·         Here, the Dog’s move() method is just a new method, not an overriding one.
·         In the following example, the Animal’s move() method is private, so the Dog’s move() method is just a new method, not an overriding one:

1
2
3
4
5
6
public class Animal {

    private void move() {
        // Animal moving code...
    }
}


1
2
3
4
5
6
public class Dog extends Animal {

    public void move() {
        // Dog moving code...
    }
}


3.    What methods that cannot be overridden?

Rule #2: Final and static methods cannot be overridden.
A final method means that it cannot be re-implemented by a subclass, thus it cannot be overridden. Consider the following example:

1
2
3
4
5
6
public class Animal {

    final void sleep() {
        // animal sleeping code...
    }
}


1
2
3
4
5
6
public class Dog extends Animal {

    public void sleep() {
        // Dog sleeping code...
    }
}




Here, the Animal’s sleep() method is marked as final, therefore the Dog class won’t compile. The compiler will complain:
1
2
3
4
5
error: sleep() in Dog cannot override sleep() in Animal
    public void sleep() {
                ^
  overridden method is final
1 error
In case of static method, because a static method is available to all instances of the superclass and its subclasses, so it’s not permissible to re-implement the static method in a particular subclass. Consider the following example:

1
2
3
4
5
6
public class Animal {

    static void sleep() {
        // animal sleeping code...
    }
}


1
2
3
4
5
6
public class Dog extends Animal {

    public void sleep() {
        // Dog sleeping code...
    }
}



The compiler will issue the following complaint when trying to compile the Dog class:
1
2
3
4
5
error: sleep() in Dog cannot override sleep() in Animal
    public void sleep() {
                ^
  overridden method is static
1 error

 


4.    Requirements for the overriding method

With respect to the overridden method, the overriding method must obey the following rules:
Rule #3: The overriding method must have same argument list.
Let’s see the following example:

1
2
3
4
5
6
public class Animal {

    protected void eat(String food) {
        // animal eating code...
    }
}


1
2
3
4
5
6
public class Dog extends Animal {

    protected void eat(String food) {
        // dog eating code...
    }
}

The eat() method of the Dog class is a legal overriding, as it keeps the same argument (String food) as the superclass’ version. If we add a new argument to the method like this:
1
2
3
protected void eat(String food, int amount) {
    // dog eating code...
}
Then this method is not an overriding, it is an overload instead.

Rule #4: The overriding method must have same return type (or subtype).
Suppose that a Food class has a subclass called DogFood, the following example shows a correct overriding:

1
2
3
4
5
6
7
8
public class Animal {

    protected Food seekFood() {

        // animal seeking for food code...

        return new Food();
    }
}


1
2
3
4
5
6
7
8
public class Dog extends Animal {

    protected Food seekFood() {

        // dog seeking for food code...

        return new DogFood();
    }
}

It’s possible to modify the return type of the Dog’s seekFood() method to DogFood - a subclass of Food, as shown below:
1
2
3
4
5
6
protected DogFood seekFood() {

    // dog seeking for food code...

    return new DogFood();
}
That’s perfectly a legal overriding, and the return type of Dog’s seekFood() method is known as covariant return type.
The Dog class won’t compile if we change the seekFood() method’s return type to another, as shown below:
1
2
3
4
5
6
protected String seekFood() {

    // dog seeking for food code...

    return new String();
}
As the complier issues this error:
1
2
3
4
5
error: seekFood() in Dog cannot override seekFood() in Animal
    protected String seekFood() {
                     ^
  return type String is not compatible with Food
1 error

Rule #5: The overriding method must not have more restrictive access modifier.
This rule can be understood as follows:
·         If the overridden method is has default access, then the overriding one must be default, protected or public.
·         If the overridden method is protected, then the overriding one must be protected or public.
·         If the overridden method is public, then the overriding one must be only public.
In other words, the overriding method may have less restrictive (more relaxed) access modifier. The following example shows a legal overriding:

1
2
3
4
5
6
public class Animal {

    protected void move() {
        // animal moving code...
    }
}


1
2
3
4
5
6
public class Dog extends Animal {

    public void move() {
        // Dog moving code...
    }
}

However, in the following example, the Dog class won’t compile:
1
2
3
4
5
6
public class Dog extends Animal {

    void move() {
        // Dog moving code...
    }
}
It is because the move() method now has default access, which is more restrictive than the protected access of the superclass’ version.

Rule #6: The overriding method must not throw new or broader checked exceptions.
In other words, the overriding method may throw fewer or narrower checked exceptions, or any unchecked exceptions.
Consider the following superclass - Animal:
1
2
3
4
5
6
public class Animal {

    protected void move() throws IOException {
        // animal moving code...
    }
}
The following subclass - Dog, correctly overrides the move() method because the FileNotFoundException is a subclass of the FileIOException:
1
2
3
4
5
6
public class Dog extends Animal {

    protected void move() throws FileNotFoundException {
        // Dog moving code...
    }
}
The following example shows an illegal overriding attempt because the InterruptedException is a new and checked exception:
1
2
3
4
5
6
public class Dog extends Animal {

    protected void move() throws IOException, InterruptedException {
        // Dog moving code...
    }
}
However, the following example is a legal overriding, because the IllegalArgumentException is an unchecked exception:
1
2
3
4
5
6
public class Dog extends Animal {

    protected void move() throws IOException, IllegalArgumentException {
        // Dog moving code...
    }
}
And in the example below, the Dog class won’t compile because its move() method throws Exception which is superclass (broader) of the IOException:
1
2
3
4
5
6
public class Dog extends Animal {

    protected void move() throws Exception {
        // Dog moving code...
    }
}


5.    Invoking the overridden method

Rule #7: Use the super keyword to invoke the overridden method from a subclass.
It’s very common that a subclass extends a superclass’ behavior rather than re-implementing the behavior from scratch. In such case, invoke the superclass’ method in the following form:
super.overriddenMethodName()
Consider the following example:

1
2
3
4
5
6
public class Animal {

    protected void move() {
        // animal moving code...
    }
}


1
2
3
4
5
6
7
8
public class Dog extends Animal {

    protected void move() {
        super.move();   // Animal movement

        // Dog-specific moving code...
    }
}

Here, the Dog class overrides the move() method from the Animal class. Then in the Dog’s move() method, it calls the superclass’ version of the method first, then add behaviors specific to only dogs.


6.    Overriding and constructor

Rule #8: Constructors cannot be overridden.
Because constructors are not methods and a subclass’ constructor cannot have same name as a superclass’ one, so there’s nothing relates between constructors and overriding.

7.    Overriding and abstract method
Rule #9: Abstract methods must be overridden by the first concrete (non-abstract) subclass.
Consider the following interface:
1
2
3
public interface Animal {
    void move();
}
If an abstract class implements the above interface, then it doesn’t require the subclass to override the move() method, as shown in the following AbstractDog class:
1
2
3
4
5
public abstract class AbstractDog implements Animal {

    protected abstract void bark();

}
But if a concrete (non-abstract) class, says BullDog, is a subclass of the AbstractDog class or the Animal interface, then it must override all the inherited abstract methods, as shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BullDog extends AbstractDog {

    public void move() {

        // Bulldog moves...

    }

    protected void bark() {

        // Bulldog barks...

    }

}
In this respect, the BullDog class is said to implement the move() and bark() abstract methods of its supertypes - the Animal interface and the AbstractDog class. Although all the rules of overriding must be obeyed in this context, the term implement is more exact then the term override, since the overridden method is abstract.


8.    Overriding and static method

Rule #10: A static method in a subclass may hide another static one in a superclass, and that’s called hiding.
Consider the following example:

1
2
3
4
5
6
7
public class Animal {

    static void sleep() {
        System.out.println("Animal sleeps");
    }

}


1
2
3
4
5
6
public class Dog extends Animal {

    static void sleep() {
        System.out.println("Dog sleeps");
    }
}

Here, the sleep() method of the Dog class is said to hide the sleep() method of the Animal class. When a static method of the superclass is hidden, it requires the subclass to use a fully qualified class name of the superclass to invoke the hidden method, as shown in the doSomething() method of the Dog class below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Dog extends Animal {

    static void sleep() {
        System.out.println("Dog sleeps");
    }

    void doSomething() {
        sleep();    // this calls the hiding method

        // because the Animal's sleep() is hidden, it requires to use
        // a fully qualified class name to access it.
        Animal.sleep();
    }
}
Note that the rules of overriding are still applied for the hiding method.


9.    Overriding and synchronized method

Rule #11: The synchronized modifier has no effect on the rules of overriding.
The synchronized modifier relates to the acquiring and releasing of a monitor object in multi-threaded context, therefore it has totally no effect on the rules of overriding. That means a synchronized method can override a non-synchronized one and vice versa.


10.    Overriding and strictfp method

Rule #12: The strictfp modifier has no effect on the rules of overriding.
That means the presence or absence of the strictfp modifier has absolutely no effect on the rules of overriding: it’s possible that a FP-strict method can override a non-FP-strict one and vice-versa.
Q.) What is constructor in java?
Constructor is block of code which allows you to create instance of the object. It does not have return type.
It has two main points 
  • Constructor name should be same as class
  • Constructor should not have any return type else it will be same as method.



Q.) What is static in java?
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1.      class Student{  
2.           int rollno;  
3.           String name;  
4.           String college="ITS";  
5.      }

2) Java static method

If you apply static keyword with any method, it is known as static method.
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.

3) Java static block

  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.

Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
Q.) What is difference between Abstract class and interface?

Parameter
Abstract class
Interface
Default method Implementation
It can have default method implementation
Interfaces are pure abstraction.It can not have implementation at all but in java 8, you can have default methods in interface.
Implementation
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class
subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface
Constructor
Abstract class can have constructor
Interface  can not have constructor
Different from normal java class
Abstract classes are almost same as java classes except you can not instantiate it.
Interfaces are altogether different type
Access Modifier
Abstract class methods can have public ,protected,private and default modifier
Interface methods are by default public. you can not use any other access modifier with it
Main() method
Abstract classes can have main method so we can run it
Interface do not have main method so we can not run it.
Multiple inheritance
Abstract class can extends one other class and can implement one or more interface.
Interface can extends to one or more interfaces only
Speed
It is faster than interface
Interface is somewhat slower as it takes some time to find implemented method in class
Adding new method
If you add new method to abstract class, you can provide default implementation of it. So you don't need to change your current code
If you add new method to interface, you have to change the classes which are implementing that interface

Q.)  What is marker interface?

Marker interfaces are interfaces which have no method but it is used to indicate JVM to behave specially when any class implement these interfaces. 
For example : If you implement cloneable interface and then call .clone method of object, it will clone your object. If you do not implement cloneable interface, it will throw cloneNotSupported exception.

Q.) What are access modifier available in java?

It Specifies accessibility of variables, methods , constructor of class.
There are four access modifier in java
Private : Accessible only to the class.
Default : Accessible in the package.
Protected : Accessible in the packages and its subclasses.
Public : Accessible everywhere

Q.)  Object class in Java and what are methods in Object class?

The Object class is the parent class of all the classes in java by default.

Methods of Object class

The Object class provides many methods. They are as follows:

Method
Description
public final Class getClass()
returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()
returns the hashcode number for this object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString()
returns the string representation of this object.
public final void notify()
wakes up single thread, waiting on this object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException
causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException
causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException
causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable
is invoked by the garbage collector before object is being garbage collected.

Q.) What is wrapper class in Java & what are the Wrapper class?


Wrapper class in java
 provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:
Primitive Type
Wrapper class
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
Note:-
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Q.) What is String in java?

Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.
To create & manipulate the String , java provide 2 class.
1)      Java.lang.String(1.0)
2)      Java.lang.StringBuffer(1.5)
3)      Java.lang.StringBuilder(1.5)

How to create String object?

There are two ways to create String object:
1.      By string literal
2.    By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:
1.      String s="welcome";  
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
1.      String s1="Welcome";  
2.      String s2="Welcome";//will not create new instance  

Note: String objects are stored in a special memory area known as string constant pool.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

2) By new keyword

1.      String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Q.) Why String is declared final or immutable in java?

There are various reasons to make String immutable.
  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value
Q.) what is the difference between equals() methods and == operator in java?

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
Example:-
String s1="Sachin";  
String s2="Sachin";  
String s3=new String("Sachin");  
System.out.println(s1.equals(s2));//true  
System.out.println(s1.equals(s3));//true  

2) String compare by == operator

The = = operator compares references not values.
Example:-
String s1="Sachin";  
String s2="Sachin";  
String s3=new String("Sachin");  
System.out.println(s1==s2);//true (because both refer to same instance)  
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  

Q.) What is StringBuffer , StringBuilder in java?

StringBuffer class

Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.


StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.


Difference between String and StringBuffer


No.
String
StringBuffer
1)
String class is immutable.
StringBuffer class is mutable.
2)
String is slow and consumes more memory when you concat too many strings because every time it creates new instance.
StringBuffer is fast and consumes less memory when you cancat strings.
3)
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
StringBuffer class doesn't override the equals() method of Object class.

Difference between StringBuffer and StringBuilder


No.
StringBuffer
StringBuilder
1)
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)
StringBuffer is less efficient than StringBuilder.
StringBuilder is more efficient than StringBuffer.





Q.) How to create Immutable class?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:
Example to create a immutable class in java
1.    public final class Employee{  
2.    final String pancardNumber;  
3.      
4.    public Employee(String pancardNumber){  
5.    this.pancardNumber=pancardNumber;  
6.    }  
7.      
8.    public String getPancardNumber(){  
9.    return pancardNumber;  
10. }  
11.   
12. }

The above class is immutable because:
  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as immutable.



Q.) What is toString() method in java?

toString() method

If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code

Q.) What is exception handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Hierarchy of Java Exception classes

hierarchy of exception handling

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
  1. Checked Exception
  2. Unchecked Exception
  3. Error

What is the difference between checked and unchecked exceptions?


1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Q.) How many way we can handle the Exception in java?

 Java Exception Handling Keywords

There are 5 keywords used in java exception handling.
  1. try
  2. catch
  3. finally
  4. throw
  5. throws


Q.) What is the Difference between throw and throws in Java?

No.
throw
throws
1)
Java throw keyword is used to explicitly throw an exception.
Java throws keyword is used to declare an exception.
2)
Checked exception cannot be propagated using throw only.
Checked exception can be propagated with throws.
3)
Throw is followed by an instance.
Throws is followed by class.
4)
Throw is used within the method.
Throws is used with the method signature.
5)
You cannot throw multiple exceptions.
You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException

Q.) What is the Difference between final, finally and finalize?

No.
final
finally
finalize
1)
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
Finally is used to place important code, it will be executed whether exception is handled or not.
Finalize is used to perform clean up processing just before object is garbage collected.
2)
Final is a keyword.
Finally is a block.
Finalize is a method.

Q.) What is ExceptionHandling with MethodOverriding in Java?

There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:
  • If the superclass method does not declare an exception
    • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
  • If the superclass method declares an exception
    • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
Q.) How to write custom Exception in java?
If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.
package com.java.interview;

public class UserException extends Exception {
     /**
      *
      */
     private static final long serialVersionUID = 1L;

     String message;

     public UserException(String message) {
           this.message = message;
     }

     @Override
     public String toString() {
           return "UserException [message=" + message + "]";
     }
}

package com.java.interview;

import java.util.Scanner;

public class UserExceptionTest {
     public static void main(String[] args) {
           Scanner sc=new Scanner(System.in);
           System.out.println("Enter the value....");
          
           int age=sc.nextInt();
           try{
                if(age<18){
                     throw  new UserException("He cannt vote...");
                }else{
                     System.out.println("He can vote");
                }
           }catch(UserException e){
                System.out.println(e);
           }
     }
}

Q.) What is thread in java?

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

Q.) Define states of thread in java?

thread life cycle in java
There are 5 states of thread in java

New : When you create a thread object and it is not alive yet.
Runnable:  When you call start method of thread, it goes into Runnable state. Whether it will execute immediately or execute after some times, depends on thread scheduler.
RunningWhen thread is being executed, it goes to running state.
Blocked When thread waits for some resources or some other thread to complete (due to thread's join), it goes to blocked state.
TerminatedWhen thread's run method returns, thread goes to dead state.

Q. How to create thread?

There are two ways to create a thread:
  1. By extending Thread class
  2. By implementing Runnable interface.

Q.) Can we start a thread twice?

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Q.) What are differences between Sleep and wait in java?

Parameter
wait
sleep
Synchonized
wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException
It need not be called from synchronized block or methods
Calls on
wait method operates on Object and defined in Object class
Sleep method operates on current thread and is in java.lang.Thread
Release of lock
wait release lock of object on which it is called and also other locks if it holds any
Sleep method does not release lock at all
Wake up condition
until call notify() or notifyAll() from Object class
Until time expires or calls interrupt()
static
wait is non static method
sleep is static method


Q.) what is Synchronization in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.

Q.) What is Synchronized block in java?

Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

o    Synchronized block is used to lock an object for any shared resource.
o    Scope of synchronized block is smaller than the method.
Q.) What is the difference between Synchronized block & method?
===============

Q.) What is Deadlock in java?

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

Q.) What is Serialization in Java?

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).
If you want a class object to be serializable, all you need to do it implement the java.io.Serializableinterface. Serializable in java is a marker interface and has no fields or methods to implement. It’s like an Opt-In process through which we make our classes serializable.
Serialization in java is implemented by ObjectInputStream and ObjectOutputStream, so all we need is a wrapper over them to either save it to file or send it over the network. Let’s see a simple Serialization in java program example.
Notice that it’s a simple java bean with some properties and getter-setter methods. If you want an object property to be not serialized to stream, you can use transient keyword like I have done with salary variable.
If these methods are present in the class, they are used for serialization purposes.
1.      readObject(ObjectInputStream ois): If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.
2.      writeObject(ObjectOutputStream oos): If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream. One of the common usage is to obscure the object variables to maintain data integrity.
3.      Object writeReplace(): If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.
4.      Object readResolve(): If this method is present, then after deserialization process, this method is called to return the final object to the caller program.



Example of Serialization & Deserialization
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Student implements Serializable{
            int rollNo;
            String name;
            double marks;
            public Student(int rollNo, String name, double marks) {
                        super();
                        this.rollNo = rollNo;
                        this.name = name;
                        this.marks = marks;
            }
            public int getRollNo() {
                        return rollNo;
            }
            public void setRollNo(int rollNo) {
                        this.rollNo = rollNo;
            }
            public String getName() {
                        return name;
            }
            public void setName(String name) {
                        this.name = name;
            }
            public double getMarks() {
                        return marks;
            }
            public void setMarks(double marks) {
                        this.marks = marks;
            }
            public static void main(String[] args) throws IOException, ClassNotFoundException {
                        Student s=new Student(101, "John Minj", 560);
                       
                        //Serialization
                        FileOutputStream fos=new FileOutputStream("C:\\Users\\Ramjeet\\Desktop\\Resumes\\temp1.txt");
                        ObjectOutputStream oos=new ObjectOutputStream(fos);
                        oos.writeObject(s);
                        System.out.println("Data saved succefully...");
                       
                        //De-serialization
                        FileInputStream fis=new FileInputStream("C:\\Users\\Ramjeet\\Desktop\\Resumes\\temp1.txt");
                        ObjectInputStream ois=new ObjectInputStream(fis);
                        s=(Student)ois.readObject();
                        System.out.println("The student rollno: "+s.getRollNo());
                        System.out.println("The student name  :"+s.getName());
                        System.out.println("The student marks :"+s.getMarks());
                        System.out.println("Data successfully retrived...");
            }
}

 Q.) What is Externalizable in java?

The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:
  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException
Q.) What are differences between ArrayList and LinkedList in java? 
ArrayList
LinkedList
1) ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
3) ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.


Q.) How add method Works Internally In ArrayList?

There are two ways to create an ArrayList object . 

a. Creates the empty list with initial capacity

 1.  List            list= new ArrayList();

When we create ArrayList this way , the default constructor of the ArrayList class is invoked. It will create internally an array of Object with default size set to 10.

 2.  List            list= new ArrayList(20);

When we create ArrayList this way , the  ArrayList will invoke the constructor with the integer argument. It will create internally an array of Object . The size of the Object[] will be equal to the argument passed in the constructor . Thus when above line of code is executed ,it  creates an Object[] of capacity 20.

Thus , above ArrayList constructors will create an empty list . Their initial capacity can be 10 or equal to the value of the argument passed in the constructor.


b. Creates the non empty list containing the elements of the specified collection. 

List list=new ArrayList(Collection c);

The above ArrayList constructor will create an non empty list containing the elements of the collection passed in the constructor.












How the size of ArrayList grows dynamically? 

Inside the add(Object) , you will find the following code


    public boolean add(E e)
    
{
   
     ensureCapacity(size+1);
     elementData[size++] = e;         
     return true;
}

Important point to note from above code is that we are checking the capacity of the ArrayList , before adding the element. ensureCapacity()  determines what is the current size of occupied elements and what is the maximum size of the array. If size of the  filled elements (including the new element to be added to the ArrayList class) is greater than the  maximum size of the array then increase the size of array. But the size of the array can not be increased dynamically. So what happens internally is new Array is created with capacity

Till Java 6
   int newCapacity = (oldCapacity * 3)/2 + 1;

(Update) From Java 7
     
int newCapacity = oldCapacity + (oldCapacity >> 1);
also, data from the old array is copied into the new array.

Q.) What is HashSet & How it works internally?

HashSet:

HashSet implements Set interface which does not allow duplicate value.It is not synchronized and is not thread safe.

Internal working of HashSet:

When you add any duplicate element to HashSet, add() method returns false and do not add duplicate element to HashSet.
How add method return false? For this, we need to see HashSet's add method in JavaAPI
  1. public class HashSet<E>  
  2.     extends AbstractSet<E>  
  3.     implements Set<E>, Cloneable, java.io.Serializable  
  4. {  
  5.       
  6.     private transient HashMap<E,Object> map;  
  7.    
  8.     // PRESENT is dummy value which will be used as value in map  
  9.     private static final Object PRESENT = new Object();  
  10.       
  11.     /** 
  12.      * Constructs a empty map.so hash 
  13.      *  
  14.      */  
  15.     public HashSet() {  
  16.      map = new HashMap<E,Object>();  
  17.     }  
  18.       
  19.     // return false if e is already present in HashSet  
  20.     public boolean add(E e) {  
  21.      return map.put(e, PRESENT)==null;  
  22.     }  
  23.       
  24.     // other HashSet methods  
  25. }  
So from above code, It is clear that HashSet uses HashMap for checking duplicate elements.As we know that in HashMap , key should be unique. So HashSet uses this concept, When element is added to HashSet, it is added to internal HashMap as Key.This HashMap required some value so a dummy Object(PRESENT) is used as value in this HashMap.
PRESENT is dummy value which is used value for internal map.
Lets see add method: 
  1. // return false if e is already present in HashSet  
  2.    public boolean add(E e) {  
  3.     return map.put(e, PRESENT)==null;  
  4.    }  
So here there will be two cases
  • map.put(e,PRESENT) will return null, if element not present in that map. So map.put(e, PRESENT) == null will return true ,hence add method will return true and element will be added in HashSet.
  • map.put(e,PRESENT) will return old value ,if element is already present in that map. So  map.put(e, PRESENT) == null will return false, hence add method will return false and element will not be added in HashSet.

Java LinkedHashSet class

  • contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
  • maintains insertion order

Java TreeSet class

  • contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • maintains ascending order.

Q.) What is Java Map Interface?

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys.
Map is useful if you have to search, update or delete elements on the basis of key.

Q.) What is Java HashMap class and how it works internally?

  • A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
Internally works of HashMap
  • There is an Entry[] array called table which has size 16. 
  • This table stores Entry class's object. HashMap class has a inner class called Entry.This Entry have key value as instance variable. 
Lets see structure of entry class Entry Structure.
  1. static class Entry implements Map.Entry  
  2. {  
  3.         final K key;  
  4.         V value;  
  5.         Entry next;  
  6.         final int hash;  
  7.         ...//More code goes here  
  8. }   
Whenever we try to put any key value pair in hashmap, Entry class object is instantiated for key value and that object will be stored in above mentioned Entry[](table). Now you must be wondering, where will above created Entry object get stored(exact position in table). The answer is, hash code is calculated for a key by calling Hashcode() method. This hashcode is used to calculate index for above Entry[] table.

Points to note -
·                     HashMap works on the principal of hashing.
·                     HashMap uses the hashCode() method to calculate a hash value. Hash value is calculated using the key object. This hash value is used to find the correct bucket where Entry object will be stored.
·                     HashMap uses the equals() method to find the correct key whose value is to be retrieved in case of get() and to find if that key already exists or not in case of put().
·                     Hashing collision means more than one key having the same hash value, in that case Entry objects are stored as a linked-list with in a same bucket.
·                     With in a bucket values are stored as Entry objects which contain both key and value.
·                     In Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached while storing values. This improves the worst case performance from O(n) to O(log n)

Java LinkedHashMap class

  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap instead maintains insertion order.

Java TreeMap class

  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.

Q.)What is difference between HashMap and TreeMap?

HashMap
TreeMap
1) HashMap can contain one null key.
TreeMap can not contain any null key.
2) HashMap maintains no order.
TreeMap maintains ascending order.



Java Hashtable class

  • A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.

Q.) What is difference between HashMap and Hashtable?

HashMap
Hashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.
Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.
Hashtable is a legacy class.
4) HashMap is fast.
Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.
Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.
Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.
Hashtable inherits Dictionary class.

Q.)What is the difference between Comparable and Comparator?

Comparable and Comparator both are interfaces and can be used to sort collection elements.
But there are many differences between Comparable and Comparator interfaces that are given below.
Comparable
Comparator
1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc.
Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
2) Comparable affects the original class i.e. actual class is modified.
Comparator doesn't affect the original class i.e. actual class is not modified.
3) Comparable provides compareTo() method to sort elements.
Comparator provides compare() method to sort elements.
4) Comparable is found in java.lang package.
Comparator is found in java.util package.
5) We can sort the list elements of Comparable type by Collections.sort(List) method.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.

 

Q.) What is the difference between ArrayList and Vector?

ArrayList
Vector
1) ArrayList is not synchronized.
Vector is synchronized.
2) ArrayList increments 50% of current array size if number of element exceeds from its capacity.
Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
3) ArrayList is not a legacy class, it is introduced in JDK 1.2.
Vector is a legacy class.
4) ArrayList is fast because it is non-synchronized.
Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
5) ArrayList uses Iterator interface to traverse the elements.
Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

Q.) What is singleton class?


Some basics rules required to implement a singleton class
  • Constructor should be private
  • Declare a static variable object of the class
  • Declare a static method to return the instance
To ensure the class has only one instance, we mark the constructor has private. So, we can only instantiate this class from within the class.
 
We create a static variable that will hold the instance of the class.
 
Then, we create a static method that provides the instance of the singleton class. This method checks if an instance of the singleton class is available. It creates an instance, if its not available; Otherwise, it returns the available instance.
We can add synchronized keyword to the getInstance method signature and it would make the method synchronized. So, only one thread can access it at a time.

public class SingletonClass {
     private static SingletonClass instance=null;

     private SingletonClass() {
         
     }

     public static synchronized SingletonClass getIntance() {
          if (instance == null) {
              instance = new SingletonClass();
          }
          return instance;
     }
}

Or
public class Singletone {
     private static Singletone instance=new Singletone();
    
     private Singletone(){
         
     }
     public static synchronized Singletone getInstance(){
          return instance;
     }}



Q. )What is the difference between notify() and notifyAll()?

The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

Q.) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.
No.
Iterator
ListIterator
1)
Iterator traverses the elements in forward direction only.
ListIterator traverses the elements in backward and forward directions both.
2)
Iterator can be used in List, Set and Queue.
ListIterator can be used in List only.

Q.) What is the difference between Iterator and Enumeration?

No.
Iterator
Enumeration
1)
Iterator can traverse legacy and non-legacy elements.
Enumeration can traverse only legacy elements.
2)
Iterator is fail-fast.
Enumeration is not fail-fast.
3)
Iterator is slower than Enumeration.
Enumeration is faster than Iterator.

Q.)What is the advantage of Properties file?

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

Q.) What is volatile keyword?
The volatile keyword cannot be used with method or class & it can only be used with variable.
Volatile keyword in java guarantees that value of the volatile variable will always be reads from main memory & not from thread local cache.

Q.) Can you explain internal working of ConcurrentHashMap in java?

ConcurrentHashMap uses concept of Segments to store elements. Each Segment logically contains an HashMap. ConcurrentHashMap does not lock whole object , it just lock part of it i.e. Segment.
Structure of Segment:
  1.  /** 
  2.      * Segments are specialized versions of hash tables.  This 
  3.      * subclasses from ReentrantLock opportunistically, just to 
  4.      * simplify some locking and avoid separate construction. 
  5.      */  
  6. static final class Segment<k> extends ReentrantLock implements Serializable {  
  7.  /** 
  8.       * The per-segment table. 
  9. */  
  10.         transient volatile HashEntry<k>[] table;  
  11. // other methods and variables  
  12. }   
It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap. static final class HashEntry {         final K key;         final int hash;         volatile V value;         final HashEntry next; }

Q.) Are you aware of Daemon Thread in Java?

Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
Q.) Explain the importance of hashCode() and equals() method ? Explain the contract also ?

HashMap object uses Key object hashCode() method and equals() method to find out the index to put the key-value pair. If we want to get value from the HashMap same both methods are used . Somehow, if both methods are not implemented correctly , it will result in two keys producing the same hashCode() and equals() output. The problem will arise that HashMap will treat both output same instead of different and overwrite the most recent key-value pair with the previous key-value pair.
Similarly all the collection classes that does not allow the duplicate values use hashCode() and equals() method to find the duplicate elements.So it is very important to implement them correctly.

Contract of hashCode() and equals() method

a.  If  object1.equals(object2) , then  object1.hashCode() == object2.hashCode() should always be true.

b. If object1.hashCode() == object2.hashCode() is true does not guarantee object1.equals(object2)
Q.) Tell me 5 features introduced in JDK 1.8? 
This is the follow-up question of the previous one. Java 8 is path breaking release in Java's history, here are the top 5 features from JDK 8 release

  • Lambda expression, which allows you pass an anonymous function as object.
  • Stream API, take advantage of multiple cores of modern CPU and allows you to write succinct code.
  • Date and Time API, finally you have a solid and easy to use date and time library right into JDK
  • Extension methods, now you can have static and default method into your interface
  • Repeated annotation, allows you apply the same annotation multiple times on a type
Q.) Tell me 3 features introduced on JDK 1.7? 
This is one of the good questions I ask to check whether the candidate is aware of recent development in Java technology space or not. Even though JDK 7 was not a big bang release like JDK 5 or JDK 8, it still has a lot of good feature to count on e.g. try-with-resource statements, which free you from closing streams and resources when you are done with that, Java automatically closes that. Fork-Join pool to implement something like the Map-reduce pattern in Java. Allowing String variable and literal into switch statements. Diamond operator for improved type inference, no need to declare generic type on the right-hand side of variable declaration anymore, results in more readable and succinct code. Another worth noting feature introduced was improved exception handling e.g. allowing you to catch multiple exceptions in the same catch block.



Q.) Thread yield() method in java?

The java.lang.Thread.yield() method causes to temporarily pause the currently executing executing and allow other threads to execute whose having same priority.
Method signature of yield() method
public static  native void  yield()

=====================================================================

Data Transfer Objects (DTO)
Are simple POJOs for the purpose of transporting data around between software sub-system interfaces. The DTOs do not have any behavior other than storage and retrieval of its data.
Purpose is for data transfer.
It is a bunch of data, not necessarily coherent
No behavior
One of the reasons for DTOs in a J2EE system are that Entity beans are not serializable. Another reason is that the domain model and the data being presented to the view is not necessarily the same structures.
Value Objects (VO)
Are domain driven entities that know how to define themselves; they make implicity concepts explicit. Value objects in DDD (Domain Driven Design) do validation on the data being passed in. For instance a phone number might be used in a DTO as a String but in a  VO it will be a PhoneNumber type.
Purpose is for domain representation
High data coherence
Rich behavior
Domain Model (DOM)
Is the relationships between different entities in the system. In J2EE systems these are the Entity Beans that have a one to one mapping with tables in persistent storage. The domain model documents the key concepts and the vocabulary of the system being modeled. This can be applied at many levels; the DTOs, the value objects, the business objects and the persistent objects. In simpler systems often the domain model can do double duty as both the business objects and the persisted entities. In more complex systems these layers need to be broken into different tiers.
Purpose is for domain representation of business concepts
Often in systems domain model for the business objects and the data access layer are one and the same and are defined as Entity Beans or objects in the ORM that directly map to the database schema. In these instances the system has effectively outgrown that architecture and needs two levels added to it; a DTO layer and a Value Object layer.
Database to (Entity Beans) to Stateless Session Beans to(VOs) to Webservices/Remote Interfaces to (DTOs) toother systems such as the view
Data Transfer Object Design
The DTOs are simple storage and do nothing other than transfer data across sub systems. This means they need to match the data requirements of the requesting and receiving systems exactly. For instance the view may request or respond with Credit Card;

public class CreditCardDTO {
     public String cardType;
    public String cardNumber;
    public String ccv;
    public String nameOnCard;
    public String expirationMonth;
    public String expirationYear;
 }

In this instance they are strings as there is no need to describe the data, or do anything complex with the data in a DTO. This would be passed through either the webservices or the remote interfaces to the business logic tier where it would be converted into a value object.
Value Object Design
The VOs are representational of the vocabulary in the domain model and carry the assumptions and behavior inherent in that. Continuing with the Credit Card, when it is changed into a Value Object it will look like:

public class CreditCardVO {
     public CreditCardType creditCardType;
    public CreditCardNumber creditCardNumber;
    public CreditCardCCV creditCardCCV;
    public String nameOnCard;
    public ExpirationDate expirationDate;
 }

The CreditCardVO is composed of other value objects such as the CreditCardNumber. This does validation on the credit card number that is stored in the DTO as a string and then transmits whether it really is a credit card number to the webservice or remote interfaces quickly whether it is or not.

public class CreditCardNumber {
     private String creditCardNumber;
     public CreditCardNumber(CreditCardType type, String creditCardNumber)
        throws ValidationException {
         if (creditCardNumber==null) {
            throw new ValidationException("No credit card number present.");
        }
         if (type==CreditCardType.VISA) {
             if (!Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$").matcher(this.creditCardNumber).matches()) {
                throw new ValidationException("Not a VISA credit card.");
            }
        }
         this.creditCardNumber = creditCardNumber;
    }
     public String getCreditCardNumber() {
        return this.creditCardNumber;
    }
 }

While this is a bit clunky with a lot of logic present in the constructor that can be refactored it is a good example of dealing with the issue. From this structure a credit card value object knows how to be a credit card number.
Domain Model Design
The business logic tier passes the value objects to the Entities to be transformed into persistent objects in the data store. A credit card value object will be absorbed by a CreditCardProfile Entity Bean and then persisted.

@Entity
public class CreditCardProfile {
     @Id
    private long id;
     @Column
    private String nameOnCard;
     @Column
    private String creditCardNumber;
     @Column
    private Date expirationDate;
 }



Warm regards,

Ramjeet Mahto

No comments:

Post a Comment