Showing posts with label Interview. Show all posts

What is the difference between HQL and Criteria in Hibernate?

HQL (Hibernate Query Language)

  • HQL can be used to perform SELECT, INSERT, UPDATE, DELETE.
  • SQL injection possible if not used parameterized query.
  • SELECT STATEMENT: You've to manually write the long queries, take care of where and other syntax.

Criteria

  • Criteria can be used to perform only SELECT.
  • SQL injection is not possible with Criteria because hibernate will take care of it while generating SQL query.
  • SELECT STATEMENT: Criteria interface comes with handy methods and take care of where and other syntax.

These are the basic difference between HQL (Hibernate Query Language) and Criteria. Do comment if other important difference is there.

Check out the stackoverflow thread for performance of Hibernate Criteria vs HQL: which is faster?

Autoboxing and unboxing conversions in Java

Autoboxing and unboxing in java

Autoboxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called Unboxing.

Autoboxing
Converting primitive values (int, long, float, double...) into an object of the corresponding wrapper class (Integer, Long, Float, Double...) is called autoboxing. The compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Autoboxing Example
The given code
/* Passed as a parameter to a method that expects an object of the corresponding wrapper class. */
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(i); 
}
=====
/* Assigned to a variable of the corresponding wrapper class. */
int x = 10;
Integer y = x;
will be converted by compiler as follow, Here i is autoboxed by Integer.valueOf(i).
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(Integer.valueOf(i));
}
=====
int x = 10;
Integer y = Interger.valueOf(x);

Unboxing
Converting an object of a wrapper type (Integer, Long, Float, Double...) to its corresponding primitive (int, long, float, double...) value is called unboxing. The compilere applied unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Unboxing Example
The given code
/* Assigned to a variable of the corresponding primitive type. */
int sum = 0;
for (Integer i : listIntegers){
 if (i % 2 == 0){
  sum += i;
 }    
}
=====
/* Passed as a parameter to a method that expects a value of the corresponding primitive type. */
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a, b);

public int sum(int x, int y){
  return x + y;
}
will be converted by compiler as follow because remainder (%) and unary plus (+=) don't apply on wrapper class Integer. Here i % 2 unboxed by i.intValue() % 2 and sum += i unboxed by sum += i.intValue().
int sum = 0;
for (Integer i : listIntegers){
 if (i.intValue() % 2 == 0){
  sum += i.intValue();
 }    
}
=====
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a.intValue(), b.intValue());

public int sum(int x, int y){
  return x + y;
}

What is SQL Injection and how to avoid it in Java?

SQL Injection
Its a technique where attacker try to alter(modify/change) your SQL query using input parameters.
SQL injection may leads to unexpected transaction (i.e select, update, delete, etc...). We'll see the basic SQL injection examples and later on see how to prevent it using Prepared Statement, Hibernate Criteria and HQL.

Source code (SQLInjection.java)
import java.util.ArrayList;
import java.util.List;

/**
 * Example of SQL injection.
 * @author javaQuery
 * @date 8th November, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SQLInjection {

    public static void main(String[] args) {
        /* You are getting parameter value from web page or other user input */
        String parameter = "12"; // normal condition
        new SQLInjection().getUser(parameter);

        /**
         * SQL injection using parameter value. 
         * - If user can change parameter in url, use some script, etc...
         */
        parameter = "12 or 1 = 1";
        new SQLInjection().getUser(parameter);
    }

    /**
     * Get user from database.
     * @param id
     * @return 
     */
    public List<Object> getUser(String id) {
        List<Object> result = new ArrayList<Object>();

        String sql = "SELECT * FROM users WHERE id = " + id + ";";
        System.out.println("SQL Query: " + sql);

        /* prepare connection and execute query */
        return result;
    }
}
Output
In following queries, 1st query is valid and return result as expected but when 2nd query is executed it'll select all users from database and that may leads to unexpected behavior of your system.
SQL Query: SELECT * FROM users WHERE id = 12;
SQL Query: SELECT * FROM users WHERE id = 12 or 1 = 1;
In this example I used user table and this table contains very few records 1k, 10k, etc... but
What if you are selecting data from table which contains millions of records? - Answer is SYSTEM CRASH

Other ways of SQL injection
Consider you are getting value of username and password from parameter into param_username and param_password.
String param_username = "\" or \"\"=\"";
String param_password = "\" or \"\"=\"";

//SQL Injection:
String sql = "SELECT * FROM users WHERE username = \"" + param_username + "\" AND password = \"" + param_password +"\"";
System.out.println(sql);
//OUTPUT: SELECT * FROM users WHERE username = "" or ""="" AND password = "" or ""=""

============================================
String param_userid = "123; DROP TABLE messages;";

//SQL Injection:
String sql = "SELECT * FROM users WHERE id = " + param_userid;
System.out.println(sql);
//OUTPUT: SELECT * FROM users WHERE id = 123; DROP TABLE messages;

First and foremost way: Handle Datatypes
For the sake of simplicity developers don't handle data types at coding. In above code I used String as input parameter in method getUser but should've use Integer/Long. If I used Integer or Long then I've to convert String => 12 or 1 = 1 to Integer/Long => Not Valid Number. It'll prevent SQL Injection.


Avoid SQL Injection using Prepared Statement
Prepared Statement doesn't append values in your SQL query rather it provide SQL query and parameter values separately to database. Database will take care of every parameter value for escape character, special character and every other precaution needed.

Source code (PreparedStatementExample.java)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Example of SQL injection.
 * @author javaQuery
 * @date 8th November, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class PreparedStatementExample {
    public static void main(String[] args) {
        new PreparedStatementExample().getUser("12");
    }
    
    /**
     * Get user from database.
     * @param id
     * @return 
     */
    public List<Object> getUser(String id) {
        List<Object> result = new ArrayList<Object>();

        String sql = "SELECT * FROM users where id = ?;";

        /* prepare connection and execute query */
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
            PreparedStatement prepareStatement = connection.prepareStatement(sql);
            prepareStatement.setInt(1,Integer.parseInt(id)); // index of ? is '1', perform null/number check for 'id'
            //execute prepared statement
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        
        return result;
    } 
}
Output
With PreparedStatement only following query can be generated.
SELECT * FROM users where id = 12;
prepareStatement.setInt: 12 or 1 = 1 is passed as value then Integer.parseInt will throw java.lang.NumberFormatException: For input string: "12 or 1=1".
prepareStatement.setString: What happen if String is used for Number data type in MySQL?


Avoid SQL Injection using Hibernate Criteria
Hibernate Criteria internally uses Prepared Statement to execute query.

Source code
String param_id = "12";

Criteria criteria = session.createCriteria(User.class);
/**
 * 'param_id' provided as String but 'id' declared as Integer/Long in User.java
 * So it'll throw exception(java.lang.String cannot be cast to java.lang.Integer) for invalid data type. (SQL injection handled)
 */
criteria.add(Restrictions.eq("id", param_id));
User user = criteria.uniqueResult();

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

// valid query
Integer param_id = 12;

Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("id", param_id));
User user = criteria.uniqueResult();

Avoid SQL Injection using HQL
Its same as Hibernate Criteria.

Source code
String param_id = "12";

Query query = session.createQuery("FROM User WHERE id = :param_id");
/**
 * 'param_id' provided as String but 'id' declared as Integer/Long in User.java
 * So it'll throw exception(java.lang.String cannot be cast to java.lang.Integer) for invalid data type. (SQL injection handled)
 */
query.setParameter("param_id", param_id);
query.list();

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

// valid query
Integer param_id = 12;

Query query = session.createQuery("FROM User WHERE id = :param_id");
query.setParameter("param_id", param_id);
query.list();

What is the difference between List, Set and Map in Java?

List , Set , Map in Java8

List interface
An ordered collection (also known as a sequence).

Characteristics
  • Element added from 0th index, 1st, 2nd, ... nth (Sequentially).
  • List allows to insert/update/read element at specific index.
  • List allows duplicate values.
  • It maintains insertion position (1st point).
  • It allows null value.

ArrayList is one of the popular implementation of List used by programmers.

Examples


Set interface
Collection which don't allows duplicate values.

Characteristics
  • Unlike List, Set will not allow index based insert/update/read.
  • Set doesn't allow duplicate. e1 and e2 such that e1.equals(e2)
  • It doesn't maintain insertion position (unordered collection). However you can maintain order using LinkedHashSet.
  • It allows null value.

HashSet is one of the popular implementation of Set used by programmers.

Examples


Map interface
Collection to hold [KEY, VALUE] data.

Characteristics
  • Unlike List, Map will not allow index based insert/update/read.
  • Map doesn't allow duplicate KEY.
  • It doesn't maintain insertion position (unordered collection). However you can maintain order using LinkedHashMap.
  • It allows one null KEY and n number of null VALUE.

HashMap us one of the popular implementation of Map used by programmers.



Collection Framework examples in Java 8

How to convert List of data to Set of data and vice versa in Java?

Following excerpt shows how you can convert List<T> to Set<T> and Set<T> to List<T> in java.

Source code (ListToSet.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * List to Set example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ListToSet {

    public static void main(String[] args) {
        /* Create list of string */
        List<String> strings = new ArrayList<String>();
        strings.add("A");
        strings.add("B");

        Set<String> stringSet = new HashSet<String>(strings);
        /**
         * new HashSet(Collection<? extends E> c) 
         * We created Set of String so we can initialize HashSet using any collection that extends String.
         */
        
        for (String string : stringSet) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize List in declaration?.

Source code (SetToList.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Set to List example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SetToList {

    public static void main(String[] args) {
        /* Create set of string */
        Set<String> strings = new HashSet<String>();
        strings.add("A");
        strings.add("B");

        List<String> list = new ArrayList<>(strings);
        /**
         * new ArrayList(Collection<? extends E> c) 
         * We created List of String so we can initialize ArrayList using any collection that extends String.
         */
        
        for (String string : list) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize Set in declaration?.

Output
A
B

What is difference between method Overloading and Overriding in Java?

Its one of the popular Interview question asked to Java developer with 0 - 1 year experience. We'll understand method overloading followed by method overriding.

Method Overloading
Same method name but different parameters in class.

Source code (MethodOverload.java)
/**
 * Example of method overloading
 *
 * @author javaQuery
 * @date 5th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MethodOverload {

    public int x = 0;

    /**
     * Method overloading - Same method name(getAndIncrement) with no parameter.
     * Increment x by 1.
     *
     * @return
     */
    public int getAndIncrement() {
        x = x + 1; // you can also use like x = getAndIncrement(1);
        return x;
    }

    /**
     * Method overloading - Same method name(getAndIncrement) with parameter.
     * Increment x by given count(value).
     *
     * @param add
     * @return
     */
    public int getAndIncrement(int add) {
        x = x + add;
        return x;
    }

    public static void main(String[] args) {
        MethodOverload methodOverload = new MethodOverload();
        System.out.println("calling 'getAndIncrement()': " + methodOverload.getAndIncrement());
        System.out.println("calling 'getAndIncrement(int add)': " + methodOverload.getAndIncrement(2));
    }
}
Output
calling 'getAndIncrement()': 1
calling 'getAndIncrement(int add)': 3

Method Overriding
In case of class(sub-class: AddAndDisplay) extends/implements other class/interface (super-class: Addition).
Method with same name and parameter created in sub-class.
Note: Overriding is used when you don't want to use default implementation provided by parent class and will write your own piece of implementation in overridden method.

Source code (Addition.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class Addition {

    /**
     * Add two numbers and return the result.
     * @param x
     * @param y
     * @return 
     */
    public int add(int x, int y) {
        return x + y;
    }
}

Source code (AddAndDisplay.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class AddAndDisplay extends Addition {

    /**
     * Method override of class Addition.
     * We're overriding 'add' method because we want to print
     * values of 'x' and 'y' to console along with the 'result'.
     * @param x
     * @param y
     * @return
     */
    @Override
    public int add(int x, int y) {
        int result = x + y;
        System.out.println("(x:" + x + ",y:" + y + ")");
        System.out.println("result: " + result);
        return result;
    }
}

Source code (MethodOverride.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MethodOverride {
    public static void main(String[] args) {
        /* Add two number using super class Addition's add method */
        Addition addition1 = new Addition();
        int result = addition1.add(20, 30);
        System.out.println("calling Addition.add(int x, int y)");
        System.out.println("result: " + result);
        System.out.println("********************************************");
        
        System.out.println("calling AddAndDisplay.add(int x, int y)");
        Addition addition2 = new AddAndDisplay();
        /**
         * Notice: We created object of 'Addition' using 'AddAndDisplay'.
         * 
         * So when we call Addition.add(int x, int y) method it'll execute
         * AddAndDisplay.add(int x, int y) method because 'add' is 
         * overridden. 
         * 
         * It'll hide the superclass Addition's add method and execute
         * subclass AddAndDisplay's method.
         */
        addition2.add(10, 20);
    }
}
Output
calling Addition.add(int x, int y)
result: 50
********************************************
calling AddAndDisplay.add(int x, int y)
(x:10,y:20)
result: 30

Understanding Thread.join in Java


Thread.join()
Waits for this thread to die.

Thread.join(long millis)
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Thread.join() and Thread.join(long millis) explained with real world example in Image.

Source code (MessageThread.java)
/**
 * Thread that prints message in interval of 4 seconds.
 *
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MessageThread implements Runnable {

    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    @Override
    public void run() {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };
        try {
            for (int i = 0; i < importantInfo.length; i++) {
                // Pause for 4 seconds
                Thread.sleep(4000);
                // Print a message
                threadMessage(importantInfo[i]);
            }
        } catch (InterruptedException e) {
            threadMessage("I wasn't done!");
        }
    }
}

Source code (ThreadJoinExample.java)
/**
 * Thread join example.
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ThreadJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MessageThread());
        // start MessageThread.
        t.start();
        /**
         * Main Thread (ThreadJoinExample) will wait for 't' to finish 
         * its task in 5 seconds of it will leave.
         */
        t.join(5000);
        
        /**
         * Main Thread (ThreadJoinExample) will wait until 't' finish its task.
         */
        // t.join(); 
        System.out.println("Main Thread left(finish).");
    }
}

Output
Thread-0: Mares eat oats
Main Thread left(finish).
Thread-0: Does eat oats
Thread-0: Little lambs eat ivy
Thread-0: A kid will eat ivy too

How Fail Fast Iterator identifies that the collection is modified?



Image gives you the abstract idea about How iterator identifies the modification on collection. Its one of the interview question asked as sub part of Fail Fast vs Fail Safe Iterator in Java. To understand it better I pulled out the source code of HashMap.

Source code (HashMap.java)
public class HashMap<K, V>...{
    transient int modCount;

    public V put(K key, V value) {
        return this.putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        ...
        ++this.modCount;
        ...
    }
 
    public Set<Map.Entry<K,V>> entrySet() {
        // this method internally uses HashIterator
    }

    abstract class HashIterator{
        int expectedModCount;  // for fast-fail
        ...
        HashIterator() {
            expectedModCount = modCount;
            ...
        }
 
        final Node nextNode() {
            ...
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            ...
            ...
        }
    }
}
So when you call method entrySet() of HashMap, It creates the object of inner class HashIterator with current value of modCount and set it in expectedModCount.

Now when nextNode() method is called it compares value of expectedModCount with parent class's (HashMap) modCount and if its not same then it throws ConcurrentModificationException.

Source code (FailFastExample.java)
/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

Fail Fast vs Fail Safe Iterator in Java

Fail Fast vs Fail Safe


One of the popular interview question asked to java developer. To know how well you understand the iterator.

Fail Fast
When you perform add, update or remove on collection while iterating on it. It throws java.util.ConcurrentModificationException.

Source code (FailFastExample.java)
import java.util.HashMap;
import java.util.Map;

/**
 * Example of Fail Fast using Map.
 * @author javaQuery
 * @date 4th August, 2016
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, Double> carPrice = new HashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for(Map.Entry<String, Double> car : carPrice.entrySet()){
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());
            
            /* Will cause java.util.ConcurrentModificationException */
            carPrice.put("Lamborghini", 300000D);
        }
    }
}

Output
Car: Ferrari
Price: 200000.0
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
 at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
 at com.javaquery.collections.map.FailFastExample.main(FailFastExample.java:23)

You can also consider Collection (List, Set, Map) shared between two or more Threads. One is iterating on collection and other tries to add element in it then the thread iterating over it, will throw java.util.ConcurrentModificationException

In interview if you are able to answer this question. They might me interested in checking your knowledge little bit deep. You may face the question How Fail Fast Iterator identifies that the collection is modified?

Fail Safe
It iterate over the clone(copy) of original collection. So It won't throw java.util.ConcurrentModificationException.

Source code (FailSafeExample.java)
/**
 * Example of Fail Safe using ConcurrentHashMap.
 * @author javaQuery
 * @date 4th August, 2016 
 * @Github: https://github.com/javaquery/Examples 
 */
public class FailSafeExample {

    public static void main(String[] args) {
        Map<String, Double> carPrice = new ConcurrentHashMap<String, Double>();
        carPrice.put("Porsche", 100000D);
        carPrice.put("Ferrari", 200000D);

        /* Iterate over Map */
        for (Map.Entry<String, Double> car : carPrice.entrySet()) {
            System.out.println("Car: " + car.getKey());
            System.out.println("Price: " + car.getValue());

            /* Will be added in original copy of Map but won't available in Iterator */
            carPrice.put("Lamborghini", 300000D);
        }
        System.out.println("=== loop finished ===");
        System.out.println("Car: Lamborghini" + ", Price: " + carPrice.get("Lamborghini"));
    }
}

Output
Car: Ferrari
Price: 200000.0
Car: Porsche
Price: 100000.0
=== loop finished ===
Car: Lamborghini, Price: 300000.0

Difference between Thread start() and Runnable run()

Lets first understand run() method of Runnable. Consider following code snippet.

Source code (Car.java)
public class Car implements Runnable{

    @Override
    public void run() {
        System.out.println("Run car...");
    }
}
Source code (Cycle.java)
public class Cycle{

    public void run() {
        System.out.println("Run cycle...");
    }
}
public class Test {
    public static void main(String[] args) {
        /* Calling method of class Cycle */
        new Cycle().run();
        /* Calling method of class Car, doesn't matter class implements Runnable */
        new Car().run();
    }
}
There is no difference between new Cycle().run() and new Car().run() even if Car implements Runnable . You are just calling method of class Car.

Runnable in Thread
public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Car());
        /* It'll start new Thread and call run method of Car() in Thread environment */
        thread.start();
    }
}
run method of Car will be executed in separate Thread environment. thread.start() will start new Thread.

Conclusion
- run method of Runnable will be executed as normal method of class.
- start method of Thread starts the new Thread.

Difference between Thread and Runnable in Java

extends Thread vs implements Runnable

Inheritance
Java supports only single Inheritance means you can't extend more than one class. When you extends Thread you lose the opportunity to extend another class.

Implementing Runnable interface gives you window to extend another class.

Extending class
Extending class means you are changing behavior of super class with your implementation. Since you are not changing the behavior of Thread, implement Runnable.

Runnable as Task
Implementing Runnable represents standalone Task and can be executed by simple Thread or Executors.

Runnable means we can reuse the Task, but you can't restart the Thread once it completes.

Executor Interface
Since you can't restart the Thread once it completes, Java designer decided to accept Runnable class in Executor Interface and it gives more control over your Task compare to Thread.

What is the difference between a process and a thread?

Process vs Thread in Java

Image clarifies the difference between Process and Thread. However lets discuss it point by point.

Process
A process has a self-contained execution environment. An instance of program called Process.

  • Each Process has its own address space.
  • Process have to use Inter Process Communication (IPC) resource like pipes and sockets to communicate with other process.
  • New processes require duplication of the parent process.
  • Processes have considerable overhead.
  • Process have their own copy of data segment of the parent process.
  • Process have control over its child processes.
  • Any change in the parent process does not affect child processes.
  • Process is controlled by the operating system.
  • Processes are independent.

Thread
Threads are sometimes called lightweight processes. It runs within the Process.

  • Thread(s) shares the address space of Process that created it.
  • Threads can directly communicate with other Threads of its process.
  • New threads can be created easily.
  • Threads have almost no overhead.
  • Threads have direct access to data segment of its Process.
  • Threads have considerable control over threads of the same process.
  • Any change in main thread (cancellation, priority change, etc...) may affect the behavior of the other threads of the process.
  • Threads are controlled by programmer in a program.
  • Threads are dependent.

Bill Pugh: Initialization-on-demand singleton in Java

Singleton
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Initialization-on-demand singleton by Bill Pugh
Its one of the concrete way of creating singleton class in Java. We will understand it with example.

Source code
/**
 * Example: Singleton by Bill Pugh.
 *
 * @author javaQuery
 * @date 24th July, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SingletonBillPugh {

    /* private constructor */
    private SingletonBillPugh() {
    }

    /* static inner class */
    private static class LazyHolder{
        private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
    }
    
    /* get instance of SingletonBillPugh */
    public static SingletonBillPugh getInstance(){
        return LazyHolder.INSTANCE;
    }
}
Explanation
Now lets understand why its Initialization-on-demand (Initialize only when we call getInstance() method).

Java Language Specification
12.4.1 When Initialization Occurs (https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.1)
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

12.4.1.1: T is a class and an instance of T is created.
12.4.1.2: A static method declared by T is invoked.
12.4.1.3: A static field declared by T is assigned.
...
When class SingletonBillPugh is loaded by JVM, the class follows initialization process specified in Java Language Specification(12.4.1). Since the class does not have any static variables to initialize(12.4.1.3) the initialization completed.

What happen to class LazyHolder?
According to Java Language Specification (8.1.3) for inner class whose declaration does not occur in a static context of SingletonBillPugh. Inner class LazyHolder is not initialized until it it executed.

Java Language Specification
8.1.3. Inner Classes and Enclosing Instances (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.3)

When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing type declaration, the variable of the corresponding lexically enclosing instance is used.

What happen to method getInstance?
According to 12.4.1.2 A static method declared by T is invoked(called).


12.4.2. Detailed Initialization Procedure (https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2)
In first paragraph "Java Virtual Machine is responsible for taking care of synchronization and recursive initialization"
So when class SingletonBillPugh is initializing through LazyHolder, no other thread can initialize class until previous initialization of class SingletonBillPugh finish. And we marked variable INSTANCE final so other initialization won't happen. SingletonBillPugh class is completely singleton when using Bill Pugh singleton pattern.


What is the difference between String.valueOf() and toString() in Java?

Java String

Each piece of code represents the expertise of developer. You can judge the developer by his/her code. One faulty piece of code may lead to critical damage. So write your code by understanding the fundamental not because someone created and we've to use it.

String.valueOf(argument)
String.valueOf() is null safe. You can avoid java.lang.NullPointerException by using it. It returns "null" String when Object is null. Let explore the source code of String.valueOf().
/* Original Source code */
public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

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


Example
public class StringExample {

   public static void main(String[] args) {
      Object obj = "Hello World!";
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
  
      obj = null;
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
   }
}

Output
String.valueOf(): Hello World!
toString(): Hello World!
String.valueOf(): null
Exception in thread "main" java.lang.NullPointerException
 at javaQuery.core.StringExample.main(StringExample.java:14)


Top 10 Interview questions on Exception handling in Java



Can we write try without catch?
Yes we can write try without catch but we must write finally.
try{
   try code...
}finally{
   ...
}

Can we write just try without catch and finally?
try{
   try code...
}
No, We can't write just try. (Already stated this in answer 1)


What is finally block?
finally block used to close resources used in try.
=> finally block will be executed even if exception occurs try block.
=> finally block will be execute even you write return variable from try block.
=> finally block will not be executed when System.exit(exitcode) executed in try block.
try {
   /* finally will be executed */
   /* int a = 1 /0; */  
   /* return; */ 
 
   /* finally will not be executed */
   System.exit(0);
} catch (Exception e) {
   e.printStackTrace();
}finally{
   System.out.println("Finally executed.");
}

Can we write try within try?
try {
   try code...
   try {
      try code... 
   } catch (Exception e) {
      e.printStackTrace();
   }  
} catch (Exception e) {
   e.printStackTrace();
}
Yes we can write nested try-catch.


What is the difference between throw and throws?
-> throw is used for throwing an exception from program.
throw new NullPointerException();
-> throws is used in method definition. When method is causing an exception and it is not handled by method itself then exception is passed to caller method.
public void readFile(String filepath) throws IOException{
   ...
}

Which is super class of all exception?
Throwable is super class of all exception including Class `Exception`.
public class IOException extends Exception

public class Exception extends Throwable

What is difference between checked and unchecked exception?
This is explained with example. Read more on http://www.javaquery.com/2015/05/difference-between-checked-vs-unchecked.html


Does the sequence of catch matter? or Following code will compile?
try {
   try code...
} catch (Exception e) {
   e.printStackTrace();
} catch (NullPointerException ne){
   ne.printStackTrace();
}
Yes, Sub class must be caught first. NullPointerException is sub class of Exception. Above program will give compile time error Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception.


What is try-with-resources?(Java 7 or above)
This is explained with example. Read more on http://www.javaquery.com/2015/04/what-is-try-with-resources-in-java-7-or.html


Can we catch multiple exception in one catch?(Java 7 or above)
Yes we can.
catch (IOException|SQLException ex) {
   throw ex;
}


Top 10 String interview question in Java

Top 10 String interview question in Java

What is String pool in Java?
Its the special area in Java heap to store the String literals like "javaQuery". When you create new String JVM first checks String in Pool, Its its available in Pool then it'll return the same object from Pool. If you create String using
new String("javaQuery") then it'll create the same object in Java heap not in String pool.


Why String is immutable or final in Java?
String objects are cached in String Pool and shared between multiple thread so it will lead to risk of value changed by one thread will affect value of other thread. This is one of the popular question in asked in Java interviews. This is explained with example and diagram Read more >>


What is the difference between str.equals("Vicky") and "Vicky".equals(str) in Java?
- name.equals("Vicky") Compare unknown value(name) with known value("Vicky").
- "Vicky".equals(name) Compare known value("Vicky") with unknown value(name) and its null safe. This is used to avoid java.lang.NullPointerException. Read more >>


What will be the output of following program? or Comparing two Strings in Java.
String str = "abc";
String str1 = "abc";
String str2 = new String("abc");

/**
 * '==' will compare the reference of two String.
 * str == str1 both points to same String in String Pool.
 */
System.out.println(str == str1); // true

/**
 * When we create String object using new String("abc"); then object will be created in Heap.
 * str belongs to String Pool and str2 belongs to Heap and they are not equal.
 */
System.out.println(str == str2); // false

/**
 * .equals() used with String compare the value of both String and they are equal.
 */
System.out.println(str.equals(str2)); //true

String vs StringBuilder vs StringBuffer
- String: When we have String that keeps changing then we have to use StringBuilder or StringBuffer and String is immutable.
- StringBuilder: Its fast compare to String and StringBuffer. However its not thread safe. StringBuilder is mutable.
- StringBuffer: Its slow compare to StringBuilder as its thread safe. StringBuffer is mutable.


How to reverse the String in Java? or How to check String is Palindrome or not in Java?
We can use StringBuilder.reverse() or StringBuffer.reverse() to reverse the String. Read more >>


How to convert String to char[] array and char[] array to String in Java?
- String to char[]: String.toCharArray()
- char[] to String:  String.valueOf(char[] data)
Read more >>


Why String is not good choice to store the password?
String is immutable, It means once you create the String it'll be available in memory for a long time. If one has access to memory dump then he/she can read the password from memory. char[] array is good choice for storing the password because you can wipe out the character array from memory.


How to move String object from Heap to String Pool?
String.intern() is used to move String object from Heap to String Pool.


Does String is thread-safe in Java?
Yes it it. String is immutable and we can't change value of String so it can be used in multi-threaded environment.


How to convert String to char[] array and char[] array to String in Java?

String to char array in Java

One of the rare question asked in Java interview however its worth knowing the basics of String.

Source Code
public class StringCharArray {
    public static void main(String[] args) {
        String str = "javaQuery";
        
        /* Conver String to char[] array */
        char[] charArray = str.toCharArray();
        
        /* Print the char[] array */
        System.out.println("String to char[]:");
        for(char ch : charArray){
            System.out.println(ch);
        }
        
        /* Convert char[] array to String */
        String strFromCharArray = String.valueOf(charArray);
        
        System.out.println("------------------------");
        
        /* Print the String */
        System.out.println("char[] to String: "+strFromCharArray);
    }
}

Output
String to char[]:
j
a
v
a
Q
u
e
r
y
------------------------
char[] to String: javaQuery

How to sort Array in Ascending, Descending and Mixed mode in Java?

java.util.Arrays
java.util.Arrays class provides many options for sorting an Array. We will sort Array in Ascending, Descending and Mixed mode(1st/first to kth in Ascending order and k+1th to nth/last in Descending order, you can choose different position for 1st,kth and nth).

In addition this question was asked in leading Multi National Company(MNC). Its worth understanding code for future interview of yours.

Source Code
public class SortArray {

    public static void main(String[] args) {
        Integer[] intSortArrayAscending = {25, 9, 23, 1, 4, 90, 99};
        Integer[] intSortArrayDescending = {25, 9, 23, 1, 4, 90, 99};
        Integer[] intSortArrayMixedMode = {25, 9, 23, 1, 4, 90, 99};

        /* Sort Array in Ascending order */
        Arrays.sort(intSortArrayAscending);
        
        /* Print array */
        System.out.print("Ascending order: ");
        for (int i : intSortArrayAscending) {
            System.out.print(i + ",");
        }

        System.out.println("\n------------------------");

        /* Sort Array in Descending order */
        SortArray objSortArray = new SortArray();
        /* Use Comparator to sort Array in Descending order */
        Arrays.sort(intSortArrayDescending, objSortArray.comparatorDescending());

        /* Print array */
        System.out.print("Descending order: ");
        for (int i : intSortArrayDescending) {
            System.out.print(i + ",");
        }
        System.out.println("\n------------------------");

        System.out.println("Mixed mode sorting:");
        /**
         * Mixed mode Sorting
         * Sort 1st/first position to kth in Ascending order
         * and
         * Sort k+1th position to nth/last in Descending order
         */
        
        /* I used middle point as pivotPoint */
        int pivotPosition = intSortArrayMixedMode.length / 2;
        System.out.println("Ascending order from element 1 to " + pivotPosition);
        System.out.println("Descending order from element " + (pivotPosition + 1) + " to " + intSortArrayMixedMode.length);

        /* Arrays.sort(int[] a, int fromIndex, int toIndex) */
        Arrays.sort(intSortArrayMixedMode, 0, pivotPosition);

        /*  sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) */
        Arrays.sort(intSortArrayMixedMode, pivotPosition, intSortArrayMixedMode.length, objSortArray.comparatorDescending());

        /* Print array */
        for (int i : intSortArrayMixedMode) {
            System.out.print(i + ",");
        }
    }

    /**
     * Comparator for Descending order
     */
    public Comparator<Integer> comparatorDescending() {
        return new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 < o2) {
                    return 1;
                } else {
                    return -1;
                }
            }
        };
    }
}

Output
Ascending order: 1,4,9,23,25,90,99,
------------------------
Descending order: 99,90,25,23,9,4,1,
------------------------
Mixed mode sorting:
Ascending order from element 1 to 3
Descending order from element 4 to 7
9,23,25,99,90,4,1,


What is the difference between replace and replaceAll in Java?


People out there have misconception about replace and replaceAll. I was having random discussion with my colleague he said replace is used to replace first occurrence of Character/String in String and replaceAll used to replace all occurrence of Character/String in String.

For those who has misconception about replace and replaceAll
replace: It will replace all occurrence of Character/String matched in String. replace can't process Regular Expression.
replaceAll: It will replace all occurrence of Character/String matched in String. replaceAll can process Regular Expression.

Source Code
public class ReplaceExample {
    public static void main(String[] args) {
        String str = "@aa @bx @ca @ax";
        System.out.println("Original String: "+str);
        System.out.println("------------------------");
        
        /* replace '@a' with 's' */
        System.out.println("replace: "+str.replace("@a", "s"));
        
        /* replace can't process REGULAR EXPRESSION */
        System.out.println("replace(with regexp): "+str.replace("@[a-z]*", "s"));
        
        /**
         * replaceAll can process REGULAR EXPRESSION
         * Replace any String followed by '@'
         */
        System.out.println("replaceAll: "+str.replaceAll("@[a-z]*", "s"));
    }
}

Output
Original String: @aa @bx @ca @ax
------------------------
replace: sa @bx @ca sx
replace(with regexp): @aa @bx @ca @ax
replaceAll: s s s s

How to check String is Palindrome or not in Java?

Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Like 121 <-reverse-> 121, aba <-reverse-> aba, etc...

Source Code
public class PalindromeString {

    public static void main(String[] args) {
        String str = "aba";
        PalindromeString objPalindromeString = new PalindromeString();
        System.out.println("Is \"" + str + "\" Palindrome?");
        System.out.println(objPalindromeString.isPalindromeString(str));
    }

    /**
     * @author javaQuery
     * @param str
     * @return {@link boolean}
     * 
     * Method is used to check String is Palindrome or not.
     */
    public boolean isPalindromeString(String str) {
        /* If its null then return false */
        if (str == null) {
            return false;
        }
        /* Use StringBuilder/StringBuffer to reverse the String */
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        /* Compare original and reversed String */
        return str.equalsIgnoreCase(strBuilder.toString());
    }
}

Output
Is "aba" Palindrome?
true