Friday, 2 September 2016

Java interview Questions and answers for Experience

                          (Courtesy : Wiki,StackOverFlow,MyInterviewExp,javaDocs,NPTEL)
                                                                             
Basic Concepts:
  1. Class vs Interface vs Abstract class.
  2. Static variables.
  3. final variables.
  4. Access modifiers - Public, Private, Default, Protected.
  5. Immutable Strings and String manipulation concepts.
  6. Object lifecycle - How objects are created and destroyed.

Threads:
  1. Thread Dump analysis
  2. Producer Consumer problem
  3. Dead lock problem
  4. Synchronization
  5. Thread creation lifecycle
  6. Priority
  7. Sleep
  8. Is Alive
  9. Join

Core:
  1. JVM Internals
  2. ClassLoaders
  3. Reflections
  4. Periodic task threads
  5. GC threads
  6. Compiler threads
  7. Signal dispatcher thread

Design Patterns:
  1. Singleton
  2. Adapter
  3. Lazy loading
  4. Builder vs fluent 
  5. Observer Patterns

Heap Management:
  1. Young Generation
  2. Old Generation (also called Tenured Generation)
  3. Permanent Generation
  4. JIT: Native code compilation

1. How to put array into ArrayList.
Answer:  I Have An Array That Is Initialized Like:
                  Element[] Array = {New Element(1), New Element(2), New Element(3)};
               I Would Like To Convert This Array Into An Object Of The ArrayList Class.
                  ArrayList<Element> Arraylist = ???;

                  new ArrayList<Element>(Arrays.asList(array))


2. How can I create an executable JAR with dependencies using Maven?

 

Refer below link

http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven



There are several ways to iterate over map.
Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.
1) Using entrySet() in for each loop

for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
    entry.getKey();
    entry.getValue();
}

2) Using keySet() in for each loop

for (String key : testMap.keySet()) {
    testMap.get(key);
}

3) Using entrySet() and iterator

Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
while(itr1.hasNext()) {
    Map.Entry<String,Integer> entry = itr1.next();
    entry.getKey();
    entry.getValue();
}

4) Using keySet() and iterator

Iterator itr2 = testMap.keySet().iterator();
while(itr2.hasNext()) {
    String key = itr2.next();
    testMap.get(key);
}


I Have A String[] With Values Like So:
Public Static Final String[] VALUES = New String[] {"AB","BC","CD","AE"};
Given String S, Is There A Good Way Of Testing Whether VALUES Contains S?


1) Using List:
public static boolean useList(String[] arr, String targetValue) {
    return Arrays.asList(arr).contains(targetValue);
}
2) Using Set:
public static boolean useSet(String[] arr, String targetValue) {
    Set<String> set = new HashSet<String>(Arrays.asList(arr));
    return set.contains(targetValue);
}
3) Using a simple loop:
public static boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}
4) Using Arrays.binarySearch():
The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.
public static boolean binarySearch(String[] arr, String targetValue) { 
            int a =  Arrays.binarySearch(arr, targetValue);
            if(a > 0)
                return true;
            else
                return false;
        }
Quick Example:-
String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); \\returns true
Arrays.asList(valueArray).contains(newValueNotInList); \\returns false






There are several differences between HashMap and Hashtable in Java:
1.    Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
2.    Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
3.    One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.


6.  what are the advantages of using enhanced for loop against iterator in java.what are the advantages of using enhanced for loop in java and why was it introduced in java at the first place when the iterator could do the job.?

it is cleaner, more concise and safer (e.g. avoids specific subtle bugs in multiple embedded loops, when the iterator is accidentally incremented too often by calling next() too many times).
Code sample (from 
Effective Java 2nd Edition, Item 46: Prefer for-each loops to traditional for loops):
// Can you spot the bug?
enum Suit { CLUB, DIAMOND, HEART, SPADE }
enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT,
NINE, TEN, JACK, QUEEN, KING }
...
Collection<Suit> suits = Arrays.asList(Suit.values());
Collection<Rank> ranks = Arrays.asList(Rank.values());
List<Card> deck = new ArrayList<Card>();
for (Iterator<Suit> i = suits.iterator(); i.hasNext(); )
  for (Iterator<Rank> j = ranks.iterator(); j.hasNext(); )
    deck.add(new Card(i.next(), j.next()));




Q 7) What is use of serialVersionUID?

Ans) The default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If notInvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree
List of incompatible changes:
Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field
So, if no suid is present, inspite of making compatible changes, jvm generates new suidthus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
If we explicitly mention the sUid using the statement:
private final static long serialVersionUID = <integer value>
then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.


Ques. Is it possible to use serialization and deserialization with a singleton-pattern class C in a way that does not break the singleton pattern?"
The answer is basically yes:



package com.array;
import java.util.*;

class RemoveDuplicatesInArray{

    public static void main(String[] args) {
        Integer[] array = new Integer[10];

        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 3;
        array[4] = 3;
        array[5] = 3;
        array[6] = 7;
        array[7] = 7;
        array[8] = 9;
        array[9] = 9;
        removeDuplicatesFromArray(array);

    }


    private static void removeDuplicatesFromArray(Integer[] array){
        StringBuffer stringBuffer = new StringBuffer();
         String arrayString =  Arrays.toString(array);
         for(int index =0 ; index <= arrayString.length(); index++){
          try{
              int number = Integer.parseInt(arrayString.charAt(index)+"");
              if(!stringBuffer.toString().contains(number+"")){
              if(stringBuffer.length()!=0)
                  stringBuffer.append(",");
                 stringBuffer.append(number);
              }

          }catch(Exception e){

          }
         }
         String[] stringArray = stringBuffer.toString().split(",");
         array = new Integer[stringArray.length];
         for(int index = 0 ; index < stringArray.length ; index++){
           array[index] = Integer.parseInt(stringArray[index]);
         }
         System.out.println(Arrays.toString(array));
      }

 

9.) Which of the following would you choose recommended when and where?

ArrayList<SomeType> a = new ArrayList<SomeType>(); or
List<SomeType> a = new ArrayList<SomeType>();



Second is better cause you can simply change underlying implementation from ArrayList to LinkedList (or to any proper implementation) by one line code change.
clone()-----returns the reference of an object in the memory

copy()------copy the structure and data of the object.


 

11.) What is Busy Spinning? Why Should You Use It in Java?

·        
One of the interesting multithreading question to senior Java programmers, busy spinning is a waiting strategy, in which a thread just wait in a loop, without releasing the CPU for going to sleep. This is a very advanced and specialized waiting strategy used in the high-frequency trading application when wait time between two messages is very minimal.

By not releasing the CPU or
 suspending the thread, your thread retains all the cached data and instruction, which may be lost if the thread was suspended and resumed back in a different core of CPU.

This question is quite popular in high-frequency low latency programming domain, where programmers are trying for extremely low latency in the range of micro to milliseconds.

12.)What is Read-Write Lock? Does ConcurrentHashMap in Java Uses The ReadWrite Lock?

·        
ReadWrite Lock is an implementation of lock stripping technique, where two separate locks are used for read and write operation. Since read operation doesn't modify the state of the object, it's safe to allow multiple thread access to a shared object for reading without locking, and by splitting one lock into read and write lock, you can easily do that. 

Question 13) How  do you prevent SQL Injection in Java Code?

·        
This question is more asked to J2EE and Java EE developers than core Java developers, but, it is still a good question to check the JDBC and Security skill of experienced Java programmers.

You can
 use PreparedStatement to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack.


 

Question 14) Why Should an Object Used As the Key should be Immutable? 

·        
This is another follow-up of previous core Java interview questions. It's good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method  always return the same value.
·          
·         Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable. It's not a rule enforced by the compiler but you should take care of it as an experienced programmer. 


Question 15) How does ConcurrentHashMap achieves its Scalability? 

·        
Sometimes this multithreading + collection interview question is also asked as, the difference between ConcurrentHashMap and Hashtable in Java. The problem with synchronized HashMap or Hashtable was that whole Map is locked when a thread performs any operation with Map.

The
 java.util.ConcurrentHashMap class solves this problem by using lock stripping technique, where the whole map is locked at different segments and only a particular segment is locked during the write operation, not the whole map. The ConcurrentHashMap also achieves it's scalability by allowing lock-free reads as read is a thread-safe operation.

 

Question 16) How do find if your program has a deadlock?


By taking thread dump using kill -3, using JConsole or VisualVM), I suggest to prepare this core java interview question in more detail, as Interviewer definitely likes to go with more detail e.g. they will press with questions like, have you really done that in your project or not?


Question 17) How do you avoid deadlock while coding?

By ensuring locks are acquire and released in an ordered manner.
18) Difference between transient and volatile in Java? (detailed answer)

transient keyword is used in Serialization while volatile is used in multi-threading. If you want to exclude a variable from serialization process then mark that variable transient. Similar to static variable, transient variables are not serialized. On the other hand, volatile variables are signal to compiler that multiple threads are interested on this variable and it shouldn't reorder its access. volatile variable also follows happens-before relationship, which means any write happens before any read in volatile variable. You can also make non atomic access of double and long variable atomic using volatile.

 

19) How to check if linked list contains loop in Java?

Two pointers, fast and slow is used while iterating over linked list. Fast pointer moves two nodes in each iteration, while slow pointer moves to one node. If linked list contains loop or cycle than both fast and slow pointer will meet at some point during iteration. If they don't meet and fast or slow will point to null, then linked list is not cyclic and it doesn't contain any loop. Here is the exact algorithm
1) Use two pointers fast and slow
2) Move fast two nodes and slow one node in each iteration
3) If fast and slow meet then linked list contains cycle
4) if fast points to null or fast.next points to null then linked list is not cyclic

 

20.) Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

Between association, composition and aggregation, composition is strongest. If part can exists without whole than relationship between two class is known as aggregation but if part cannot exists without whole than relationship between two class is known as composition. Between Inheritance and composition, later provides more flexible design.

21) How do you convert bytes to character in Java? (detailed answer)
Bytes are converted to character or text data using character encoding. When you read binary data from a file or network endpoint, you provide a character encoding to convert those bytes to equivalent character. Incorrect choice of character encoding may alter meaning of message by interpreting it differently.

 

 

22) What is difference between FileInputStream and FileReader in Java? (detailed answer)


Main difference between FileInputStream and FileReader is that former is used to read binary data while later is used to read text data, which means later also consider character encoding while converting bytes to text in Java.

23) Write a Program to solve Producer Consumer problem in Java? (solution)


A very good question to check if candidate can write inter thread communication code or not. If a guy can write producer consumer solution by hand and point out critical section and how to protect, how to communicate with thread then he is good enough to write and maintain your concurrent Java program. This is the very minimum requirement for a Java developer and that's why I love this question, it also has several solution e.g. by using concurrent collections like blocking queue, by using wait and notify and by using other synchronizers of Java 5 e.g. semaphores.


24) What is equlas() and hashCode() contract in Java? Where does it used? (detailed answer)


One of the must ask question in Java telephonic interview. If a guy doesn't know about 
equals() and hashCode() then he is probably not worth pursuing further because it’s the core of the Java fundamentals. The key point of contract is that if two objects are equal by equals() method then they must have same hashcode, but unequal object can also have same hashcode, which is the cause of collision on hash table based collection e.g HashMap. When you override equals() you must remember to override hashCode() method to keep the contract valid.

 

25) Why wait and notify methods are declared in Object class? (detailed answer)


This question is more to find out how much experience you really have and what is your thinking towards Java API and its design decision. Similar question is why String is immutable in Java? Well, true answer can only be given by Java designers but you can reason something. For example, wait and notify methods are associated with locks which is owned by object not thread, and that's why it make sense to keep those method on java.lang.Object class. See the detailed answer for more discussion and reasoning.

34) What is difference between Iterator and Enumeration in Java? (detailed answer)


Main difference is that Iterator was introduced in place of Enumeration. It also allows you to remove elements from collection while traversing which was not possible with Enumeration. The methods of Iterator e.g. 
hasNext() and next() are also more concise then corresponding methods in Enumeration e.g. hasMoreElements(). You should always use Iterator in your Java code as Enumeration may get deprecated and removed in future Java release.


35) Difference between static and dynamic binding in Java? (detailed answer)


This is usually asked as follow-up of previous question, static binding is related to overloaded method and dynamic binding is related to overridden method. Method like private, final and static are resolved using static binding at compile time but virtual methods which can be overridden are resolved using dynamic binding at runtime


36) Difference between Comparator and Comparable in Java? (detailed answer)

This is one more basic concept, I expect every Java candidate to know. You will deal with them on every Java project. Several core classes in Java e.g. String, Integer implements Comparable to define their natural sorting order and if you define a value class or a domain object then you should also implement Comparable and define natural ordering of your object. Main difference between these two is that, you could create multiple Comparator to define multiple sorting order based upon different attribute of object. Also, In order to implement Comparable you must have access of the class or code, but you can use Comparator without having source code of class, all you need is the JAR file of particular object. That's why Comparator is very powerful to implement custom sorting order and from Java 8 you can do it even more elegantly, as seen here.


37) How do you sort ArrayList in descending order? (solution)

You can use 
Collections.sort() method with reverse Comparator, which can sort elements in the reverse order of their natural order e.g.

List<String> listOfString = Arrays.asList("Narendra", "Pankaj", "Leo");
Collections.sort(listOfString, Collections.reverseOrder());
System.out.println(listOfString); //[ Leo,Narendra,Pankaj]


38.) Why use Inner class.
I would say Inner class is never mandatory or necessary, there is always workaround
But at some places they are convinience like in Map.Entry, Iterator inside List, or
listener in GUI.
The use is to increase encapsulation and hide some implementation details.
Classes like Semaphore use internal objects for locking, etc.

How to ensure that instance is never garbage collected.
A singleton kind of pattern.
There's a static reference to a singleton, so it won't be eligible for garbage collection until the
classloader is eligible for garbage collection.

I will explain it later In depth 



39) Which one would be easy to write? synchronization code for 10 threads or 2 threads?

In terms of writing code, both will be of same complexity because synchronization code is independent of a number of threads. Choice of synchronization though depends upon a number of threads because the number of thread present more contention, so you go for advanced synchronization technique e.g. lock stripping, which requires more complex code and expertise.


40) How do you call wait() method? using if block or loop? Why? (answer)

wait() method should always be called in loop because it's possible that until thread gets CPU to start running again the condition might not hold, so its always better to check condition in loop before proceeding. Here is the standard idiom of using wait and notify method in Java:

// The standard idiom for using the wait method
synchronized (obj) {
   while (condition does not hold)
      obj.wait(); // (Releases lock, and reacquires on wakeup)
      ... // Perform action appropriate to condition
}


41) Can we create an Immutable object, which contains a mutable object?

Yes, its possible to create an Immutable object which may contain a mutable object, you just need to be a little bit careful not to share the reference of the mutable component, instead, you should return a copy of it if you have to. Most common example is an Object which contain the reference of
 java.util.Date object.

42) Can we use String in the switch case? (answer)

Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch.

43.) What is the difference between JRE, JDK, JVM and JIT? (answer)

JRE stands for Java run-time and it's required to run Java application. JDK stands for Java development kit and provides tools to develop Java program e.g. Java compiler. It also contains JRE. The JVM stands for Java virtual machine and it's the process responsible for running Java application. The JIT stands for Just In Time compilation and helps to boost the performance of Java application by converting Java byte code into native code when the crossed certain threshold i.e. mainly hot code is converted into native code.

Java Interview Questions for 3 years experience

44) What is the difference between stack and heap in Java? (answer)

Stack and heap are different memory areas in the JVM and they are used for different purposes. The stack is used to hold method frames and local variables while objects are always allocated memory from the heap. The stack is usually much smaller than heap memory and also didn't shared between multiple threads, but heap is shared among all threads in JVM.

45) What is a compile time constant in Java? What is the risk of using it?
·        
public static final variables are also known as a compile time constant, the public is optional there. They are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time. One of the problem with this is that if you happened to use a public static final variable from some in-house or third party library and their value changed later than your client will still be using old value even after you deploy a new version of JARs. To avoid that, make sure you compile your program when you upgrade dependency JAR files.


·         46. Describe and compare fail-fast and fail-safe iterators. Give examples.
The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.
·         Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayListHashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).
·         Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.


Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.
In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.


Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.


sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.
wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.
sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.

 

What is the Java Classloader? List and explain the purpose of the three types of class loaders.


The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.
When the JVM is started, three class loaders are used:
1. Bootstrap Classloader: Loads core java API file rt.jar from folder. 2.Extension Classloader: Loads jar files from folder. 3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.


What variance is imposed on generic type parameters? How much control does Java give you over this?


Java’s generic type parameters are invariant. This means for any distinct types A and BG<A> is not a subtype or supertype of G<B>. As a real world example, List<String> is not a supertype or subtype of List<Object>. So even though String extends (i.e. is a subtype of) Object, both of the following assignments will fail to compile:
        List<String> strings = Arrays.<Object>asList("hi there");
        List<Object> objects = Arrays.<String>asList("hi there");


What are static initializers and when would you use them? A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.
They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do.
Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:


What is the difference between poll() and remove() method in collection framework?
The remove() and poll() methods differ only in their behavior when the queue is empty:
the remove() method throws an exception,
while the poll() method returns null.


How to Create immutable Class in java?
To create immutable class in java, you have to do following steps.
1.    Declare the class as final so it can’t be extended.
2.    Make all fields private so that direct access is not allowed.
3.    Don’t provide setter methods for variables
4.    Make all mutable fields final so that it’s value can be assigned only once.
5.    Initialize all the fields via a constructor performing deep copy.
6.    Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}


What is Static Import in java:
The static import feature of Java 5 facilitates the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

Advantage of static import:

  • Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:

  • If you overuse the static import feature, it makes the program unreadable and unmaintainable.

Simple Example of static import

import static java.lang.System.*;    
class StaticImportExample{  
  public static void main(String args[]){  
     
   out.println("Hello");//Now no need of System.out  
   out.println("Java");  
  
 }   
}  
      

 s