Wednesday, 28 June 2017

Question: What benefits of oops?
Answer:
1. Re usability
2. Inheritance
3. Data Hiding
4. Solution based on real life entity
5. Maintainability
6. Upgradeable.

Question: Can you explain OOPs.
Answer:
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Question: What is Dynamic polymorphism?
Answer :

class A {
 method()
}
class B extends A{
   method() 
} 
class Main{
psvm(){
   A a = new B(); //Creating the Instance of child class
   a.method() ; //It will call the method from child    
} 
}
Question : What will happen if we delete the method from Class B
Answer : Then method in class A will be called.

Question : If the method from class A is deleted then what will happen?
Answer : Compilation error as there is no method in class A.

Question : Is it possible to extend a class which has private constructor?
Answer :   No, It canot be as Object creation won't able to find the super constructor.

Question: Does constructor return any value?
Answer:yes, that is current class instance (You cannot use return type yet it returns a value).

Question :What is Co variant Return Type?
Answer : The co variant return type specifies that the return type may vary in the same direction as the subclass.Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

class A{
   public HashSet<String> get(){
          System.out.println("Returning A");
          return new HashSet<String>();
   }
}

class B extends A{
   public LinkedHashSet<String> get(){
          System.out.println("Returning B");
          return new LinkedHashSet<String>();
   }
}



As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.


Question : How to use Class.forName to create the instance?
Answer :    

          try {
            Class.forName("com.scjp.classes.covariant").newInstance();
          } catch (IllegalAccessException     e ) {
          }
          catch (ClassNotFoundException e ) {
          }
          catch (InstantiationException e ) {
          }



Question: Why we have to override both equals and hashcode, if we want to override one of them either equals or hashcode what will happen?

Question:can we declare a class as private or protected?
Answer : No for the normal classes but yes for the inner classes. 

Question: How can we create immutable class in java ?
Answer: We can also create immutable class by creating final class that have final data members as the example given below:
public final class Employee{
final String pancardNumber;

public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}

public String getPancardNumber(){
return pancardNumber;
}

} 

What do you understand by final value?

Answer: FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived.

Question : Can we create setter method for the final variable?
Answer : No

Question : Can we create setter method for the static final variable?
Answer : No
Question : What are the diff option for initializing the final variable?
Answer : Following are the option to initialize the final variable
Initialize it inline i.e. at the time of declaration.
Initialize it in the constructor. 
Initialize in the non-static block. 
Question : What are the diff option for initializing the static final variable?
Answer : Following are the option to initialize the final variable
Initialize it inline i.e. at the time of declaration.
Initialize in the static block.
Question : Can we declare a constructor as final?
Answer : No.

Question : How can we create singleton class?
Answer :

public class Singleton {


   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}

Question: what is the class variables ?
Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 

Question: What is the difference between the instanceOf and getclass, these two are same or not ?
Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use
if(o.getClass().getName().equals("java.lang.Math")){ }

This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can.
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two.

Interface one{
}

Class Two implements one {
}
Class Three implements one {
}

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}
} 

Question :Which type are check instanceof operator whether the reference type or object type?
Answer : it's just check for object comparison,  look at the below code for more understanding,

 Integer x = new Integer(1);      
         if(x instanceof Integer){}
         //compilation fails
         //if(x instanceof int){}
         //compilation fails
         if(1 instanceof Integer){}
         Integer y = 10;
         //Compilation success
         if(y instanceof Integer){}
         //compilation fails
         if(y instanceof int){}
         int z =10;
         //Compilation fails, as one of the operand is not a object
         //i.e z is of primitive type
         if(z instanceof Integer){}
        
         int[] w = {10};
         //compilation success as below int[] is nothing but the Object so it works
         if(w instanceof int[]){}

           
Question:What are the restrictions while overriding.
Answer :  List of restrictions are as follows

The Return type should be same.
The Argument type and Order should be same.
The overriding method cannot be less visible than the method it overrides. i.e., a public method cannot be override to private.
The overriding method may not throw any exceptions that may not be thrown by the overridden method i.e. the method should either not throw any exception or if it is throwing then the given exception should be either same in child/subclass of it. 
Question : Can we declare the method as static having the same name in super class?
Answer : not it's not possible, we will get an error, saying "This static method cannot hide the instance method from StaticParent". The reason could be at the run time it may be confusing weather we want to access static method or super class method, as it is very much legal to call the static method using the reference of the class.

Question : What is the difference between an abstract class and an interface?
Answer : An abstract class can be partly finished so that the child class can fill in appropriate missing info. An interface simply demands that an implementing class to implement a certain behavior, leaving it up to the implementing class as to how this is to be done. Neither interface or abstract classes can be instantiated.

An abstract class can contain both non-abstract methods (methods with a body) and abstract methods (methods without a body).
An interface only contains abstract methods.

A class can implement multiple interfaces, but can only subclass one abstract class.

An abstract class can have instance variables and instance initializers.
An interface cannot.

Any variables defined in an interface are implicitly public, static, and final (the variables of an interface are final they must be initialized).

An abstract class can define constructor. An interface cannot.

An abstract class can have public or protected methods. An interface can have only public methods.
An abstract class inherits from Object and includes methods such as clone() and equals().

Question : Can we declare abstract method private  in abstract class?
Answer : No we can not, we will get the compilation error "can only set a visibility modifier, one of public or   protected", hence we canot declare the method as private.

Question : Can we declare static abstract method in abstract class?
Answer : No we can not, we will get the compilation error "can only set a visibility modifier, one of public or   protected", hence we canot declare the method as private.

What is protected variable or method and from where it can be accessed?
Answer : The protected variable/method can be accessed, from the same class where it is declared, then same package and then the child class either in the same package or other package.

Question : What will happen if we declare the constructor as protected?
Answer : The object can be instantiated in the classes which belong to the same package, in which class is declared, but it cannot be instantiated in the classes which are in another package even though if they extends the class having protected constructor as the constructors are not part of the inheritance.

enum

Question : Diff between class and enum?
Answer : Following are the Diff between Class and Enum
In enum only toString() can be overridden but in class all methods from java.lang.Object.can be overridden.
enum can't be clone but class can be.
enum can only have private constructor but class can have private, protected and public.
No object can be created using the new operator for Enum but we can create object for the class.
Question : What are the similarity between class and enum.   
Answer : 
Both have constructor
Both are having variables with all kind of access specifier, like public protected and private.
Both have regular methods which can be use to get the information for the member variable and can also be used to manupulate them.
Question : Can we have overloaded constructor in enum?
Answer : Yes it's possible, find the below example.
public enum DirectEnum {
    ABC,CDE,EFG("narendra");
    private DirectEnum(){
        
    }
    private DirectEnum(String name){
        this.name= name;
    }
    private String name;
    private static String staticname= "narendra";
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return super.toString();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

  
Question : From the example there is setter method if we call the setter method like as follows then will it affect,         
                  DirectEnum.EFG.setName("vijay");
                  System.out.println(DirectEnum.EFG.getName())
 Answer : Yes it will display the name as "vijay" rather than "vikash".

http://java67.blogspot.in/2012/09/difference-between-overloading-vs-overriding-in-java.html

Question :  Can we call super() and this() in the same constructor?
Answer : No, we cannot we will get the following error "Constructor call must be the first statement in a constructor".
class TestClass {
        TestClass(){
                super();
                this(); XXXXXXX
        }
        TestClass(int i){
        }
    public static void main(String args[] ) throws Exception {
        new TestClass(1);
        System.out.println(10 >> 1);
    }
}



Question : Can we call this() in the default constructor i.e. non argument constructor?
Answer : No, It is not allowed and if we try to do that we will get the compilation error, "Recursive constructor invocation TestClass()".
class TestClass {
        TestClass(){
                this();XXXXXX
        }
        TestClass(int i){
        }
    public static void main(String args[] ) throws Exception {
        new TestClass(1);
        System.out.println(10 >> 1);
    }
}



Question :  Can we call this() in the non default or argument constructor?
Answer : yes that is very much legal.

Question : Can we create the same object of the same type in the constructor?
Answer : we can do that but if we try to invoke the constructor using new operator inside the default constructor then we will get stack overflow error, but if it is non default constructor call using new operator then it will be fine.
class TestClass {
        TestClass(){
                new TestClass();
        }
        TestClass(int i){
                this();
        }
    public static void main(String args[] ) throws Exception {
        new TestClass();
        System.out.println(10 >> 1);
    }
}

Output
Exception in thread "main" java.lang.StackOverflowError
 at TestClass.<init>(TestClass.java:10)
 at TestClass.<init>(TestClass.java:10)

But below is fine
class TestClass {
        TestClass(){
                new TestClass(1);
        }
        TestClass(int i){
        }
    public static void main(String args[] ) throws Exception {
        new TestClass(1);
        System.out.println(10 >> 1);
    }
}


  
Static

Question : Is static block allowed in the constructor?
Answer : No.

Question : Is static block allowed in the non static method?
Answer : No.

Question : Can we access static method and variable in the constructor.
Answer :  Yes that is very much possible.

Question: Class.forname does?
Answer : load the class in JVM and also execute any static block available in class.

Question : Is Any method/variable declared in the static block accessible outside that block?
Answer : No

Question: Can we use non static variable in static method?
Answer : No.

Question: What is static import can we static import methods also?
Ansswer : static import will import all the static variable and method in the class if we end with the class name, e.g. import static java.util.Calender.* will include all the static varible in the imported class, hence we need not have to use the className.static method name.

Question : Can we call public or protected static variable from the child class?
Answer : Yes
 

Question : What will happen if the parent class method is having non static method and child class is having the static method.
Answer : We will get the compilation error as "This static method cannot hide the instance method from StaticParent".

Question : What will happen if the parent class method is having static method and child class is having the non static method.
Answer : We will get the compilation error as "This instance method cannot override the static method from StaticParent".

Question: Can we override static method?
Answer: Theoretically no but we can override static methods but it is not called overriding, It is called "method Hiding". Based on the class the method will be invoked, if there is no static method in child class then method from the super class will be called. All the default rules of overriding applies in case of static also like 1)Argument Rules 2) Return type rules 3) Throw Exception rules.
Additionally You can not make child method non static and keep parent method static and vice versa.

Question: Can we override static final method?
Answer: No, even the static method follows all the overriding rules, so similar to the instance method which is declared as the final, cannot be overridden, hence the static method declared as the final is also not allowed to be overridden. 

Question: Why we cannot override static method?
Answer: It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

Question:What is the difference between static block and normal block.     
Answer:  One main difference is when we create an object of the class then normal block is called and when the class is loaded for the first time then static block is called.
So that this concludes the static block is called only once but normal block can be called multiple times as an when constructoris called. 

Question: What is the difference between class variable, member variable and automatic(local) variable 
Answer: class variable is a static variable and does not belong to instance of class but rather shared across all the instances member variable belongs to a particular instance of class and can be called from any method of the class
automatic or local variable is created on entry to a method and has only method scope

Question: When are static and non static variables of the class initialized
Answer: The static variables are initialized when the class is loaded Non static variables are initialized just before the constructor is called.

Question: Why is the main method static 
Answer: So that it can be invoked without creating an instance of that class.
Question: Why do we need public static void main(String args[]) method in Java
Answer: We need
·         public: The method can be accessed outside the class / package
·         static: You need not have an instance of the class to access the method
·         void: Your application need not return a value, as the JVM launcher would return the value when it exits
·         main(): This is the entry point for the application
If the main() was not static, you would require an instance of the class in order to execute the method.
If this is the case, what would create the instance of the class? What if your class did not have a public constructor?

Question : What is the order in which static variable, static block and main method executed.
Answer : They will be executed in the same order in which they are declared, only thing is the main method is executed at the end, so even though we have declared few static block after the main method declaration, but irrespective of the order of declaration they will be executed first before the main method.
 
Question : How many types of memory areas are allocated by JVM?
Answer : Many types:
·         Class(Method) Area
·         Heap
·         Stack
·         Program Counter Register
·         Native Method Stack

String & StringBuilder

Question:Why string objects are immutable in java?
Answer: Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Question:Which classes in java are immutable?
Answer :  All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger. 

Question: Why java uses the concept of string literal?
Answer: To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

Question : Demonstrate the StringPool with the program.
Answer :  
public class StringMemoryCheck {
       public static void main(String[] args) {

              String s1 = "Cat";
              String s2 = "Cat";
              String s3 = new String("Cat");
              // equality Check from the String Pool ref
              System.out.println("s1 == s2 :" + (s1 == s2));
              // equality check from the String pool and heap space as s1 is in String
              // pool and s3 is created in heap space
              System.out.println("s1 == s3 :" + (s1 == s3));
              // equality Check from the String Pool ref, intern force the content of
              // the s3 to go to the String pool and
              // return the ref location from the String pool
              System.out.println("s1 == s3 :" + (s1 == s3.intern()));
              // As there is no change for the s3 so this still return false.
              System.out.println("s1 == s3 :" + (s1 == s3));

       }
}


  

s1 == s2 :true
s1 == s3 :false
s1 == s3 :true
s1 == s3 :false


List<String> list = new ArrayList<String>(){{
      add("vikash");
      add("vikash");
      add("vikash");
      add("vikash");
      add("vikash");
      add("vikash");
      add("vikash");
 }
};
             
System.out.println(list.get(0) == list.get(1));
System.out.println(list.get(1) == list.get(2));
System.out.println(list.get(2) == list.get(3));



Output
true
true
true
//Reason is all the ”vikash” is going to String Pool so == check will able to succeed as the memory location for all the “vikash” is same.


·        

Question: How many objects will be created in the following code?
String s = new String("Welcome");
Answer: Two objects, one in string constant pool and other in non-pool(heap).

Question: Is "abc" a primitive value?
Answer: The String literal "abc" is not a primitive value. It is a String object. 
·         Question: For concatenation of strings, which method is good, StringBuffer ,StringBuilder or  String?
·         Answer: StringBuilder is faster than String for concatenation.
·        
Question: What would you use to compare two String variables - the operator == or the method equals()? 
·         Answer:  I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
·        
Question: To what value is a variable of the String type automatically initialized?
Answer: The default value of an String type is null.

Question: What is the difference between the String and StringBuffer classes?
Answer: String objects are constants. StringBuffer objects are not. 
·         CASE_INSENSITIVE_ORDER :  its comprator can be used for sorting a list of String in the case insensitive way, we can use utility method of class Collections.getSortedList.
·         chartAt : returns the character at the specified index position.
·         compareTo : compare two strings and returns if they equal, greater than and less than.
·         compareToIgnroreCase : compare two strings without caring about cases and returns if they equal, greater than and less than.
·         endsWith : check if the given string is ends with the passed String.
·         getChars : copy the character from the specified starting position to specified ending position, to a character array.
·         lastIndexOf : find the last occurrence of passed character
·         StringBuilder Class
·         Capacity : It will return the current capacity of the StringBuilder Object.
·         charAt : similar to string.
·         delete :  delete the contents from the starting index to ending index.
·         deleteCharAt : delete the character a specified index.
·         ensureCapacity : It will try to ensure minimum capacity, it is good practice to use it when, we that approximately how much will be data needed to be stored inside the StringBuilder object, so there is no need to assign additional space when it reaches to the maximum limit.
·         insert : insert a character at the specified location.
·         lastIndexOf : similar to string.
·         replace : It will replace entire area, i.e. starting index till ending index with the specified String, e.g. if we have String "vikash chandra Mishra" we pass (7,14,"kumar") then we will have outcome as, "Vikash Kumar Mishra"
·         reverse : it will reverse the character sequence.
·         setCharAt : It will replace the character at specified position with the passed character, taking same example as earlier outcome of setCharAt(2,'l'); = "Vilash Chandra Mishra".
·         subsequence: return the charsequence object, from start index to end index, only diffrence from the substring method, is substring method will return string data type object but this one return charsequence data type object, with the same set of chracter provided start and end index are same.
·         trimToSize : it will try reduce the capacity of the StringBuilder object, capacity is useually greater than the actual length of stringbuilder object to avoid the frequency to assign addtional space when it runs out of it, but this method will kick of addtional space taken by the object and try to assign it what is good enough to hold the required data, hence if we run the trimtosize method then outcome of the method capacity and length will be same.
·         setLength : Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character '\u0000'. In other words, if the newLength argument is less than the current length, the length is changed to the specified length.
·        
Question : What will happen if we pass the negetive number to the  setLength method of StringBuilder?
Answer : It will throw indexOutOfBound Exception.

Question : What will happen if we pass 0 to setLength to the StringBuilder class.
Answer : It will empty the StringBuilder Object.

Question: How is it possible for two String objects with identical values not to be equal under the == operator?
·         Answer: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. 
·         Question: What happens when you add a double value to a String?
Answer: The result is a String object. 
·        
Question: How to convert String to Number in java program?
·         Answer: The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String strId = "10";
·         int id=Integer.valueOf(strId);
·        
Question :  How to sort list of strings - case insensitive? 
·         Answer : using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Question : How to convert a String to character Array? 
·         Answer : Call the toCharArray().

Question : List out few constructor with the example.
·         Answer :


      String s = "vikash chandra mishra";
        System.out.println(s);
        
        String sa = new String(new char[]{'v','i','k','a','s','h'});
        System.out.println(sa);
        
        String sb = new String(s);
        System.out.println(sb);
        //Pick the characters from the index i.e. 2 and 3 characters from the index will be used to create
        //a new Object
        String sc = new String(new char[]{'v','i','k','a','s','h'},2,3);
        System.out.println(sc);

Output : 

vikash chandra mishra
vikash
vikash chandra mishra
kas




Question : What is Concat method?
Answer : Concat method will concatinate two String and return the concatinated string, but the original String will remain untouched i.e. no changes on any of the string.

Question : What is the diff between charSequence and String?
Answer : charSequence is interface and String is class, the String class is implementing the charSequence, other classes which has implemented the charSequence are

·         StringBuilder
·         StringBuffer
·         CharBuffer
·         Segment

Method needs to be implemented by those classes are

·         length()
·         charAt()
·         toString()
·         subSequence() 
Question : What is the diff between String's equals and matches method?
Answer : Equals check wether the given string is exactly equal to the passed string, but matches will look weather the regular expression passed as an argument is matches with the given String.

Question : What is intern method?
Answer :Returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.When the intern method is invoked, if the pool already contains a string equal to this Stringobject as determined by the 
equals(Object) method, then the string from the pool is returned. Otherwise, this Stringobject is added to the pool and a reference to this String object is returned.It follows that for any two strings s and t,s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification. 
Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.


Question : What is String.format()?
Answer : Returns a formatted string using the specified format string and arguments.The locale always used is the one returned by Locale.getDefault().
Parameters: 
format A format string 
args Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a null argument depends on the conversion.
Returns:A formatted string.
pre style="background:#042029;color:#839496">public static void main(String[] args) { double d = 12345454.3456; int i = 12345454; String s = "abc"; System.out.println(String.format("%,.3f%n", d));//show last 3 decimal point and also do the round operation System.out.println(String.format("%10d", i)); //just show the integer and add space if the total output is less than 10 characters System.out.println(String.format("%S", s)); //upper case the characer System.out.println(String.format("%s", s));//show the sring }


Question : What is the output of the following code.
Integer integer = 123456;
System.out.println(new StringBuilder(integer).reverse());
Answer : output will be blank, reason is StringBuilder(int capacity) constrcutor will create StringBuilder with the initial capacity of 123456 length, it will not add 123456 into the StringBuilder.
Question : How to reverse a Number?
Answer :  Following is way to reverse a number.
Integer integer = 123456;
Integer reverseInteger = 
                         Integer.parseInt(new StringBuilder(String.valueOf(integer)).reverse().toString());
OR 

StringBuffer sb = new StringBuffer();
System.out.println(sb.append(123456).reverse());;




Question : How to convert a number to binary?
Answer : We can use utility method from Integer class toBinary(), but it is asked to write a program then following is the example.
     int i = 15;
        while(i>0){
            System.out.print(i%2);
            i=i/2;
        }
if it is asked to do the same in the recusrsion then following is the code.
static void toBinary(int i){
        if(i>0){
            toBinary(i/2);
        }
        if(i!=0){
            System.out.print(i%2);
        }        
    }





Question : Why strBuilder_1.equals(strBuilder_2) return false, even though they have same content?
Answer : Reason is StringBuilder has not overridden the equals method, it has just inherited from the Object Class so, equality check will be based on the memory location hence it won't able check if the content are similar.

What is the difference between String.valueOf() and toString() in Java?
Answer : Following is basic differance between the both the method.
String.valueOf(argument) : String.valueOf() is null safe. You can avoid java.lang.NullPointerException by using it. It returns "null" String when Object is null. Let explore the source code of String.valueOf().


toString():toString() can cause the java.lang.NullPointerException. It throws java.lang.NullPointerException when Object is null and also terminate the execution of program in case its not handled properly.

Question : What is the best way to compare a StringBuilder and String?
Answer : contentEquals

Question : What is the difference between equals and contentEquals?
Answer : The String#equals() not only compares the String's contents, but also checks if the other object is also an instance of a String. The String#contentEquals() methods only compares the contents (the character sequence) and does not check if the other object is also an instance of String. It can be anything as long as it is an implementation of CharSequence or an instance of StringBuffer.



Generic
Question : What is type erasure?
Answer : Generics have been available in Java since J2SE 5.0 was released in 2004. Generics allow for parameterised types — for example, an instance of the Vector class can be declared to be a vector of strings (written Vector) — and hence allow the compiler to enforce type safety. To avoid major changes to the Java run-time environment, generics are implemented using a technique called type erasure. This is equivalent to removing the additional type information and adding casts where required.



public static void main(String[] args) {       
              List<String> list = new ArrayList<>();         
              list.add("1");
              //Below it gets the list of Integer
              list = find(list);  
              //Above no exception is thrown till now, so no runtime check if the returned object
              //Compatible or not?
              //We will get the error if we try to iterate like following
              //THe exception thrown Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
              //at core.HelloWorld.main(HelloWorld.java:17)
              for(String s : list){
                     System.out.println(s);
              }
       }
       /**
        * Returning Integer list of Integer by creating non parameterized list
        */
       static List<String> find(List<String> list){
              List listw = new ArrayList<>();
              listw.add(1);
              listw.add(2);
              listw.add(3);
              listw.add(4);
              return listw;
       }

Calendar Class

Question: What is the GregorianCalendar class?
Answer: The GregorianCalendar provides support for traditional Western calendars.

Question : How will create the Calendar Object?
Answer : Calendar c = new GregorianCalendar();

Question : How to know if any year is leap year?
Answer : calandarInstace.isLeapYear();

Question : How can we change the date from today to next week same day.
Answer : We can use the roll(WEEK, 7), WEEK is the date class.
 
Data Type / Operators /Keywords

Question : What is the output of the below code?
        Integer i3 = 1;
        Integer i4 = 1;
        Integer i5 = 300;
        Integer i6 = 300;
        System.out.println(i4==i3);
        System.out.println(i5==i6);

Answer : For first line it's true and for the second line it's false.

Question : Give the reason for the above output.
Answer: Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10
or
Integer myNumber = Integer.valueOf(10);

256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer.
So
Integer i3 = 1;
and
Integer i4 = 1; will be created in the IntegerCache but 300 which is not in the range of -128 to 127 is created outside the cache hence have different memory location, so == comparison fails for the 300 but it's fine for the 1.

Question : Similar to IntegerCache what are the other wrapper classes does the similar activity?
Answer : The other wrapper classes (Byte, Short, Long, Character) also contain this caching mechanism. The Byte, Short and Long all contain the same caching principle to the Integer object i.e. range from -128 to 127. The Character class caches from 0 to 127. The negative cache is not created for the Character wrapper as these values do not represent a corresponding character. There is no caching for the Float object.
Hence
Float i7 = 1F; 
Float i8 = 1F;
System.out.println(i7==i8);//false as there is no maintainance of the Float Cache, make sense we cannot predict the usual numbers for the Float/Double.

Question : How to covert a Integer to binary?
Answer : In Integer class we have one utility method called, toBinary(), it can be used to convert to binary string.

Question: Is null a keyword?
Answer:  The null value is not a keyword.

Question: How does Java handle integer overflows and underflows? 
Answer: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Question: What is the difference between the >> and >>> operators?
Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

Question: How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Answer: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Question: Is sizeof a keyword?
Answer: The sizeof operator is not a keyword.


Question: What are order of precedence and associativity, and how are they used?
Answer: Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left


Question: What is the catch or declare rule for method declarations?
Answer: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

Question: What is the difference between the Boolean & operator and the && operator?
Answer: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. 
Question: What is transient variable?
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: Can transient variables be declared as 'final' or 'static'?
Answer : Java's serialization provides an elegant, and easy to use mechanism for making an object's state persistent. While controlling object serialization, we might have a particular object data member that we do not want the serialization mechanism to save.

The modifier transient can be applied to field members of a class to turn off serialization on these field members. Every field marked as transient will not be serialized. You use the transient keyword to indicate to the Java virtual machine that the transient variable is not part of the persistent state of an object.

The transient modifier applies to variables only.

Like other variable modifiers in the Java system, you use transient in a class or instance variable declaration like this:

class TransientExample {
    transient int hobo;
}

This statement declares an integer variable named hobo that is not part of the persistent state of the TransientExample class.

Java classes often hold some globally relevant value in a static class variable. The static member fields belong to class and not to an individual instance. The concept of serialization is concerned with the object's current state. Only data associated with a specific instance of a class is serialized, therefore static member fields  are ignored during serialization (they are not serialized automatically), because they do not belong to the serialized instance, but to the class. To serialize data stored in a static variable one must provide class-specific serialization.

Surprisingly, the java compiler does not complaint if you declare a static member field as transient. However, there is no point in declaring a static member field as transient, since transient means: "do not serialize", and static fields would not be serialized anyway.

On the other hand, an instance member field declared as final could also be transient, but if so, you would face a problem a little bit difficult to solve: As the field is transient, its state would not be serialized, it implies that, when you deserialize the object you would have to initialize the field manually, however, as it is declared final, the compiler would complaint about it.

For instance, maybe you do not want to serialize your class' logger, then you declared it this way:

private transient final Log log = LogFactory.getLog(EJBRefFactory.class);

Now, when you deserialize the class your logger will be a null object, since it was transient. Then you should initialize the logger manually after serialization or during the serialization process. But you can't, because logger is a final member as well.
Question : What is variable hiding and shadowing?
Answer: In Java, there are three kinds of variables: local variables, instance variables, and class variables. Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed.

Question : Can private method be overridden?
Answer: The private methods are not inherited by subclasses and you cannot be overridden by subclasses. According to Java Language Specification (8.4.8.3 Requirements in Overriding and Hiding), "Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass."
What does it mean? It means you can have a private method has the exact same name and signature as a private method in the superclass, but you are not overriding the private method in superclass and you are just declaring a new private method in the subclass. The new defined method in the subclass is completely unrelated to the superclass method. A private method of a class can be only accessed by the implementation in its class. A subclass cannot call a private method in its superclasses.

Question: Can a double value be cast to a byte?
Answer: Yes, a double value can be cast to a byte. using the byteValue method.

Question: What is the difference between a break statement and a continue statement?
Answer: A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

Question: Can a Byte object be cast to a double value?
Answer: No, an object cannot be cast to a primitive value.

Question: If a variable is declared as private, where may the variable be accessed?
Answer: private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. An example, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not accessible to the user.

Question : Can we declare a class private or protected, and if no then what is error reported by compiler.
Answer : Illegal modifier for the class Test; only public, abstract & final are permitted.

Question: If a variable is declared as protected, where may the variable be accessed?
Answer : protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.

Question: If a variable is declared as default(i.e. no specified), where may the variable be accessed?
Answer : If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package.

Question: What is an object's lock and which object's have locks?
Answer: An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Question: When can an object reference be cast to an interface reference?
Answer: An object reference be cast to an interface reference when the object implements the referenced interface.

Question: How is rounding performed under integer division?
Answer: The fractional part of the result is truncated. This is known as rounding toward zero.

Question: What restrictions are placed on the values of each case of a switch statement? 
Answer: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

Question : What is signum method?
Answer : Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

Question: Which non-Unicode letter characters may be used as the first character of an identifier?
Answer: The non-Unicode letter characters $ and _ may appear as the first character of an identifier

Question: What is casting?
Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Question: What is the return type of a program's main() method?
Answer: A program's main() method has a void return type.

Question: What is the difference between a field variable and a local variable?
Answer: A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

  
Answer: Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

Question: To what value is a variable of the boolean type automatically initialized?
Answer : The default value of the boolean type is false.

Question: What is the difference between the prefix and postfix forms of the ++ operator?
Answer: The prefix form performs the increment operation and returns the value ofthe increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

Question: What is the purpose of a statement block?
Answer: A statement block is used to organize a sequence of statements as a single statement group.

Question: What is the difference between an if statement and a switch statement?
Answer: The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

Question: What is instanceOf operator used for
Answer: It is used to if an object can be cast into a specific type without throwing Class cast exception 

Question: How many number of non-public class definitions can a source file have A source file can contain unlimited number of non-public class definitions List primitive data types, there size and there range (min, max)
Answer: 
Data Type
Bytes
bits
min
Max
Boolean
-
1
-
-
Char
2
16
0
2^16-1
Byte
1
8
-2^7
2^7-1
Short
2
16
-2^15
2^15-1
Int
4
32
-2^31
2^31-1
Long
8
64
-2^63
2^63-1
Float
4
32
-
-
Double
8
64
-
-


Question: How is an argument passed in java, by copy or by reference
Answer: If the variable is primitive datatype then it is passed by copy. If the variable is an object then it is passed by reference.

Question: How does bitwise (~) operator work
Answer: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 coverts to 00001111

Question: What is a modulo operator %
Answer: This operator gives the value which is related to the remainder of a divisione.g x=7%4 gives remainder 3 as an answer

Question: Can shift operators be applied to float types.
Answer: No, shift operators can be applied only to integer or long types

Question: What happens to the bits that fall off after shifting
Answer: They are discarded 

Question: What values of the bits are shifted in after the shift
Answer: In case of signed left shift >> the new bits are set to zero But in case of signed right shift it takes the value of most significant bit before the shift, that is if the most significant bit before shift is 0 it will introduce 0, else if it is 1, it will introduce 1

Question: What are access modifiers
Answer: These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly

Question: Can protected or friendly features be accessed from different packages
Answer: No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package 

Question: What are the rules for primitive assignment and method call conversion
Answer: 
A boolean can not be converted to any other type
A non Boolean can be converted to another non boolean type, if the conversion is widening conversion
A non Boolean cannot be converted to another non boolean type, if the conversion is narrowing conversion
See figure below for simplicity

Question: What are the rules for primitive arithmetic promotion conversion
Answer: 
·         For Unary operators :
·         If operant is byte, short or a char it is converted to an int
If it is any other type it is not converted
·         For binary operands :
·         If one of the operands is double, the other operand is converted to double
Else If one of the operands is float, the other operand is converted to float
Else If one of the operands is long, the other operand is converted to long
Else both the operands are converted to int
Question: What are the rules for casting primitive types boolean type.
Answer: 
You can cast any non Boolean type to any other non boolean type
You cannot cast a boolean to any other type; you cannot cast any other type to a boolean

Question: What are the rules for object reference assignment and method call conversion
Answer: An interface type can only be converted to an interface type or to object. If the new type is an interface, it must be a super interface of the old type. A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type new type the old class must implement the interface. An array maybe converted to class object, to the interface cloneable, or to an array. Only an array of object references types may be converted to an array, and the old element type must be convertible to the new element.

Question: What are the rules for Object reference casting                                                                
Answer: Casting from Old types to Newtypes
Compile time rules
·         When both Oldtypes and Newtypes are classes, one should be subclass of the other
·         When both Oldtype ad Newtype are arrays, both arrays must contain reference types (not primitive), and it must be legal to cast an element of Oldtype to an element of Newtype
·         You can always cast between an interface and a non-final object
Runtime rules
·         If Newtype is a class. The class of the expression being converted must be Newtype or must inherit from Newtype
·         If NewType is an interface, the class of the expression being converted must implement Newtype
Question: What is the difference between = = and equals()?
Answer: = = does shallow comparison, It retuns true if the two object points to the same address in the memory, i.e if the same the same reference equals() does deep comparison, it checks if the values of the data in the object are same

Question: What do you understand by a variable?
Answer: The variables plays very important role in computer programming. Variables enable programmers to write flexible programs. It is a memory location that has been named so that it can be easily be referred in the program. The variable is used to hold the data and it can be changed changed during the course of the execution of the program.

Question: What do you understand by numeric promotion?
Answer: The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

Question: What are the types of casting?
Answer: There are two types of casting in Java, these are Implicit casting and explicit casting.

Question: What is Implicit casting?
Answer: Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not workout for all application scenarios.

Example:

int i = 4000;

long h = i; //Implicit casting

Question: What is explicit casting?
Answer: Explicit casting in the process in which the complier are specifically informed to about transforming the object.

long ln = 700.20;

t = (int) ln; //Explicit casting

Question: What do you understand by downcasting?
Answer: The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy.


Question: What is the output of x
Answer: When this kind of question has been asked, find the problems you think is necessary to ask before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x

Question:  How does Java handle integer overflows and underflows?
Answer: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Question:  How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Answer: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Question: How can you write a loop indefinitely?
Answer: for(;;)--for loop; while(true)--always true, etc.

Question: What is the difference between the Boolean & operator and the && operator?
Answer: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

Question: What is casting?
Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Question: Name primitive Java types.
Answer: The primitive types are byte, char, short, int, long, float, double, and boolean.

Question: Read the following program:
public class test {
public static void main(String [] args) {
  int x = 3;
  int y = 1;
   if (x = y)
   System.out.println("Not equal");
  else
  System.out.println("Equal");
 }
}



What is the result?
   A. The output is ?Equal?
   B. The output in ?Not Equal?
   C. An error at " if (x = y)" causes compilation to fall.
   D. The program executes but no output is show on console.
Answer: C
Question: What can go wrong if you replace && with & in the following code: String a=null; if (a!=null && a.length()>10) {...}
Answer: A single ampersand here would lead to a NullPointerException.

Question : What are the data types allowed for the switch case statement?
Answer : it can allow below list of data types
1. short 2. byte 3. char 4. int
Additionally we canot pass the negetive value to char
and it will not allow the
1.boolean 2. long 3. float  4. double

What are the rules of creating an array?
Rule 1 : You canot give the number of elements in the right side, even if it is more than one dimension.
example : int k[20] = new int[20]; its wrong
int k[] = new int[20]; its right
Rule 2: don't use the () for using new operator, use [] instead
rule 3 : For N dimensional array starting from first [] at least for one dimension we have to give the number of elements required
example : Integer k[][][][][] = new Integer[5][][][][];
Integer k[][][][][] = new Integer[][][][][]; wrong
Integer k[][][][][] = new Integer[][5][][][]; wrong
Integer k[][][][][] = new Integer[5][5][][][]; right

Question : Is Java is Pass by value or Pass by Referance?
Answer : Java Is always Pass by Reference when it is Object and Pass by value when it is primitive data type, additionally when we send the Object reference into a method then we are sending the internal value reference of the internal Object.

Question:Explain any design pattern apart from factory and singleton and where you have used it? 



Cloning

1) What are different types of cloning in Java?
Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning.

2) What is Shallow copy?
In shallow copy the object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.      
                                      Figure 1: Original java object obj
The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.

                                      Figure 2: Shallow copy object obj1
It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contains any other object no new reference is created.

3)  What is deep copy and how it can be achieved?
In deep copy the object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.
                                          Figure 3 : Original Object obj
When a deep copy of the object is done new references are created.

                                     Figure 4: obj2 is deep copy of obj1
One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks:
·         You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have a third-party class for which you do not have the source and which is marked final, you are out of luck.
·         You must be able to access all of the fields of the class’s superclasses. If significant parts of the object’s state are contained in private fields of a superclass, you will not be able to access them.
·         You must have a way to make copies of instances of all of the other kinds of objects that the object references. This is particularly problematic if the exact classes of referenced objects cannot be known until runtime.
·         Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain. The method must be revisited any time a change is made to the class or to any of its superclasses.

4) What is difference between deep and shallow cloning?
The differences are as follows:
·         Consider the class:
public class MyData{
String id;
Map myData;
}

The shallow copying of this object will have new id object and values as “” but will point to the myData of the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will be new id object and also new myData object and independent of original object but with same values.
Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For deep copying some extra logic need to be provided
5) What are the characteristics of a shallow clone?
 If we do
          a = clone(b);
Then,
1) b.equals(a)
2) No method of a can modify the value of b

6) What are the disadvantages of deep cloning?
Disadvantages of using Serialization to achieve deep cloning –
·         Serialization is more expensive than using object.clone().
·         Not all objects are serializable.
Serialization is not simple to implement for deep cloned object

7) Give the example of the shallow copy?
public class CloneExample implements Cloneable {
      String a;
      java.util.List<String> list = new ArrayList<String>();
      int i;
      public static void main(String[] args) throws CloneNotSupportedException{
            CloneExample ce = new CloneExample();
            ce.a = "vikash";
            ce.list.add("vikash");
            ce.i = 5;
            CloneExample ce1 = (CloneExample)ce.clone();
            System.out.println(ce1.a);
            ce1.a="vijay";
            System.out.println(ce.a);
            System.out.println(ce1.list.get(0));
            ce1.list.set(0, "vijay");
            System.out.println(ce.list.get(0));
           
            System.out.println(ce1.i);
            ce1.i = 7;
            System.out.println(ce.i);
      }
}


explanation :
??????????So what we can see that, we can clone an object if we implements cloneble.
??????????If we have refrence object, upon shallow copy they can be accessed by cloned object.
??????????This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. Shallow Copy concept is not applicable to the classes having only primitive data type members as in that case the default cloning will also result into a Deep Copy only.

In case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That's why the name Shallow Copy.But the for the primitive data type

Question : If a class A is extended by class B and class B wants to pro­vide the cloning fea­ture. Then what should the class do?
Answer : The super class A should also over­ride and pro­vide a valid clone of itself through the clone method. Class B’s clone method will invoke super.clone() and mod­ify the behav­iour of mem­ber instance vari­ables and return the proper clone.

Question : What if the parent class doesn't implements the cloneble interface?
Answer : Practically doesn't matter super classes will also become cloneable, i.e. the properties can be cloned using the clone method.

Question : Give an example of shalow cloning.

public class Test implements Cloneable{
      int a=10;
      StringBuffer str = new StringBuffer("abc");
      public void main (String args[])  throwsCloneNotSupportedException{
             Test t1 = new Test();
             Test t2 = (Test)t1.clone();
             t1.a=20;t2.a=30;
            t1.str.append("def");t2.str.append("ghi");

             System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
             System.out.println("t1.str = " + t1.str +" t2.str = " + t2.str);
      }
}


Output:
t1.a = 20 t2.a = 30
t1.str = abcdefghi t2.str = abcdefghi

Question: Give an example of deep cloning.
public class Test implements Cloneable{
      int a=10;
      StringBuffer str = new StringBuffer("abc");
      public void main (String args[])  throwsCloneNotSupportedException{
             Test t1 = new Test();
             Test t2 = (Test)t1.clone();
             t1.a=20;t2.a=30;
            t1.str.append("def");t2.str.append("ghi");
             System.out.println("t1.a = " + t1.a + " t2.a = " + t2.a);
             System.out.println("t1.str = " + t1.str +" t2.str = " + t2.str);

      }

      @Override
      protected Object clone() throwsCloneNotSupoortedException{
             Test t = new Test();
              t.str = new StringBuffer();
              return t;
      }

}

Output:
t1.a = 20 t2.a = 30
t1.str = abcdef t2.str = ghi

Question : What will happen if we clone an Array Of Primitive type?
Answer : Ideally it is a shallow copy if we do that, hence the new variable will also start pointing to the same reference location.

Question : Can we create clone of String Object?
Answer : No, that is not allowed, and also we can observe that same rule applies for other wrapper classes as well, First of all clone() method from java.lang.Object is marked as protected.
Moreover only classes that implement the Clonable interface can be cloned (as Prsanth Pilai said).
String could be cloned if it implements Clonable interface and override clone() method with public access. But designers of String class didn't do that. Why?

String class is immutable. An immutable object is an object whose state cannot be modified after it is created. Immutable can't be change so it is good idea to keep them all in a objects pool.

So all String objects are stored in String pool. Other words there is only one copy of String object that store selected value, but there could be many references to it. But there is a catch...
Only if you create them as a literal:
String a = "word literal";
String are checked if it already exist in a pool. If you create them using new operator:
String b = new String("word literal");
There will be a problem. Because we have two objects, two references and repeated value (against String desiners idea). To solve that issue you could call intern() method:
b.intern();
Then there is only one String object that store "word literal".

What does that have with clone() method?
Answer: clone() method will create new instance of object.
So designers of String would need to call intern() method inside potential clone() method.. But any call of intern() method would be less efficient, if compare it to compiler check (in case String a = "word literal";).
And that is probably reason that we don't have clone() method in String class :-).

Question : If we implement the cloneable interface, do we need to implement clone method?

Answer : No

Question : If we implement the cloneable interface, without implementing clone(), will the class become cloneable?
Answer : No, it is required to implement/override the clone();

Question : Does constructor get called while cloning?
Answer : No while cloning, only clone function get called, no constructor get called.

Question : Will the parent class participate in cloning even if the parent class has not implemented cloneable interface.
Answer : Yes, it will look at the below code
class NotCloneableParnet{
        private String name = "vikash";
        private Integer rollNumber = 10;
        public NotCloneableParnet(){
                System.out.println("NotCloneableParnet");
        }
        private List<String> listParent = new ArrayList<String>();
        public void add(String s){
                listParent.add(s);
        }
        public int size(){
                return listParent.size();
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public Integer getRollNumber() {
                return rollNumber;
        }
        public void setRollNumber(Integer rollNumber) {
                this.rollNumber = rollNumber;
        }
       
       
}

class CloneableChild extends NotCloneableParnet implements Cloneable{
        public CloneableChild(){
                System.out.println("CloneableChild");
        }
        @Override
        protected Object clone() throws CloneNotSupportedException {
                // TODO Auto-generated method stub
                return super.clone();
        }
       
}

        public static void main(String[] args) throws CloneNotSupportedException {
                CloneableChild child = new CloneableChild();
                System.out.println(child.size());
                CloneableChild cloneChild = (CloneableChild) child.clone();
                cloneChild.add("hello");
                cloneChild.setName("Archit");
                cloneChild.setRollNumber(1);
                System.out.println(child.size());
                System.out.println(child.getName());
                System.out.println(child.getRollNumber());
                System.out.println(cloneChild.size());
                System.out.println(cloneChild.getName());
                System.out.println(cloneChild.getRollNumber());
               
        }
}

NotCloneableParnet
CloneableChild
0
1
vikash
10
1
Archit
1


Question : What is the behavior of primitive type and all the wrapper class object, during the cloning.
Answer : Cloning is like deep cloning for the primitive and wrapper classes, only if there is any other type like used defined and the classes which are not part of java.lang are treated as the ref, but for primitive/wrapper types clone and the real object have there separate copy.

Question : What is the behavior of static variables, during the cloning.
Answer : static variable are class level variable but very much possible through instance variable as well, so any changes done through real or clone object will make changes globally.


Algorithm/Design and Design Pattern Question
Question: What is composition? 
Answer : Holding the reference of the other class within some other class is known as composition.

Question: What is difference between aggregation and composition?
Answer : Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

Question : What is diff between B-Tree and B+Tree?

Question : What is Adapter Pattern?


New Questions to be moved in respective section

Question : What is ThreadLocal?
Answer  : The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

Creating a ThreadLocal
Here is a code example that shows how to create a ThreadLocal variable:

private ThreadLocal myThreadLocal = new ThreadLocal();
As you can see, you instantiate a new ThreadLocal object. This only needs to be done once per thread. Even if different threads execute the same code which accesses a ThreadLococal, each thread will see only its own ThreadLocal instance. Even if two different threads set different values on the same ThreadLocal object, they cannot see each other's values.

Accessing a ThreadLocal
Once a ThreadLocal has been created you can set the value to be stored in it like this:

myThreadLocal.set("A thread local value");
You read the value stored in a ThreadLocal like this:

String threadLocalValue = (String) myThreadLocal.get();
The get() method returns an Object and the set() method takes an Object as parameter.

Generic ThreadLocal
You can create a generic ThreadLocal so that you do not have to typecast the value returned by get(). Here is a generic ThreadLocal example:

private ThreadLocal myThreadLocal = new ThreadLocal();
Now you can only store strings in the ThreadLocal instance. Additionally, you do not need to typecast the value obtained from the ThreadLocal:

myThreadLocal.set("Hello ThreadLocal");

String threadLocalValue = myThreadLocal.get();
Initial ThreadLocal Value
Since values set on a ThreadLocal object only are visible to the thread who set the value, no thread can set an initial value on a ThreadLocal using set() which is visible to all threads.

Instead you can specify an initial value for a ThreadLocal object by subclassing ThreadLocal and overriding the initialValue() method. Here is how that looks:

private ThreadLocal myThreadLocal = new ThreadLocal() {
    @Override protected String initialValue() {
        return "This is the initial value";
    }
};
Now all threads will see the same initial value when calling get() before having called set() .

Full ThreadLocal Example
Here is a fully runnable Java ThreadLocal example:
Full ThreadLocal Example
Here is a fully runnable Java ThreadLocal example:

public class ThreadLocalExample {


    public static class MyRunnable implements Runnable {

        private ThreadLocal threadLocal =
               new ThreadLocal();

        @Override
        public void run() {
            threadLocal.set( (int) (Math.random() * 100D) );

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }

            System.out.println(threadLocal.get());
        }
    }


    public static void main(String[] args) {
        MyRunnable sharedRunnableInstance = new MyRunnable();

        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();
        thread2.start();

        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
    }

}
This example creates a single MyRunnable instance which is passed to two different threads. Both threads execute the run() method, and thus sets different values on the ThreadLocal instance. If the access to the set() call had been synchronized, and it had not been a ThreadLocal object, the second thread would have overridden the value set by the first thread.
However, since it is a ThreadLocal object then the two threads cannot see each other's values. Thus, they set and get different values.

Question : What is Volatile?
The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in an int or a boolean variable then  you can declare them as volatile variable.

From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made from one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread.

The Java volatile keyword cannot be used with method or class and it can only be used with a variable. Java volatile keyword also guarantees visibility and ordering, after Java 5 write to any volatile variable happens before any read into the volatile variable. By the way use of volatile keyword also prevents compiler or JVM from the reordering of code or moving away them from synchronization barrier.

The Volatile variable Example in Java

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without the volatile keyword in java.


/**
 * Java program to demonstrate where to use Volatile keyword in Java.
 * In this example Singleton Instance is declared as volatile variable to ensure
 * every thread see updated value for _instance.
 *
 * @author Javin Paul
 */

public class Singleton{
private static volatile Singleton _instance; //volatile variable

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;
}



If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of the first request comes.

If we do not make the _instance variable volatile than the Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

Why? because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java, this is handled by Java himself and such updates will be visible by all reader threads.

So in Summary apart from synchronized keyword in Java, volatile keyword is also used to communicate the content of memory between threads.


Important points on Volatile keyword in Java

1. The volatile keyword in Java is only application to a variable and using volatile keyword with class and method is illegal.

2. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5 changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable in Java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without the use of volatile keyword in Java.

7. An access to a volatile variable in Java never has a chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

8. Java volatile variable that is an object reference may be null.

9. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.


Difference between synchronized and volatile keyword in Java

What is the difference between volatile and synchronized is another popular core Java question asked on multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

1. The volatile keyword in Java is a field modifier while synchronized modifies code blocks and methods.

2. Synchronized obtains and releases the lock on monitor’s Java volatile keyword doesn't require that.

3. Threads in Java can be blocked for waiting for any monitor in case of synchronized, that is not the case with the volatile keyword in Java.

4. Synchronized method affects performance more than a volatile keyword in Java.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

6. You can not synchronize on the null object but your volatile variable in Java could be null.

7. From Java 5 writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire


In short, volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java. If you like to know more about volatile I would also suggest going thorough FAQ on Java Memory Model here which explains happens-before operations quite well.


Question : What are the features added for the JDK 1.5/1.6
Answer :

·         Scripting Language Support
·         JDBC 4.0 API
·         Java Compiler API
·         Pluggable Annotations
·         Native PKI, Java GSS, Kerberos and LDAP support.
·         Integrated Web Services.
·         Lot more enhancements.
·         Generics
·         Enhanced for Loop
·         Autoboxing/Unboxing
·         Typesafe Enums
·         Varargs
·         Static Import
·         Metadata (Annotations)
·         Instrumentation
Question What are the feature of JDK 1.7 you are aware of?
Answer :
Strings in switch Statement : Now Switch statement can accept the String as well.
public class StringUseInCaseDemo {
       public static void main(String[] args) {
              String lang = "java";
              switch (lang) {
              case "java":
                     System.out.println("java language");
                     break;
              case "python":
                     System.out.println("python language");
                     break;
              case "c++":
                     System.out.println("c++ language");
                     break;
              default:
                     break;
              }
       }
}



Improved type inference for generic instance creation Diamond Syntax: Java 5 introduced generics which enabled developers to write type safe collections. However, generics can sometimes be too verbose. Consider the following example where we are creating a Map of List of String.

With Java 5 and 6
Map<String, List<String>> retVal = new HashMap<String, List<String>>();


Note that the full type is specified twice and is therefore redundant. Unfortunately, this was a limitation of Java 5 and 6.

With Java 7
Java 7 tries to get rid of this redundancy by introducing a left to right type inference. You can now rewrite the same statement by using the <> construct.
Map> retVal = new HashMap<>();

Multiple Exception Handling: Java 7 lets you catch multiple Exceptions in a single catch block by defining a “union” of Exceptions to be caught in the catch clause.
public class TryWithResourceDemo {
public static void main(String[] args) {
         try (
                 InputStream is = new FileInputStream(new File("C:\\logs\\STSOnline_log.txt"));
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
             ) 
             {
                     Class.forName("");
                     DriverManager.getConnection("");
                     System.out.println(bufferedReader.readLine());
              } 
              catch (IOException | ClassNotFoundException | SQLException e) 
              {
                     e.printStackTrace();
              }
       }
}


Note that the pipe ‘|’ character is used as the delimiter. The variable ‘ex’ in the above example is statically typed to the base class of Ex1 and Ex2, which is java.lang.Exception in this case.

Support for Dynamic Languages :

Try with Resources : try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoClosable interface. The AutoClosable interface consists of just one method.
public class TryWithResourceDemo {
       public static void main(String[] args) {
              try(InputStream is = new FileInputStream(new File("C:\\logs\\STSOnline_log.txt")))               {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                System.out.println(bufferedReader.readLine());
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }
}


Each AutoClosable resource created in the try statement will be automatically closed! If an exception is thrown in the try block and another Exception is thrown while closing the resource, the first Exception is the one eventually thrown to the caller. The second Exception is available to the caller via the ex.getSupressed() method. Throwable.getSupressed() is a new method added on Throwable in Java 7 just for this purpose.
We can also open multiple autocloseble resources.
public class TryWithResourceDemo {
public static void main(String[] args) {
      try (
            InputStream is = new FileInputStream(new File("C:\\logs\\STSOnline_log.txt"));
            BufferedReader bufferedReader = new BufferedReader(    new InputStreamReader(is));
          ) 
          {
             Class.forName("");
             DriverManager.getConnection("");
             System.out.println(bufferedReader.readLine());
          } catch (IOException | ClassNotFoundException | SQLException e) {
             e.printStackTrace();
          }
       }
}



Java nio Package
Binary Literals : With Java 7, you can now create numerical literals using binary notation using the prefix “0b”

int n = 0b100000;
System.out.println(“n = ” + n);

Output
n = 32

Underscores in numeric literals : With Java 7, you can include underscores in numeric literals to make them more readable. The underscore is only present in the representation of the literal in Java code, and will not show up when you print the value.

Without underscore
int tenMillion = 10000000;
System.out.println(“Amount is “ + tenMillion);

Output
10000000

With underscore
int tenMillionButMoreReadable = 10_000_000;
System.out.println(“Amount is ” + tenMillionButMoreReadable);

Output
10000000

Question What are the feature of JDK 1.8 you are aware of?
Answer :

·         Lambda Expressions
·         Pipelines and Streams
·         Date and Time API
·         Default Methods
·         Type Annotations
·         Nashhorn JavaScript Engine
·         Concurrent Accumulators
·         Parallel operations
·         PermGen Error Removed
·         TLS SNI


Question : What is CountDownLatch in Java?
Answer : CountDownLatch in Java is a kind of synchronizer which allows one Thread  to wait for one or more Threads before starts processing. This is very crucial requirement and often needed in server side core Java application and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. In this Java concurrency tutorial we will  what is CountDownLatch in Java, How CountDownLatch works in Java, an example of CountDownLatch in Java and finally some worth noting points about this concurrent utility. You can also implement same functionality using  wait and notify mechanism in Java but it requires lot of code and getting it write in first attempt is tricky,  With CountDownLatch it can  be done in just few lines. CountDownLatch also allows flexibility on number of thread for which main thread should wait, It can wait for one thread or n number of thread, there is not much change on code.  Key point is that you need to figure out where to use CountDownLatch in Java application which is not difficult if you understand What is CountDownLatch in Java, What does CountDownLatch do and How CountDownLatch works in Java.

Question : How CountDownLatch works in Java
Answer : CountDownLatch Example in Java 5 6 7Now we know What is CountDownLatch in Java, its time to find out How CountDownLatch works in Java. CountDownLatch works in latch principle,  main thread will wait until Gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Any thread, usually main thread of application,  which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such requirements.

Question : Give a CountDownLatch Exmaple in Java?

In this section we will see a full featured real world example of using CountDownLatch in Java. In following CountDownLatch example, Java program requires 3 services namely CacheService, AlertService  and ValidationService  to be started and ready before application can handle any request and this is achieved by using CountDownLatch in Java.



import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How to use CountDownLatch in Java. CountDownLatch is
 * useful if you want to start main processing thread once its dependency is completed
 * as illustrated in this CountDownLatch Example
 *
 * @author Javin Paul
 */
public class CountDownLatchDemo {

    public static void main(String args[]) {
       final CountDownLatch latch = new CountDownLatch(3);
       Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
       Thread alertService = new Thread(new Service("AlertService", 1000, latch));
       Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
    
       cacheService.start(); //separate thread will initialize CacheService
       alertService.start(); //another thread for AlertService initialization
       validationService.start();
    
       // application should not start processing any thread until all service is up
       // and ready to do there job.
       // Countdown latch is idle choice here, main thread will start with count 3
       // and wait until count reaches zero. each thread once up and read will do
       // a count down. this will ensure that main thread is not started processing
       // until all services is up.
    
       //count is 3 since we have 3 Threads (Services)
    
       try{
            latch.await();  //main thread is waiting on CountDownLatch to finish
            System.out.println("All services are up, Application is starting now");
       }catch(InterruptedException ie){
           ie.printStackTrace();
       }
    
    }

}

/**
 * Service class which will be executed by Thread using CountDownLatch synchronizer.
 */
class Service implements Runnable{
    private final String name;
    private final int timeToStart;
    private final CountDownLatch latch;

    public Service(String name, int timeToStart, CountDownLatch latch){
        this.name = name;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println( name + " is Up");
        latch.countDown(); //reduce count of CountDownLatch by 1
    }

}

Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now


By looking at output of this CountDownLatch example in Java, you can see that Application is not started until all services started by individual Threads are completed.
When should we use CountDownLatch in Java :

Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete, before its start doing processing. Classical example of using CountDownLatch in Java  is any server side core Java application which uses services architecture,  where multiple services is provided by multiple threads and application can not start processing  until all services have started successfully as shown in our CountDownLatch example.


What are the Things to remember CountDownLatch in Java?
Answer : Few points about Java CountDownLatch which is worth remembering

1) You can not reuse CountDownLatch once count is reaches to zero, this is the main difference between CountDownLatch and CyclicBarrier, which is frequently asked in core Java interviews and multi-threading  interviews.

2) Main Thread wait on Latch by calling CountDownLatch.await() method while other thread calls CountDownLatch.countDown() to inform that they have completed.

That’s all on What is CountDownLatch in Java, What does CountDownLatch do in Java, How CountDownLatch works in Java along with a real life CountDownLatch example in Java. This is a very useful concurrency utility and if you master when to use CountDownLatch and how to use CountDownLatch you will be able to reduce good amount of complex concurrency control code written using wait and notify in Java.


Question : How to avoid deadlock in Java Threads
Answer : How to avoid deadlock in Java? is one of the question which is flavor of the season for multi-threading, asked more at a senior level and with lots of follow up questions. Even though question looks very basic but most of developer get stuck once you start going deep.

Interview questions starts with "What is deadlock?"
Answer is simple, when two or more threads are waiting for each other to release lock and get stuck for infinite time, situation is called deadlock . It will only happen in case of multitasking.


Question : How do you detect deadlock in Java ?
Answer : Though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

Other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.

Other way is to use jconsole, it will show you exactly which threads are get locked and on which object.

Question : Write a Java program which will result in deadlock?
Answer : Once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version


/**
Java program to create a deadlock by imposing circular wait.
*
@author WINDOWS 8
*
*/
public class DeadLockDemo {

/*
This method request two locks, first String and then Integer
*/
    public void method1() {
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");

            synchronized (Integer.class) {
                System.out.println("Aquired lock on Integer.class object");
            }
        }
    }

    /*
     * This method also requests same two lock but in exactly
     * Opposite order i.e. first Integer and then String.
     * This creates potential deadlock, if one thread holds String lock
     * and other holds Integer lock and they wait for each other, forever.
     */
    public void method2() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }}


If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thread 1 acquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.

This diagram exactly demonstrate our program, where one thread holds lock on one object and waiting for other object lock which is held by other thread.

Question : How to avoid deadlock in Java?
Answer : Now interviewer comes to final part, one of the most important in my view; How do you fix deadlock? or How to avoid deadlock in Java?

If you have looked above code carefully then you may have figured out that real reason for deadlock is not multiple threads but the way they are requesting lock , if you provide an ordered access then problem will be resolved , here is my fixed version, which avoids deadlock by avoiding circular wait with no preemption.

public class DeadLockFixed {

    /**
     * Both method are now requesting lock in same order, first Integer and then String.
     * You could have also done reverse e.g. first String and then Integer,
     * both will solve the problem, as long as both method are requesting lock
     * in consistent order.
     */
    public void method1() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }

    public void method2() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }
}

Now there would not be any deadlock because both methods are accessing lock on Integer and String class literal in same order. So, if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock, same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.

Diff between FileReader vs FileInputStream Java
Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller.

Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. "UTF-8". Despite being one of the simplest concept, lots of Java developers make mistakes of not specifying character encoding, while 
reading text files or text data from socket.

Remember, if you don't specify correct encoding, or your program is not using character encoding already present in protocol e.g. encoding specified in "Content-Type" for HTML files and encoding presents in header of XML files, you may not read all data correctly. Some characters which are not present in default encoding, may come up as ? or little square.

Once you know this fundamental difference between stream and reader, understanding difference between FileInputStream and FileReader is quite easy. Both allows you to
 read data from File, but FileInputStream is used to read binary data, while FileReader is used to read character data.

FileReader vs FileInputStream Java
Since FileReader extends InputStreamReader, it uses character encoding provided to this class, or else default character encoding of platform. Remember, InputStreamReader caches the character encoding and setting character encoding after creating object will not have any affect. Let's see an example of How to use FileInputStream and FileReader in Java. You can provide either a File object or a String, containing location of file to start reading character data from File. This is similar to FileInputStream, which also provides similar constructors for reading from file source. Though its advised to use BufferedReader to read data from file.
import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * Java Program to read data from file as stream of bytes and stream of characters.
 * It also highlight key difference between FileInputStream and FileReader that
 * FileReader is meant for reading streams of characters. 
 * For reading streams of raw bytes, consider using a FileInputStream.
 *
 * @author Javin Paul
 */
public class HowToReadFileInJava {
    public static void main(String args[]) {

        // Example 1 - Reading File's content using FileInputStream
        try (FileInputStream fis = new FileInputStream("data.txt")) {
            int data = fis.read();
            while (data != -1) {
                System.out.print(Integer.toHexString(data));
                data = fis.read();
            }
        } catch (IOException e) {
            System.out.println("Failed to read binary data from File");
            e.printStackTrace();
        }


        // Example 2 - Reading File data using FileReader in Java
        try (FileReader reader = new FileReader("data.txt")) {
            int character = reader.read();
            while (character != -1) {
                System.out.print((char) character);
                character = reader.read();
            }
        } catch (IOException io) {
            System.out.println("Failed to read character data from File");
            io.printStackTrace();
        }
    }
}

Output:
4157532d416d617a6f6e205765622053657276696365da474f4f472d476f6f676c65da4150504c2d4170706c65da47532d476f6c646d616e205361636873
AWS-Amazon Web Service
GOOG-Google
APPL-Apple
GS-Goldman Sachs






Our first example is reading data from file byte by byte, so its bound to be very slow. read() method from FileInputStreamis a blocking method, which reads a byte of data or blocks if no input is yet available. It either returns next byte of data, or -1 if the end of the file is reached. This means we read one byte in each iteration of loop and prints it as Hexadecimal String. By the way, there is options to convert InputStream into byte array as well. On the other hand, in example 2 are reading data character by character. read() method from InputStreamReader, which is inherited by FileReader reads a single character and returns the character read, or -1 if the end of the stream has been reached. This is why you see exactly same text as written in file output from our example 2.

That's all on difference between FileInputStream and FileReader in Java. Bottom line is use FileReader or BufferedReader to read stream of characters or text data from File and always specify character encoding. Use FileInputStream to read raw streams of bytes from file or socket in Java.


Question : What value does readLine() return when it has reached the end of a file?
Answer : The readLine() method returns null when it has reached the end of a file. 

Question : What is a native method?
Answer : A native method is a method that is implemented in a language other than Java.

Can a double value be cast to a byte?
Yes, a double value can be cast to a byte. But, it will result in loss of precision.

What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.

Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
Note : As of java 1.7 now we can use the string also.

What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.

What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.

What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

Which package is always imported by default?
The java.lang package is always imported by default in all Java Classes.

What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides but it can expand it. The overriding method may not throw any exceptions that are not thrown by the overridden method.

What do you mean by object oriented programming
In object oriented programming the emphasis is more on data than on the procedure and the program is divided into objects. Some concepts in OO Programming are:
* the data fields are hidden and they can’t be accessed by external functions.
* The design approach is bottom up.
* The Methods operate on data that is tied together in data structure

What are 4 pillars of object oriented programming
1. Abstraction - It means hiding the details and only exposing the essential parts

2. Polymorphism - Polymorphism means having many forms. In java you can see polymorphism when you have multiple methods with the same name

3. Inheritance - Inheritance means the child class inherits the non-private properties of the parent class

4. Encapsulation - It means data hiding. In java with encapsulate the data by making it private and even we want some other class to work on that data then the setter and getter methods are provided.

Difference between procedural and object oriented language
In procedural programming the instructions are executed one after another and the data is exposed to the whole program
In Object Oriented programming the unit of program is an object which is nothing but combination of data and code and the data is not exposed outside the object.

What is the difference between parameters and arguments
While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

What is a cloneable interface and how many methods does it contain
The cloneable interface is used to identify objects that can be cloned using the Object.clone() method. IT is a Tagged or a Marker Interface and hence it does not have any methods.


What is the difference between Authentication and Authorization ?
Authentication is a process for verifying that an individual is who they say they are. Authorization is an additional level of security, and it means that a particular user (usually authenticated), may have access to a particular resource say record, file, directory or script.

What is the difference between class variable, member variable and automatic(local) variable
class variable is a static variable and does not belong to instance of class but rather shared across all the instances of the Class.

member variable belongs to a particular instance of class and can be called from any method of the class

automatic or local variable is created on entry to a method and is alive only when the method is executed

When are static and non static variables of the class initialized ?
The static variables are initialized when the class is loaded

Non static variables are initialized just before the constructor is called

How is an argument passed in java, is it by copy or by reference?
If the variable is primitive datatype then it is passed by copy.
If the variable is an object then it is passed by reference .



What are the rules for overriding ?
The rules for Overriding are: Private method can be overridden by private, protected or public methods Friendly method can be overridden by protected or public methods Protected method can be overridden by protected or public methods Public method can be overridden by public method


Can you change the reference of the final object ?
No the reference cannot be changed, but the data in that object can be changed.

Can abstract modifier be applied to a variable ?
No it can be applied only to class and methods

When are the static variables loaded into the memory
During the class load time

When are the non static variables loaded into the memory ?
They are loaded just before the constructor is called

What is the output of the below code.
{
  System.out.println(" XX  "+t);
 }
 static Integer t;
 static  {
  System.out.println("YY "+t);
  t=20;
 }
 
 public static void main(String[] args) {
  new ResearcherDAO();
  System.out.println(t);
 }
 
YY null
 XX  20
20



Question : What will happen if we try to make the first block as static?
Answer : We will get the compilation error as  "Cannot reference a field before it is defined".


What do you understand by late binding or virtual method Invocation ?
When a compiler for a non object oriented language comes across a method invocation, it determines exactly what target code should be called and build machine language to represent that call. In an object oriented language, this is not possible since the proper code to invoke is determined based upon the class if the object being used to make the call, not the type of the variable. Instead code is generated that will allow the decision to be made at run time. This delayed decision making is called as late binding

Can Overridden methods have different return types ?
No they cannot have different return types, only exception is if it is co variant type i.e. could be the subclass e.g. if the overidden method return type is ArrayList if the parent method return type is list.

If the method to be overridden has access type protected, can subclass have the access type as private
No, it must have access type as protected or public, since an overriding method must not be less accessible than the method it overrides ?

What about vice versa?
yes, that is fine as the private is not visible, so there is no complain for the access type for public protected or private.

Is below Possible?


class a{
  protected void tt(){
   
  }
 }
 
class b extends a{
  public void tt(){
   
  }
}



Answer : Yes we are just incresing the visibility of the method.

What is an abstraction ?
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.

What is Association?
It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.


What is Aggregation?
It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.

For concatenation of strings, which class is good, StringBuffer or String ?
StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.



As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation?
As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.



To what value is a variable of the String type automatically initialized?
The default value of String variable is null.

Why String class is final or immutable?
The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason.

If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different.

Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it?

MyString str1 = "Rocky";
YourString str2 = "Rocky";


What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.

The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.


There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

What is Runnable interface ? Are there any other ways to make a multithreaded java program?
There are two ways to create new threads:

- Define a new class that extends the Thread class
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor.

The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.


How can I tell what state a thread is in ?
Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.

Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.

New, Runnable, Blocked, Waiting, Timed_waiting and Terminated


What is the difference between notify and notify All methods ?
A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll

so, sometimes it is better to use notify than notifyAll.


What is synchronized keyword? In what situations you will Use it?
Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.


Why do threads block on I/O?
Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password.


What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.

Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.

How do you make threads to wait for one another to complete execution as a group?
We can use the join() method to make threads wait for one another

What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.


What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same.

When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.

What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.


When a thread is created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.

What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.


What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

25. How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

26. What happens when you invoke a thread's interrupt method while it is sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

27. How can a dead thread be restarted?
A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it.

28. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

29. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Without a run() method, a thread cannot execute.

30. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

A synchronized statement can be inside a regular method and vice versa.

31. What are volatile variables
It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment.

32. Where does java thread support reside
It resides in three distinct places

The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine

33. What is the difference between Thread and a Process
Threads run inside process and they share data.

One process can have multiple threads, if the process is killed all the threads inside it are killed

34. What happens when you call the start() method of the thread
This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it.

35. Does calling start () method of the thread causes it to run
No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run

36. When the thread gets to execute, what does it execute
It executes all the code that is placed inside the run() method.

37. How many methods are declared in the interface runnable
The runnable method declares only one method : public void run();

38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface
The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java.

39. What happens when the run() method returns
When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread.

40. What are the different states of the thread
The different states of Threads are:

New: Just created Thraed
Running: The state that all threads want to be
Various waiting states : Waiting, Sleeping, Suspended and Blocked
Ready : Waiting only for the CPU
Dead : Story Over

41. What is Thread priority
Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler

42. What is the range of priority integer that can be set for Threads?
It is from 1 to 10. 10 beings the highest priority and 1 being the lowest

43. What is the default priority of the thread
The default priority is 5. It is also called the Normal Priority.

44. What happens when you call Thread.yield()
It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread

45. What is the advantage of yielding
It allows a time consuming thread to permit other threads to execute

46. What happens when you call Thread.sleep()
It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method.

47. Does the thread method start executing as soon as the sleep time is over

No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over.

48. What do you mean by thread blocking
If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked.

49. What threading related methods are there in object class
wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only

50. What is preemptive scheduling
Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever.

51. What is non-preemptive or Time sliced or round robin scheduling
With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute.

52. What are the two ways of synchronizing the code
Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method.

Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code

53. What happens when the wait() method is called
The following things happen:


The calling thread gives up CPU
The calling thread gives up the lock
The calling thread goes into the monitor's waiting pool

54. What happens when the notify() method is called
One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution

55. Using notify () method how you can specify which thread should be notified You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method.

How can you force garbage collection?
You cannot force Garbage Collection, but could request it by calling System.gc(). Though you manually call this command from your program, the JVM does not guarantee that GC will be started immediately.

2. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references. We need to ensure that all objects that are no longer required in the program are cleared off using finalize() blocks in your code.

3. Explain garbage collection ?
Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed or used by the program are "garbage" and can be thrown away to create free space for the programs that are currently running. A more accurate and up-to-date term might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. This way, unused memory space is reclaimed and made available for the program to use.

4. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection as well. Hence, the Garbage Collection mechanism is a "On Best Effort Basis" system where the GC tries to clean up memory as much as possible to ensure that the system does not run out of memory but it does not guarantee the same.

5. Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

6. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. We usually nullify the object references of large objects like collections, maps etc in the finalize block.


7. How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.


8. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. The system will not do it and you cannot force it either.

9. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. i.e., it is dead or deleted. It can no longer become reachable again.


10. What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.


11. Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

12. When is an object subject to garbage collection?
An object is subject to garbage collection when it becomes unreachable to the program in which it is used. i.e., no other object or code in the system is going to access this current object

13. Does System.gc() and Runtime.gc() guarantee garbage collection
No.

14. Do we need memory management code in our application?
No. Memory Management is a complicated activity and that is exactly why the creators of the Java language did it themselves so that programmers like us do not have to go through the pain of handling memory management.

15. What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?
This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception.

Two important types of OutOfMemoryError are often encountered
1. java.lang.OutOfMemoryError: Java heap space - The quick solution is to add these flags to JVM command line when Java runtime is started as follows:
-Xms1024m -Xmx1024m
2. java.lang.OutOfMemoryError: PermGen space - The solution is to add these flags to JVM command line when Java runtime is started as follows:

-XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled

Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks.



Explain the usage of the keyword transient?
The transient keyword indicates that the value of this variable need not be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (ex: 0 for integers).

2. What are the uses of Serialization?
Serialization is widely used to:

* To persist data for future use.
* To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
* To "flatten" an object into array of bytes in memory.
* To exchange data between applets and servlets.
* To store user session in Web applications.
* To activate/passivate enterprise java beans.
* To send objects between the servers in a cluster.

3. What is serialization ?

Serialization is the process of writing the complete state of java object into an output stream. This stream can be file or byte array or stream associated with a TCP/IP socket.

4. What does the Serializable interface do ?

Serializable is a tagging interface which declares/describes no methods. It is just used to signify the fact that, the current class can be serialized. ObjectOutputStream serializes only those objects which implement this interface.

5. How do I serialize an object to a file ?
To serialize an object into a stream perform the following steps:

1. Open one of the output streams, for exaample FileOutputStream
2. Chain it with the ObjectOutputStream - Call the method writeObject() providing the instance of a Serializable object as an argument.
3. Close the streams

6. How do I deserilaize an Object?
To deserialize an object, perform the following steps:

1. Open an input stream
2. Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized.
3. Close the streams

7. What is Externalizable Interface ?
Externalizable interface is a subclass of Serializable. Java provides Externalizable interface so as to give you more control over what is being serialized and what is not. Using this interface, you can Serialize only the fields of the class you want serialize and ignore the rest.

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.

8. What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

9. What are the rules of serialization
Some rules of Serialization are:

1. Static fileds are not serialized because they are not part of any one particular object
2. Fileds from the base class are handled only if the parent class itself is serializable
3. Transient fileds are not serialized.



10. What is the difference between StringBuffer and StringBuilder in Java?
Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not synchronized.

Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered the bad practice to use StringBuffer anymore, because, in almost 99% scenario, you perform string concatenation on the same thread.


What is the difference between application server and web server?



Application Server is a term that sometimes is mixed with a web server. While a web server handles mainly HTTP protocols, the application server deals with several different protocols, including, but not limited, to HTTP.
The Web server's main job is to display the site content and the application server is in charge of the logic, the interaction between the user and the displayed content. The application server is working in conjunction with the web server, where one displays and the other one interacts.
The information traveling back and forth between the server and its client is not restricted to simple display markup, but to interaction between the two.
In most cases, the server creates this interaction through a component API, such as J2EE (Java 2 Platform)EJB (Enterprise JavaBean) and other different application software models.
enter image description here

Web Server -> Programming Environment
IIS : ASP (.NET)
Tomcat : Servlet
Jetty : Servlet
Apache : Php, CGI

Application Servers -> Programming Environment
MTS : COM+
WAS : EJB
JBoss : EJB
WebLogic Application Server : EJB



http://javaconceptoftheday.com/core-java-coding-questions-which-will-test-your-java-basic-skills/
http://java4732.blogspot.in/2015/06/programming-challenges.html
http://www.improgrammer.net/9-puzzle-websites-to-sharpen-your-programming-skills/
http://java4732.blogspot.in/2015/05/topics-based-interview-questions.html
http://crbtech.in/Java-Training/
http://freshernet.com/top-500-java-interview-questions-and-answers/
http://javaconceptoftheday.com/how-hashset-works-internally-in-java/
http://www.igetsure.com/
https://somritachatterjee16.wordpress.com/2015/07/02/blog-1-java-oops-concept/
http://www.hub4tech.com/interview/java 
http://www.javaquery.com/2015/07/how-to-iterate-over-stream-and.html
http://www.technology-ebay.de/the-teams/mobile-de/blog/a-conversation-around-decorators.html
http://robinfromsps.com/possible-combinations-consecutive-natural-number-program/
http://javaconceptoftheday.com/how-to-find-roman-equivalent-of-a-decimal-number-in-java/
http://www.thoughts-on-java.org/java-weekly/
https://vimeo.com/124034512?ref=fb-share
http://java-latte.blogspot.in/2015/08/file-locking-example-in-java.html
http://www.javaquery.com/2015/06/default-and-static-method-in-java.html
http://javasolutionsguide.blogspot.nl/2015/08/how-to-make-object-eligible-for-garbage.html
http://www.toptal.com/java/why-you-need-to-upgrade-to-java-8-already/#remote-developer-job
http://markup.su/highlighter/