Core Java

What are the New Features in Java
Important features of Java 8
----------------------
Lambda Expressions
Default Methods with body in interface
Static Methods with body in interface
Functional Interfaces
Nashorn- JAVA based engine to execute JavaScript code.
New API java.util.stream
New API java.util.function
New API java.time

Important features of Java 7
----------------------
Binary Literals
Underscore in Numeric Literals
String in switch Statement
Handling Multiple Exception in catch
try with Resources
Autocloseable interface in java.lang package to support try with resource
java.nio Package
Diamond Operator <>

Important features of Java 6
----------------------
Java Compiler API that helps to develop online compiler.
JDBC 4.0 API that contains Auto Driver loading and many more features.
isEmpty() method in String class

Important features of Java 5
----------------------
Hexadecimal Floating Point Notations
enum keyword
enum in switch statement
Enhanced for statement aka for each statement
Varargs
Covarient Return Type
Autoboxing and Auto-Unboxing
Static Import
Generics
Annotations

Important Methods and API in Java 5
-------------------
getEnv(String) & getEnv() in System class
parseBoolean() in Boolean class
StringBuilder class in java.lang package
Scanner class and Formatter class in java.util package
Concurrency API in java.util.concurrent package
API to create Thread Pool like Executor and ExecutorService
ConcurrentHashMap class to solve problem of HashMap
PriorityBlockingQueue Class to implement problem like producer-consumer
Lock, Semaphore, CyclicBarrier etc for Threading

New features of Java 2
----------------------
assert keyword for Assertions
JDBC 3.0 API
API for logging

Regular Expressions for validating inputs.


Sort Java ArrayList in descending order using comparator?
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SortArrayListInDescendingOrderExample
{
 public static void main(String[] args){
ArrayList<String> arrayList =  new ArrayList<String>();
           arrayList.add("A");
           arrayList.add("B");
           arrayList.add("C");
           arrayList.add("D");
          arrayList.add("E");              
 Comparator comparator = Collections.reverseOrder();
 Collections.sort(arrayList,comparator);
 System.out.println("After sorting ArrayList in descending order : " + arrayList);
           }
}

What is difference between HashMap and Hashtable?
HashMapHashtable
1) HashMap is not synchronized.1) Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values.2) Hashtable cannot contain any null key nor value.

How to remove duplicate element from a ArrayList?
By converting the ArrayList into HashSet. When you convert a ArrayList to HashSet all duplicates elements will be removed but insertion order of the element will be lost.
But if you would like to preserve the order of data use LinkedHashSet rather HashSet
Example:-
public class RemDupFromList {
    public static void main(String[] args)
    {
        List li = new ArrayList();
              li.add("one");
              li.add("two");
              li.add("three");
              li.add("one");//Duplicate
              li.add("one");//Duplicate
             // We have facility to pass a List into Set constructor and vice verse to cast     
                List li2 = new ArrayList(new HashSet(li)); //no order
             // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve
                                                                                           // the order use 'LinkedHashSet'        
              Iterator it= li2.iterator();
             while(it.hasNext())
             {
                 System.out.println(it.next());
             }
    }
}
Output
one
two
three
Find duplicate elements in an array
By using Collections.frequency(),we can find duplicate elements in array.
import java.util.HashSet;
import java.util.Set;
public class DuplicateInArray
{
public static void main(String[] args)
{
int[] array = {1,1,2,3,4,5,6,7,8,8};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < array.length ; i++)
{
//If same integer is already present then add method will return FALSE
if(set.add(array[i]) == false)
{
System.out.println("Duplicate element found : " + array[i]);
}
}
}
}

Output:
Duplicate element found : 1
Duplicate element found : 8
In this solution, all you have to do is to iterate over array and all elements in a set one by one. If Set.add() method returns false then element is already present in set and thus it is duplicate.

Why String is immutable in Java?
In Java, strings are object. There are many different ways to create a String object. One of them is using string literals.

Each time a string literal is created, JVM checks the string constant pool first. If string already exist in the pool, a reference to the pool instance is returned. Sometime it is possible that one string literals is referenced by many reference variable. So if any of them change the string, other will also get affected. This is the prominent reason why string object is immutable.
What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.
    class Simple{ 
     public static void main(String args[]){ 
       String s="Sachin"; 
       s.concat(" Tendulkar");//concat() method appends the string at the end 
       System.out.println(s);//will print Sachin because strings are immutable objects 
     } 
    } 
Output:Sachin

Example to create Immutable class
In this example, we have created a final class named Employee. It have one final data member, a parameterized constructor and getter method.
    public final class Employee{ 
    final String pancardNumber
     
    public Employee(String pancardNumber){ 
    this.pancardNumber=pancardNumber
    } 
    public String getPancardNumber(){ 
    return pancardNumber
    } 
    } 

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

When we have to override equals and hashcode in java..?
what will happened if you don't override?
These methods are usually overridden when you want 
use objects of that type as keys in data structures like hashtables.
Whenever overriding the equals method is recommended to also override the hashCode method. That is because there must be a relationship between these two methods: equal objects must have equal hash codes, but non-equal objects can have the same hash code.

If the methods are not overridden , then using them as keys in a hashtable is practically impossible (inefficient). By default equals returns true if the two reference variables refer to the same object , and hashCode returns different hash codes for different objects.
How HashMap  works in Java?
HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.

When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.


When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.
When to use LinkedList and ArrayList in Java?
1.The insert and remove operations give good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Hence if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice.
2.Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet.
Accessing elements are faster with ArrayList, because it is index based.But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes.
Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.



What is the difference between "path" and "classpath"?
We keep all "executable files"(like .exe files) and "batch files"(like .bat) in path variable. And we keep all jar files and class files in classpath variables.

What is the difference in precision the java.util.Date and java.sql.Date?A. java.util.Date includes time and java.sql.Date does not
How to convert String to Number in java program?
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
What is difference between "abc".equals(unknown string) and unknown.equals("abc")? 
(former is safe from NullPointerException).
How can one call one constructor from another constructor in a class?
Use the this() method to refer to constructors.
What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.
We have Abstract class still why we need Interface?
if we use more common functionality we can use interface,but if use use common functionality as well some other functionality we use abstract class.
What is the Role of Private Constructor?
If you make any class constructor private, you cannot create the instance of that class from outside the class. 
What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
class Bike{ 
int cube(final int n){ 
n=n+2; //can't be changed as n is final 
n*n*n; 

public static void main(String args[]){ 
Bike b=new Bike(); 
b.cube(5); 


What will happen if we put a key object in a HashMap which is already there ?
if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.


What is the difference between SAX and DOM xml parsing?A: SAX is event driven and does not load all of the XML data into memory while DOM parses and loads the entire document into memory.
Java 8 - Journey of for loop in Java, for(index) to forEach()
package test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/** * Java Program to demonstrate different ways to loop over collection in * pre Java 8 and Java 8 world using Stream's forEach method. 
* @author Javin Paul */

public class JourneyOfForLoopInJava {
public static void main(String args[]) throws IOException {

// pre JDK 1.5, printing each element of List using for loop 
List < String > countries = Arrays.asList("India", "Australia", "England", "South Africa");
for (int i = 0; i < countries.size(); i++) {
System.out.println(countries.get(i));
}
// In Java 5, we god advanced for loop, which makes it easy to loop over 
// List or Collection 
for (String country: countries) {
System.out.println(country);
}
// In Java 8, you can use forEach method of Stream class to loop over 
// any List or Collection 
countries.stream().forEach(str - > System.out.println(str));
// doing some pre-processing filtering on our list 
// will print India, England as only they contain "n" 
countries.stream()
             .filter(country - > country.contains("n"))
             .forEach(str - > System.out.println(str));
// making the code more concise using method reference 
countries.stream()
           .filter(country - > country.contains("n"))
           .forEach(System.out::println);
}
}

Note:-forEach() method of java.util.Stream class
What is difference between Checked Exception and Unchecked Exception?
1)Checked Exception: Checked exceptions are checked at compile-time.
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. 
2)Unchecked Exception:unchecked exceptions are caught during runtime only and hence can't be checked.
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException etc.
Give an Example of checked and unchecked exception ?
ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked exception.
What is the base class for Error and Exception?
Throwable.
How to solve a NullPointerException in Java?
1.It is simple, do a null check e.g. name != null Surround your object with if statement like
For Example:-
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}
2) we can use the fact that equals method return false if we compare it will null e.g. if we write code like "java".equals(name) we will not get any NullPointerException, instead it will return false.
Common cause of NullPointerException in Java as Example
1)  Java  NullPointerException while calling instance method on null object
Trade pennyStock = null;
pennyStock.getPrice(); //this will throw NullPointerException
2) NullPointerException in Java while accessing field on null reference.
Trade fxtrade = null;
int price = fxtrade.price; //here fxtrade is null, you can’t access field here.
3) java.lang.NullPointerException when throwing null as exception.
If you throw an Exception object and if that is null you will get null pointer exception as shown in below example
RuntimeException nullException = null;
throw nullException;
4)example of NullPointerException when getting length of an array which is null.
Trade[] bluechips = null;
int length = bluechips.length;  //array is null here
5) Example of NPE when accessing element of a null array.
Trade[] bluechips = null;
Trade motorola = bluechips[0]; //array is null here
6) You will also get NullPointerException in Java if you try to synchronize on null object or try to use null object inside synchronized block in Java.
Trade highbetaTrade = null;
synchronized(highbetaTrade){
System.out.print("This statement is synchronized on null");
}
How to avoid the NullPointerException?
1. String comparison with literals
  //wrong way - may cause NullPointerException
if(unknownObject.equals("knownObject")){
   System.err.println("This may result in NullPointerException if unknownObject is null");
}
//right way - avoid NullPointerException even if unknownObject is null
if("knownObject".equals(unknownObject)){
    System.err.println("better coding avoided NullPointerException");
}
2. Check the arguments of a method
public static int getLength(String s) {
          if (s == null)
               throw new IllegalArgumentException("The argument cannot be null");
          return s.length();
     }
3. Prefer String.valueOf() method instead of toString()
Since calling toString() on null object throws NullPointerException, if we can get same value by calling valueOf() then prefer that, as passing null to  valueOf() returns "null", specially in case of wrapper classes  like Integer, Float, Double or BigDecimal.


BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //doesn’t throw NPE
System.out.println(bd.toString()); //throws "Exception in thread "main" java.lang.NullPointerException"
4. Use the Ternary Operator
String message = (str == null) ? "" : str.substring(0, 10);
5. Create methods that return empty collections instead of null
public class Example {
          private static List<Integer> numbers = null;
    
          public static List<Integer> getList() {
               if (numbers == null)
                    return Collections.emptyList();
               else
                    return numbers;
          }
     }
6. Make use of Apache’s StringUtils class
You can make use of the StringUtils.isNotEmpty, StringUtils.IsEmpty and StringUtils.equals methods, in order to avoid the NullPointerException.
 For example:
     if (StringUtils.isNotEmpty(str)) {
          System.out.println(str.toString());
     }
7. Use the contains(), containsKey(), containsValue() methods
Map<String, String> map = …
     …
     String key = …
     String value = map.get(key);
     System.out.println(value.toString()); // An exception will be thrown, if the value is null.
The safest way is the following:
     Map<String, String> map = …
     …
     String key = …
     if(map.containsKey(key)) {
          String value = map.get(key);
          System.out.println(value.toString()); // No exception will be thrown.
8. Use Assertions
A sample example using Java assertions is the following:
     public static int getLength(String s) {
          /* Ensure that the String is not null. */
          assert (s != null);
          return s.length();
     }
When in Java Code NullPointerException doesn't come
1) When you access any static method or static variable with null reference.
If you are dealing with static variables or static method than you won't get null pointer exception even if you have your reference variable pointing to null because static variables and method call are bonded during compile time based on class name and not associated with object. for example below code will run fine and not throw NullPointerException because "market" is an static variable inside Trade Class.

Trade lowBetaTrade = null;
String market = lowBetaTrade.market; //no NullPointerException market is static variable.
Important points on NullPointerException in Java
1) NullPointerException is an unchecked exception because itsextends RuntimeException and it doesn’t mandate try catch block to handle it.
2) When you get NullPointerException look at line number to find out which object is null, it may be object which is calling any method.
3) Modern IDE like Netbeans and Eclipse gives you hyper link of line where NullPointerException occurs