Thursday, 28 January 2016

How can you describe String Literal/Constant Pool ??

There are two ways to create a String object in Java:

Using the new operator. For example,
String str = new String("Hello");

Using a string literal or constant expression). For example,
String str="Hello"; (string literal) or
String str="Hel" + "lo"; (string constant expression).

What is difference between these String's creations? 

In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object.

Let's use the following example to see what difference between these creations of string:

public class DemoStringCreation {

  public static void main (String args[]) {
    String str1 = "Hello";
    String str2 = "Hello";
    System.out.println("str1 and str2 are created by using string literal.");  
    System.out.println("    str1 == str2 is " + (str1 == str2));
    System.out.println("    str1.equals(str2) is " + str1.equals(str2));

   
    String str3 = new String("Hello");
    String str4 = new String("Hello");
    System.out.println("str3 and str4 are created by using new operator.");  
    System.out.println("    str3 == str4 is " + (str3 == str4));
    System.out.println("    str3.equals(str4) is " + str3.equals(str4));
   
    String str5 = "Hel"+ "lo";
    String str6 = "He" + "llo";
    System.out.println("str5 and str6 are created by using string
constant expression.");  
    System.out.println("    str5 == str6 is " + (str5 == str6));
    System.out.println("    str5.equals(str6) is " + str5.equals(str6));

    String s = "lo";
    String str7 = "Hel"+ s;
    String str8 = "He" + "llo";
    System.out.println("str7 is computed at runtime.");
    System.out.println("str8 is created by using string constant
expression.");  
    System.out.println("    str7 == str8 is " + (str7 == str8));
    System.out.println("    str7.equals(str8) is " + str7.equals(str8));
   
  }
}
The output result is:

str1 and str2 are created by using string literal.
    str1 == str2 is true
    str1.equals(str2) is true
str3 and str4 are created by using new operator.
    str3 == str4 is false
    str3.equals(str4) is true
str5 and str6 are created by using string constant expression.
    str5 == str6 is true
    str5.equals(str6) is true
str7 is computed at runtime.
str8 is created by using string constant expression.
    str7 == str8 is false
    str7.equals(str8) is true

The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.



String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";
       String str2 = "Hello";
       System.out.print(str1 == str2);
    }
}
The result is

true


Unfortunately, when you use
String a=new String("Hello");

A String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it!

For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";
       String str2 = new String("Hello");
       System.out.print(str1 == str2 + " ");
       System.out.print(str1.equals(str2));
    }
}
The result is

false true


A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.
For example

public class Program
{
    public static void main(String[] args)
    {
        // Create three strings in three different ways.
        String s1 = "Hello";
        String s2 = new StringBuffer("He").append("llo").toString();
        String s3 = s2.intern();

        // Determine which strings are equivalent using the ==
        // operator
        System.out.println("s1 == s2? " + (s1 == s2));
        System.out.println("s1 == s3? " + (s1 == s3));
    }
}
The output is

s1 == s2? false
s1 == s3? true
There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.

Thus, the test program consisting of the compilation unit:

package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello", lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}
class Other { static String hello = "Hello"; }
and the compilation unit:

package other;
public class Other { static String hello = "Hello"; }
produces the output:

true true true true false true

This example illustrates 5 points:

a) Literal strings within the same class in the same package represent references to the same String object.
b) Literal strings within different classes in the same package represent references to the same String object.
c) Literal strings within different classes in different packages likewise represent references to the same String object.
d) Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
e) Strings computed by concatenation at run time are newly created and therefore distinct.

Thursday, 21 January 2016

Widely Used 65 Abbreviations within Java Technologies and Frameworks

AJAX - Asynchronus Javascript and XML

ANT - Another Neat Tool
AOP - Aspect Oriented Programming
API - Application Program Interface
AWT - Abstract Window Toolkit
BMP - Bean Managed Persistence
BMT - Bean Managed Transaction
CGI - Common Gateway Interface
CORBA - Common Object Request Broker Architecture
CSS - Cascading Style Sheets
DAO - Data Access Object
DNS - Domain Name Service
DOM - Document Object Model
DTD - Document Type Definition
EAR - Enterprise ARchive
EIS - Enterprise Information System
EJB - Enterprise Java Bean
ERP - Enterprise Resource Planning
HQL - Hibernate Query Language.
HTML - Hyper Text Markup Language
IDE - Integrated Development Environment
IOC - Inversion of Control
J2EE - Java 2 Enterprise Edition
JAAS - Java Authentication and Authorization Service
JAF - JavaBeans Activation Framework
JAR - Java ARchive
JAXB - Java API for XML Binding
JAXP - Java API for XML Parsing
JAXR - Java API for XML Registries
JAX-RPC - Java API for XML-based RPC
JAX-WS - Java API for XML-based Web Services
JDBC - Java Database Connectivity
JDK - Java Development Kit
JFC - Java Foundation Classes
JMS - Java Messaging Service
JNDI - Java Naming and Directory Interface
JNI - Java Native Interface
JSF - Java Server Faces
JSON - Javascript Object Notation
JSP - Java Server Pages
JSTL - Java Standard Tag Library
JTA - Java Transaction API
JVM - Java Virtual Machine
LDAP - Lightweight Directory Access Protocol
MVC - Model View Controller
OOP - Object Oriented Programming
ORM - Object to Relational Mapping.
POJI - Plain Old Java Interface
POJO - Plain Old Java Object
RAD - Rational Application Development
RDBMS Relational Database Management System
RMI - Remote Method Invocation
RPC - Remote Procedure Call
SAX - Simple API for XML
SOAP - Simple Object Access Protocol
UI - User Interface
UML - Unified Modelling Language
WAR - Web ARchive
WSAD - Websphere Application Development.
WSDL - Web Service Description Language
XHTML - Extensible Hypertext Markup Language
XML - Extensible Markup Language
XSD - XML Schema Definition
XSL - Extensible Style Language
XSLT Extensible Style Language Transformation

Tuesday, 12 January 2016

Map & Set Tracking

1) How HashSet internally work ??

HashSet uses HashMap internally to store it’s objects. 
HashSet is developed on the top of HashMap.

> Whenever you create a HashSet object, one HashMap object associated with it is also created. 
> This HashMap object is used to store the elements you enter in the HashSet. 
> The elements you add into HashSet are stored as keys of this HashMap object. 
> The value associated with those keys will be a constant named as "PRESENT". 
> Every constructor of HashSet class internally creates one HashMap object.

2) How HashMap internally work ??

static class Entry<K,V> implements Map.Entry<K,V> 
{
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
        //Some methods are defined here
}

key : It stores the key of an element and its final.

value : It holds the value of an element.

next : It holds the pointer to next key-value pair. This attribute makes the key-value pairs stored as a linked list.

hash : It holds the hashcode of the key.

These Entry objects are stored in an array called table[]. This array is initially of size 16. It is defined like below.

     /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */

    transient Entry<K,V>[] table;

To summarize the whole HashMap structure, each key-value pair is stored in an object of Entry<K, V> class. This class has an attribute called next which holds the pointer to next key-value pair. This makes the key-value pairs stored as a linked list. All these Entry<K, V> objects are stored in an array called table[]. 

3) What Is Hashing?

The whole HashMap data structure is based on the principle of Hashing. Hashing is nothing but the function or algorithm or method which when applied on any object/variable returns an unique integer value representing that object/variable. This unique integer value is called hash code. Hash function or simply hash said to be the best if it returns the same hash code each time it is called on the same object. Two objects can have same hash code.

Whenever you insert new key-value pair using put() method, HashMap blindly doesn’t allocate slot in the table[] array. Instead it calls hash function on the key. HashMap has its own hash function to calculate the hash code of the key. 

4) How race condition works in Java Hashmap?

Hashmap could run into race condition if it would be modified by two thread simultaneous and one thread tries to resize or rehash the map because of capacity crossing threshold value. since hashmap maintains a linked list of element in bucket and while copying from one hashmap to other or old to new order of linked list got reversed, which could result in infinite loop if two threads are doing resizing at same time.

 there are potential race conditions:
  • when resizing an HashMap by two threads at the same time
  • when collisions happens. Collision can happen when two elements map to the same cell even if they have a different hashcode. During the conflict resolution, there can be a race condition and one added key/value pair could be overwritten by another pair inserted by another thread.
To explain better what I mean on the second point, I was looking at the source code of HashMap in OpenJdk 7
389        int hash = hash(key.hashCode());
390        int i = indexFor(hash, table.length);
First it calculates an Hash of your key (combining two hash functions), then it maps to a cell with indexFor, then it checks if that cell contains the same key or is already occupied by another one. If it's the same key, it just overwrite the value and there is no problem here.
If it's occupied it looks at the next cell and then the next until it finds an empty position and call addEntry(), which could even decide to resize the array if the array is more loaded than a certainloadFactor.
Our table containing the entries is just a vector of Entry which holds key and value.
146    /**
147     * The table, resized as necessary. Length MUST Always be a power of two.
148     */
149    transient Entry[] table;
In a concurrent environment, all sort of evil things can happen, for instance one thread gets a collision for cell number 5 and looks for the next cell (6) and finds it empty.
Meanwhile another thread gets an index of 6 as a result of indexFor and both decide to use that cell at the same time, one of the two overwriting the other.

5) How does get() method of HashMap works, if two keys has same hashCode?

Hashmap works on the principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in a bucket which is essential to understand the retrieving logic. 


Important Discussions on HashMap : Please go through it.

How Hashmap works in Java

HashMap works on the principle of Hashing .  
To understand Hashing, we should understand the three terms first 1) Hash Function 2) Hash Value 3) Bucket.

What is Hash Function, Hash Value and Bucket ?

hashCode() function  which returns an integer value is the Hash function. The important point to note that,  this method is present in Object class (Mother of all class).

This is the code for the hash function(also known as hashCode method) in Object Class :
    public native int hashCode();

The most important point to note from the above line :  hashCode method return  int value.

So the Hash value is the int value returned by the hash function .

A bucket is used to store key value pairs . 
A bucket can have multiple key-value pairs . In hash map, bucket used simple linked list to store objects .

After understanding the terms we are ready to move next step , How hash map works in java or How get() works internally in java .

Code inside Java Api (HashMap class internal implementation) for HashMap get(Obejct key) method 

1.  Public  V get(Object key)
   {
2.     if (key ==null)
3.     //Some code
    
4.     int hash = hash(key.hashCode());
    
5.     // if key found in hash table then  return value
6.     //    else return null
   }

Hash map works on the principle of hashing 

HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of  Entry object . So thinking that Only value is stored  in the bucket is not correct and will not give a good impression on the interviewer .

* Whenever we call get( Key k )  method on the HashMap object . First it checks that whether key is null or not .  Note that there can only be one null key in HashMap .  

If key is null , then Null keys always map to hash 0, thus index 0.

If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()  ,so after key.hashCode() returns hashValue , line 4 looks like

4) int hash = hash(hashValue) and now it applies returned hashValue into its own hashing function .

We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is, It defends against poor quality hash functions.

Now step 4 final  hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex) .  


Interviewer: What if when two different keys have the same hashcode ?

Solution, equals() method comes to rescue. Here candidate gets puzzled. Since bucket is one and we have two objects with the same hashcode .Candidate usually forgets that bucket is a simple linked list.

The bucket is the linked list effectively. Its not a LinkedList as in a java.util.LinkedList - It's a separate (simpler) implementation just for the map .

So we traverse through linked list , comparing keys in each entries using keys.equals() until it return true.  Then the corresponding entry object Value is returned .


How hashmap works internally in java

One of  our readers Jammy  asked a very good  question 

When the functions 'equals' traverses through the linked list does it traverses from start to end one by one...in other words brute method. Or the linked list is sorted based on key and then it traverses? 

Answer is when an element is added/retrieved, same procedure follows:

 
a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key

b. Pass intial hashvalue as hashValue  in    hash(hashValue) function, to calculate the final hashvalue.

c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method .
    The second parameter is length which is a constant in HashMap Java Api , represented by                             DEFAULT_INITIAL_CAPACITY

    The default  value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .

 indexFor(int,int) method  returns the first entry in the appropriate bucket. The linked list in the bucket is then iterated over - (the end is found and the element is added or the key is matched and the value is returned )


Explanation about indexFor(int,int) is below :

/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
    return h & (length-1);
}


The above function indexFor() works because Java HashMaps always have a capacity, i.e. number of buckets, as a power of 2.
 Let's work with a capacity of 256,which is 0x100, but it could work with any power of 2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.


Interviewer:    What if  when two  keys are same and have the same hashcode ?

If key needs to be inserted and already inserted hashkey's hashcodes are same, and keys are also same(via reference or using equals() method)  then override the previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve as a key if and only if it overrides the equals() and hashCode() method .


Interviewer:  How will you measure the performance of HashMap?

According to Oracle Java docs,  

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.  The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the hash table is created. 


The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

In HashMap class, the default value of load factor is (.75) .

Interviewer : What is the time complexity of Hashmap get() and put() method ?

The hashmap implementation provides constant time performance for (get and put) basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses the elements properly among the buckets. 


How to implement duplicate key for a HashMap?

Example :

Map data = new HashMap(); 
data.put("a","America"); 
data.put("a","Africa"); 
data.put("b","Bangladesh");
Need to have both "America" and "Africa" as value against key "a". Is there any mechanism to achieve this scenario.

By using :

Map<String,List> data = new HashMap();
{a:[America,Africa] ,b:[Bangaldesh]}


Super 30 Interview questions from Collection Framework ??

Question 1. What is Collection framework in java?

Question 2. Which interfaces and classes are most frequently used in Collection framework in java (Draw the hierarchy)?

Question 3. What are sub interfaces of Collection interface in java? Is Map interface also a sub interface of Collection interface in java?

Question 4. What are differences between ArrayList and LinkedList in java?

Question 5. What are differences between ArrayList and Vector in java?

Question 6. What are differences between List and Set interface in java?

Question 7. What are differences among Iterator and ListIterator and Enumeration in java?

Question 8. What are differences between Collection and Collections in java?

Question 9. How do we override equals and hashcode method in java, write a code to use Employee as key in HashMap in java? (Important)

Question 10. What classes should i prefer to use a key in HashMap in java? (Important)

Question 11. What are differences between HashMap and Hashtable in java?

Question 12. when to use HashSet vs LinkedHashSet vs TreeSet in java?

Question 13. What are differences between HashMap and ConcurrentHashMap in java?

Question 14. When to use HashMap vs Hashtable vs LinkedHashMap vs TreeMap in java?

Question 15. What is WeakHashMap in java?

Question 16. What is EnumSet & EnumMap in java?

Question 17. How to implement own/custom HashMap in java? Or How HashMap works in java?

Question 18. How to implement own LinkedHashMap in java? Or LinkedHashMap works in java?

Question 19. How to implement own ArrayList in java?Or How ArrayList works in java ?

Question 20. How to implement own HashSet in java? Or How HashSet works in java ?

Question 21. How to implement own LinkedHashSet in java Or How LinkedHashSet works in java ?

Question 22. What do you mean by fail-fast and fast-safe? What is ConcurrentModificationException?

Question 23. What are different ways of iterating over elements in List?

Question 24. What are different ways of iterating over elements in Set?

Question 25. What are different ways of iterating over keys, values and entry in Map?

Question 26. What is difference between Comparable and Comparator? How can you sort List?

Question 27. What are differences between ArrayList vs CopyOnWriteArrayList?

Question 28. What are differences between HashSet vs CopyOnWriteArraySet?

Question 29. What are differences between TreeSet vs ConcurrentSkipListSet?

Question 30. Can we use null element/key in TreeSet? Give reason?

***** Please follow the below given diagram for proper difference *****










Friday, 8 January 2016

Important Points On Java !!! Remind Always

1) Unnecessarily Don't override hashCode() method within java code.

2) private, static, final keywords can't be overridden in java.

3) StringBuffer doesn't override the equal() method of an Object class but String class does.

4) when we extend Thread class each and every thread gets associated with new object.

5) When we implement Runnable interface, same object is shared amongst multiple threads.

6) There some illegal combination of modifier, which is never used in java

         a) abstract can't be used with ( final , static , private , native , strictfp , synchronized )

         b) A transient variable may not be declared as final or static

         c) volatile and final combination is always illegal in nature.

         d) Native and strictfp combination is illegal for methods in java.

         e) The methods cannot be declared native and strictfp simultaneously within java code.

         f) final fields cannot be volatile in nature within java.

7)  An array is an object in Java. They are not primitive like int, short, or long, but they are also not full featured object with lot of methods, but because they are object, they implicitly extend Object and that's why you can call any method of java.lang.Object using array reference e.g. toString().

8)  Initializing array or collection with proper size is still one of the best practices to follow.
    for that create one new array and then copy the previous array to newly generated array which still an expensive operation and can slow down the performance of your Java application.
    i.e. Array in Java is once created then you can not change the size of the array.

9)  Important Points about Constructor in java

      a) Constructors can be overloaded.

      b) Constructors shouldn't have any return types , not even void.

      c) Default constructor is provided by the compiler if we don't declare any constructor. If we declare a parameterized constructor, Compiler will not create any default non parameterized constructor for the class.

      d) A constructor can only have either this or super statement and that statement should be the first statement in constructor.

      e) If Constructor has been declared private, Objects of the class cannot be instantiated from outside class.

      f) If super is not explicitly called, still super() is intrinsically added by the compiler.

      g) Default Constructor initializes the instance variables to their default values.

      h) Final variables can be initialized within constructor.


10)  Important Points about Classes and Interfaces

       a) Default constructor initializes the primitives to their default values ( 0 for int , 0.0 for float etc ) and Instance variables to null.

       b) Outer Class can't be declared private or protected. It can only be either public or package protected ( default ).

       c) All members of Interfaces are intrinsically public which cannot be declared private.
.
       d) Variables of an interface are intrinsically public , static and final and can be accessed directly by the implementing class.

       e) An object is eligible for garbage collection when it looses all its references.

       f) Last Reference assigned null doesn't make the object eligible for gc. Reference should be assigned to some other object.

       g) System.gc doesn't enforce garbage collection immediately.

       h) All wrapper classes are immutable in nature. But String is not a wrapper class.

       i) We don't need object of outer class for accessing static inner class object. Inner static class object can be initiated using outer Class name only.

11)  Important Points about Thread

       a) Thread.yield() doesn't guarantee that the Thread will keep waiting until execution of other threads.

       b) run method can be called directly but in such case it doesn't initiate new thread.

       c) invoking start twice on same thread leads to IllegalStateException.

       d) Sequence in which multiple runnable threads are executed is system dependent and cannot be predicted.

       e) Only methods ( static , instance ) and blocks can be synchronized. Variables cannot be synchronized.

       f) InterruptedException is the checked exception for sleep method.

       g) sleep is a static method and puts the current thread to sleep for specified time in ms.

       h) If the synchronized block is on a string literal, all threads will try to get lock on a common object as its picked from String pool.

       i) synchronized cannot be applied to a constructor.

       j) wait and notify should be there in synchronized section only.

       k) Overridden method run cannot throw any checked exception.

       l) There are object spcific locks and class specific locks.

       m) suspend() method is used to suspend the execution of a thread for a period of time. We can then restart the thread by using resume() method.

       n) yield and sleep are static methods of Thread Class. join is the instance method of Thread Class. wait, notify and notifyAll are methods of Object class.

       o) Difference between implementing Runnable interface and extending Thread class

                   1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance So get your chance through implementing Runnable Interface.

                   2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

                   3) Runnable provides only run() whereas Thread provides start(), run() etc.

                   4) Separating task as Runnable means we can reuse the task but you can't restart a Thread once it completes.

                   5) Runnable is loosely coupled whereas Thread no.

                   6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

12.   Important Points about Exception

         a) ArithmeticException is the subclass of RuntimeException and it is an unchecked exception.

         b) Compiler gives error if we don't handle checked exceptions whereas unchecked exceptions are optional to be handled.

         c) Either we should catch the checked exceptions or the method should be declared to throw those exceptions.

         d) Catch blocks for try should handle exceptions from specific to general. Compiler gives error if we have generalize catch before specific.

         e) Finally block is always executed whether an exception occurs or not.

         f) When an exception is thrown, rest statements in the try block are not executed.

         g) try and then finally without catch is legal in java.

         h) try without catch or finally is not legal.

         i) An overriding method cannot throw an exception wider than the exception being thrown                     from the overriden method.

13.   Important Points about Inner Class

          a) Static inner class cannot access instance members of the enclosing class.

          b) Local class declared within static method cannot access instance members.

          c) Static inner class can be accessed without instance of the parent class.

          d) An inner class can access all elements of the parent class , even declared private.

          e) To instantiate the inner class object following code is used

                            OuterClass.InnerClass innerRef = outerRef.new InnerClass();

          f) An anonymous inner class can either extend one class or implement one interface only.

          g) Anonymous inner class should be ended with a semi colon after curly brace.

          h) Static inner class can be instantited like this

                            OuterClass.InnerClass inner = new OuterClass.InnerClass();


14.  Only Integers, char, String and Enum are allowed in Switch statement.

15.  If there are no break statements in case blocks, it will execute all statements either till the next break statement or end of switch block (End Of SWT)

16   Default case will be executed if there is no match, and statements thereafter till break or EOS.

17.  Important Points about overloading & overriding

        a) Methods can be overloaded on number, type and order of arguments.

        b) Static methods can be overloaded.

        c) Constructors can be overloaded. this( ) is used to call constructors in chain.

        d) Methods can't be overloaded on the basis of return type alone.

        e) When overloaded on the co variant types, conflict is resolved by the type of reference.

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

         f) Overriding Method should have same syntax and return type as Overridden method. If the                    number and type of arguments varies, it becomes overloading. If the  return type is different,                compiler gives compilation error i.e "The return type is incompatible with                                            BaseClass.overriddenMethod()".

          g) No Explicit cast is required in case of Upcasting i.e derived class reference is assigned to                     Base class reference but explicit cast is required in case of  downcasting i.e Base Class                         reference is assigned to Derived class reference.

          h) Downcasting may throw ClassCastException if object is found to be non compatible during                  runtime. That's why instanceof check should be made before doing  the downcast.

          i)  Overridding method cannot throw checked exception wider than the exception thrown by                    the overriden method. If the overridden method doesn't throw any  exception, overriding                      method can throw any exception.

          j)  We cannot reduce the visibility of the overridden method. Means If the method in base class                is public, we cannot declare it private in derived class.

          k) Only instance methods can be overridden. Static methods and instance / static variables                        cannot be overridden.

          l) Final methods cannot be overridden.

         m) If a method cannot be inherited, It cannot be overridden. So private methods cannot be                          overridden.


Top Interview Questions asked for Java Developer

 Q1. What are 4 different OOPS principal in java ??


    Abstraction -
           Abstraction is a design level or logical concept and doesn’t include programming approach.
            It is a process of hiding the detail-information from the end users, and exposing only the essential  features of a particular object. Data Hiding is a ability of objects to shields the variables from external access.

    Encapsulation - Encapsulation means data hiding.
           Encapsulation is a mechanism by which you restrict the access to some of the object's components, as well as binding the data and methods operating on the data by writing class.

    Inheritance - Inheritance is a process where child class acquires the properties of super class.

    Polymorphism -
        Compile time polymorphism - can be achieved by using Method overloading.
        Runtime polymorphism - Runtime polymorphism can be achieved by using Method overriding.
                                                  Runtime polymorphism is not applicable on final, due to not override.

Q2. Can overriding of hashcode() method cause any performance issues ??

Improper implementation of hashCode() can cause performance issues, because in that most of the key-value pairs will be stored on same bucket location and unnecessary time will be consumed while fetching value corresponding to key.

Q3. What are immutable classes in java? How we can create immutable classes in java?

Any change made to object of immutable class produces new object.
Example- String is Immutable class in java, Integer, Double, Long, Short, Byte etc are also.

We must follow following steps for creating immutable classes -

1) Final class - Make class final so that it cannot be inherited
2) private member variable-Making member variables private ensure fields can't be accessed outside class.
3) final member variable-Make member variables final so that once assigned their values cannot be changed
4) Constructor - Initialize all fields in constructor. assign all mutable member variable using new keyword.
5) Don't provide setter methods in class/ provide only getter methods.


 Q4. What is cloning in java ??

Cloning is done for copying the object, cloning can be done using shallow or deep copy.

Few key points about clone method -

    1) Definition of clone method -

           protected native Object clone() throws CloneNotSupportedException;

    Clone is a protected method - clone method can’t be called outside class without inheritance.
    Clone is native method, if not overridden its implementation is provided by JVM.
    It returns Object - Means explicitly cast is needed to convert it to original object.

    2) By default clone method do shallow copy.
    3) Class must implement marker interface java.lang.Cloneable. If class doesn’t implement Cloneable than   calling clone method on its object will throw CloneNotSupportedException.
    4) shallow copy- If we implement Cloneable interface, we must override clone method and call super.clone() from it, invoking super.clone() will do shallow copy.
    5) Deep copy - We need to provide custom implementation of clone method for deep copying.  When the copied object contains some other object its references are copied recursively in deep copy.


Q6. How can we ensure that all threads started from main must end in order in which they started i.e. ends with main ? 


We can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die.
Calling join() method internally calls join(0);

 class MyRunnable implements Runnable
{
    public void run(){
        System.out.println("in run() method");
           for(int i=0;i<5;i++){
                  System.out.println("i="+i+" ,ThreadName="+Thread.currentThread().getName());
           }         
    }
}

public class MyClass {
    public static void main(String...args) throws InterruptedException{
           System.out.println("In main() method");
           MyRunnable runnable=new MyRunnable();
           Thread thread1=new Thread(runnable);
           Thread thread2=new Thread(runnable);

           thread1.start();
           thread1.join();

           thread2.start();
           thread2.join();

           System.out.println("end main() method");
    }
}

/*OUTPUT IN SUCH MANNER

In main() method
in run() method
i=0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-0
i=2 ,ThreadName=Thread-0
i=3 ,ThreadName=Thread-0
i=4 ,ThreadName=Thread-0
in run() method
i=0 ,ThreadName=Thread-1
i=1 ,ThreadName=Thread-1
i=2 ,ThreadName=Thread-1
i=3 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-1
end main() method

*/
If we note output, all threads ended in order in which they were called and main thread has ended last.

First, main thread was called, it started Thread1 and then we called join() method on Thread1, once Thread1 ended main thread started Thread2 and we called join() method on Thread2, once Thread2 ended main thread also ended.


Q7. What is significance of using Volatile keyword?

Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables.
           If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.
 Volatile members are never cached in CPU by jvm, they are always read from main memory i.e. from stack where variable lives. It is possible for multiple CPU’s to exist on machine, so it is possibility that thread might cache different values in different CPU’s for same variable, so it’s important that value is not cached in CPU and always read from main memory.

 Let’s discuss a scenario where non-volatile variable is used :

int x=0;  // Let’s say we have variable x with value 0, in main memory value of x is 0 and in cache value of x is also 0.
x++;  //increment done by thread1, so now in main memory  value of x is 1 but it might happen somehow that value is not updated in cache, so value of x in cache is still 0.
Now, lets say thread2 try to read that value, as value is cached, it will read read value from cache only, so value read of x will be 0 (but actual value of x is 1), which of course is a synchronization problem.

Let’s discuss a scenario where volatile variable is used :
int x=0;  // Let’s say we have variable x with value 0, in main memory value of x is 0 and it’s not cached (as volatile variables are not cached).
x++;  //increment done by thread1, so now in main memory  value of x is 1 and it’s not cached.
Now, lets say thread2 try to read that value, as value is not cached, it will read read value from main memory, so value read of x will be 1 (and actual value of x is 1), we have solved synchronization problem.


Q8. Can transient variables be declared as final or static ?             Answer is NO

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.
Java classes often hold some globally relevant value in a static class variable,because it's loaded during the class loading time.
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.

There is just one exception to this rule, and it is when the transient final field member is initialized to a constant expression as those defined in the JLS 15.28. Hence, field members declared this way would hold their constant value expression even after deserializing the object. I guess that is so because the value of the final field is actually a constant expression as described by the JLS.

This example shows transient final fields that would hold their constant values even after deserializing the object:

class X implements Serializable
{
  transient static String transientStaticVar = "transientStaticVar";
  transient final String transientFinalVar = "transientFinalVar";
  transient static final String transientStaticFinalVar = "transientStaticFinalVar";
  transient String transientVar = "transientVar";
}

public class  Test {
  public static void main( String[] args ){
    try {
      ObjectOutputStream o = new ObjectOutputStream(
                      new FileOutputStream("logInfo.out"));
      X a = new X();
      System.out.println("Before Serialization ...");
      System.out.println("transientStaticVar = " + X.transientStaticVar);
      System.out.println("transientFinalVar = " + a.transientFinalVar);
      System.out.println("transientStaticFinalVar = " +
          X.transientStaticFinalVar);
      System.out.println("transientVar = " + a.transientVar);
      o.writeObject(a);
      o.close();
      X.transientStaticVar = "newTransientStaticVar";
    }
    catch(Exception e) {
      //deal with exception
    }

    try {

      ObjectInputStream in =new ObjectInputStream(
                             new FileInputStream("logInfo.out"));
      X x = (X)in.readObject();
      System.out.println("After Serialization ...");
      System.out.println("transientStaticVar = " + X.transientStaticVar);
      System.out.println("transientFinalVar = " + x.transientFinalVar);
      System.out.println("transientStaticFinalVar = " +
           X.transientStaticFinalVar);
      System.out.println("transientVar = " + x.transientVar);
    }
    catch(Exception e) {
      //deal with exception
    }

  }

}

The output results are:

Before Serialization ...
transientStaticVar = transientStaticVar
transientFinalVar = transientFinalVar
transientStaticFinalVar = transientStaticFinalVar
transientVar = transientVar
After Serialization ...
transientStaticVar = newTransientStaticVar
transientFinalVar = transientFinalVar
transientStaticFinalVar = transientStaticFinalVar
transientVar = null
If we change the way to initialize final variables, you have different variable and you can do not initialize them during the serialization process because they are final.

class X implements Serializable {
  transient static String transientStaticVar;
  transient final String transientFinalVar;
  transient static final String transientStaticFinalVar;
  transient String transientVar = "transientVar";

  static {
    transientStaticVar = "transientStaticVar"
    transientStaticFinalVar = "transientStaticFinalVar";
  }

  {
    transientFinalVar = "transientFinalVar";
  }

}

public class  Test {
  public static void main( String[] args ){
    try {
      ObjectOutputStream o = new ObjectOutputStream(
                      new FileOutputStream("logInfo.out"));
      X a = new X();
      System.out.println("Before Serialization ...");
      System.out.println("transientStaticVar = " + X.transientStaticVar);
      System.out.println("transientFinalVar = " + a.transientFinalVar);
      System.out.println("transientStaticFinalVar = " +
          X.transientStaticFinalVar);
      System.out.println("transientVar = " + a.transientVar);
      o.writeObject(a);
      o.close();
      X.transientStaticVar = "newTransientStaticVar";
    }
    catch(Exception e) {
      //deal with exception
    }

    try {

      ObjectInputStream in =new ObjectInputStream(
                             new FileInputStream("logInfo.out"));
      X x = (X)in.readObject();
      System.out.println("After Serialization ...");
      System.out.println("transientStaticVar = " + X.transientStaticVar);
      System.out.println("transientFinalVar = " + x.transientFinalVar);
      System.out.println("transientStaticFinalVar = " +
          X.transientStaticFinalVar);
      System.out.println("transientVar = " + x.transientVar);
    }
    catch(Exception e) {
      //deal with exception
    }

  }

}

The output results are:

Before Serialization ...
transientStaticVar = transientStaticVar
transientFinalVar = transientFinalVar
transientStaticFinalVar = transientStaticFinalVar
transientVar = transientVar
After Serialization ...
transientStaticVar = newTransientStaticVar
transientFinalVar = null
transientStaticFinalVar = transientStaticFinalVar
transientVar = null


Surprisingly, the java compiler does not complaint if you declare a static member field as transient or a final member field as transient in your classes. These should be compile-time errors. Because a "transient" part of an object's state is assumed to be changing within each instance,
it can not be static or final. Similarly, a "volatile" variable cannot be final (constant). This restriction matters only in the future, though, when transient and volatile are actually used by Java.



Question: Which of the following is true?
A. transient methods must be static
B. native methods violate Java's platform independence.
C. static methods cannot be protected
D. transient variables may not be final or static

Answer:
A is incorrect as the modifier transient applies to variables only.

B is correct  because native methods execute code which lies entirely outside the Java Virtual Machine, this code is compiled for a specific targeted machine and hence makes the application platform independent thereby violating Java's platform independence.

C is incorrect as there is nothing wrong in static methods being protected.

D is correct as transient variables may not be final or static.


Q9. Can static methods be overridden?          Answer is No

If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.

If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method.

In this respect, hiding of methods differs from hiding of fields, for it is permissible for a static variable to hide an instance variable. Hiding is also distinct from shadowing and obscuring.

A hidden method can be accessed by using a qualified name or by using a method invocation expression that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.

Let's look at an example. This example contains two classes. The first is Animal, which contains one instance method and one class method:

public class Animal {
    public static void hide() {
        System.out.format("The hide method in Animal.%n");
    }
    public void override() {
        System.out.format("The override method in Animal.%n");
    }
}
The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void hide() {
        System.out.format("The hide method in Cat.%n");
    }
    public void override() {
        System.out.format("The override method in Cat.%n");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        System.out.println("Create a Cat instance ...");
        myCat.hide();
        Cat.hide();
        myCat.override();
     
        Animal myAnimal = myCat;
        System.out.println("\nCast the Cat instance to Animal...");
        myAnimal.hide();   //BAD STYLE
        Animal.hide();     //Better!
        myAnimal.override();

        Animal myAnimal1 = new Animal();
        System.out.println("\nCreate an Animal instance....");
        myAnimal1.hide();   //BAD STYLE
        Animal.hide();     //Better!
        myAnimal1.override();
    }
}
The output results are:

Create a Cat instance ...
The hide method in Cat.
The hide method in Cat.
The override method in Cat.

Cast the Cat instance to Animal...
The hide method in Animal.
The hide method in Animal.
The override method in Cat.

Create an Animal instance....
The hide method in Animal.
The hide method in Animal.
The override method in Animal.
There are three sections in this example. The first and third ones are normal. The second one is wired one, we cast the Cat type instance to it's parent Animal type. myAnimal.hide() invoke the static method defined in the Animal class.  If this method were truly overridden, we should have invoked static hide() method defined in Cat class, but we didn't.

It is considered bad style to call static methods on instances because hiding can be confusing. So it is better to use the class, for example Animal.hide or Cat.hide. The output from this program is as follows:

The hide method in Animal.
The override method in Cat.
The version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

For class methods, the runtime system invokes the method defined in the compile-time type of the reference on which the method is called. In other words, call to static methods are mapped at the compile time and depends on the declared type of the reference(Parent in this case) and not the instance the reference points at runtime. In the example, the compile-time type of myAnimal is Animal. Thus, the runtime system invokes the hide method defined in Animal.

For instance methods, the runtime system invokes the method defined in the runtime type of the reference on which the method is called. In the example, the runtime type of myAnimal is Cat. Thus, the runtime system invokes the override method defined in Cat.

An instance method cannot override a static method, and a static method cannot hide an instance method. The following table summarizes what happens when you define a method with the same signature as a method in a superclass.

How to access the static methods defined in the superclass?

A hidden method can be accessed by using a qualified name or by using a method invocation expression that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.

public class Cat extends Animal {
    public static void hide() {
        System.out.format("The hide method in Cat.%n");
    }
    public void override() {
        hide(); //Access Cat's hide() method
        super.hide(); //Access Animal's hide() method
        Animal.hide(); //Access Animal's hide() method
        System.out.format("The override method in Cat.%n");
    }

    public static void main(String[] args) {
           ....
    }
}


Q 10. What is parameters passed by reference or passed by value in method invocation?

In programming, there are two ways to pass arguments to a method, pass-by-value and pass-by-reference:
When you have a pass-by-value parameter, a copy of the argument is stored into the memory location allocated for the formal parameter. In this case, any changes made to the formal parameter inside the method will not affect the value of the argument back in the calling method.
When a parameter is pass-by-reference, the memory address of the argument is passed to the method, making the formal parameter an alias for the argument. This means that changes made to the formal parameter inside the method will be reflected in the value of the argument when control is returned to the calling function.

Technically, all parameters in Java are pass-by-value.

All primitives are pass-by-value, period. When a primitive value is passed into a method, a copy of the primitive is made. The copy is what is actually manipulated in the method. So, the value of the copy can be changed within the method, but the original value remains unchanged.

For example:

public class TestPassPrimitive {
  static void doSomething(int m) {
    m = m + 2;
    System.out.println("The new value is " + m + ".");
  }
  public static void main(String[] args) {
    int m = 5;
    System.out.println("Before doSomething, m is " + m + ".");
    doSomething(m);
    System.out.println("After doSomething, m is " + m + ".");
  }
}

The output result is

Before doSomething, m is 5.
The new value is 7.
After doSomething, m is 5.


Objects, however, work a bit differently. When you pass a Java object or array as a parameter, an object reference or array reference is passed into a method. The method can manipulate the attributes of the object that is referenced by the reference (formal parameter).

This reference is passed-by-value. What does this mean exactly?

Any direct changes made to the reference (formal parameter) inside the method will be reflected in the value of the object back in the calling method;

If you were to reassigns a new instantiation of an object or array to the reference (formal parameter) within the method, the reassignment only affects the copy reference (formal parameter), not the original reference passed by the caller. After that, any direct changes made to the reference (formal parameter) inside the method will be reflected the new reassigned object or array.

For example:

class TestReferenceParameter{
  public static void main (String args[]) {
    String s1 = "one";
    String s2 = doSomething(s1);
    System.out.println(s1 + " " + s2);
  }


  static String doSomething(String s1) {
    s1 = s1 + " two";
    System.out.println(s1 + " ");
    return "three";
  }
}
The output result is

one two
one three


Q11.What is the role for a ClassLoader in Java?

A Java program is made up of a number of custom classes (written by programmers like us) and core classes (which come pre-packaged with Java). When a program is executed, JVM needs to load the content of all the needed class. JVM uses a ClassLoader to find the classes.

Three Java Class Loaders are shown here


1)    System Class Loader - Loads all classes from CLASSPATH
2)    Extension Class Loader - Loads all classes from extension directory
3)    Bootstrap Class Loader - Loads all the Java core files

When JVM needs to find a class, it starts with System Class Loader. If it is not found, it checks with Extension Class Loader. If it not found, it goes to the Bootstrap Class Loader. If a class is still not found, a ClassNotFoundException is thrown.

JSP interview questions and answers

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