Showing posts with label Core Java Interview questions. Show all posts
Showing posts with label Core Java Interview questions. Show all posts

Friday, 23 November 2018


  1. When Parent throws Generic Exception and Child throws specific exception
    1. Compiles and run successfully
    2. public class Animal { public void eat() throws Exception { System.out.println("Animal Eating..."); } } public class Cat extends Animal { @Override public void eat() throws FileNotFoundException { System.out.println("Cat Eating ....."); } } public class App { public static void main(String[] args) throws Exception { Animal cat = new Cat(); cat.eat(); } } ######### RESULT ########## Cat Eating .....
  2. When Parent throws specific exception and child throws generic exception
    1. Compile time error
  3. When Parent modifier is protected and child modifier is public
    1. Compiles and run successfully
  4. When Parent modifier is private and child modifier is public
    1. Compile time error
  5. When Parent modifier is public and child modifier is private
    1. Compile time error

Friday, 12 October 2018


  1. How Volatile in Java works?
    1. The Java volatile keyword cannot be used with method or class and it can only be used with a variable.
    2. Java volatile keyword also guarantees visibility and ordering and write to any volatile variable happens before any read into the volatile variable.
    3. Example: Singleton Class 
      1. public class Singleton{ private static volatile Singleton _instance; //volatile variable public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); } } return _instance; }
      2. writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java, this is handled by Java himself and such updates will be visible by all reader threads.
    4. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.
    5. Both T1 and T2 can refer to a class containing this variable. You can then make this variable volatile, and this means that changes to that variable are immeditately visible in both threads.
    6. public class App { public static volatile boolean isEven = true; public static void main(String[] args) { Object mutex = new Object(); Thread odd = new Thread(new Runnable() { @Override public void run() { try { int i = 0; while (i < 20) { synchronized (mutex) { if (isEven) { mutex.wait(); } System.out.println("Odd"); isEven = true; mutex.notify(); } i++; } } catch (Exception e) { e.printStackTrace(); } } }); Thread even = new Thread(new Runnable() { @Override public void run() { try { int i = 0; while (i < 20) { synchronized (mutex) { if (!isEven) { mutex.wait(); } System.out.println("Even"); isEven = false; mutex.notify(); } i++; } } catch (Exception e) { e.printStackTrace(); } } }); odd.start(); even.start(); } }
    7. Volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.
    8. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
    9. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
    10. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
  2. How is CountDownLatch used in Java Multithreading?
    1. CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.
    2. Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. 
    3. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.
    4. As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.
  3. can we make array volatile in java?
    1. Yes, you can make an array (both primitive and reference type array e.g. an int array and String array) volatile in Java
    2. But declaring an array volatile does NOT give volatile access to it's fields. you're declaring the reference itself volatile, not it's elements.
      1. protected volatile int[] primes = new int[10];
        1. then if you assign a new array to primes variable, change will be visible to all threads, but changes to individual indices will not be covered under volatile guarantee i.e
      2. primes = new int[20];
        1. will follow the "happens-before" rule and cause memory barrier refresh visible to all threads
      3. primes[0] = 10;
        1.  will not visible changes in all threads
    3. Same for collections also
    4. In other words you're declaring a volatile set of elements, not a set of volatile elements. The solution here is to use AtomicIntegerArray in case you want to use integers
  4.  Thread Local?
    1. The ThreadLocal class in Java enables you to create variables that can only be read and writte by the same thread
    2. private ThreadLocal myThreadLocal = new ThreadLocal();
    3. Now you can only store strings in the ThreadLocal instance.
    4. myThreadLocal.set("Hello ThreadLocal"); String threadLocalValue = myThreadLocal.get();
  5. How immutable objects manage memory ?
    1. The advantage we get with String is that a common pool of string literals is kept by the virtual machine stopping the Heap getting filled up . The reasoning behind this is that much of the memory of a program can be taken up with storing commonly used strings.
  6. How to throw exceptions from Runnable.run?
    1. Do not use Runnable interface from Thread library, but instead create your own interface with the modified signature that allows checked exception to be thrown
    2. public interface MyRunnable { void myRun ( ) throws MyException; }
    3. You may even create an adapter that converts this interface to real Runnable ( by handling checked exception ) suitable for use in Thread framework.
  7. Difference Between Daemon and User Threads?
    1. Java offers two types of threads: user threads and daemon threads.
    2. JVM will wait for all active user threads to finish their execution before it shutdown itself.
    3. Daemon thread doesn't get that preference, JVM will exit and close the Java program even if there is a daemon thread running in the background
    4.  Daemon threads are low-priority threads whose only role is to provide services to user threads..
    5. A daemon thread is a thread that does not prevent the JVM from exiting when the user thread finishes but the thread is still running. An example for a daemon thread is the garbage collection.
    6. That’s why infinite loops, which typically exist in daemon threads, will not cause problems, because any code, including the finally blocks, won’t be executed once all user threads have finished their execution. For this reason, daemon threads are not recommended for I/O tasks.
    7. // Java program to demonstrate the usage of // setDaemon() and isDaemon() method. public class DaemonThread extends Thread { public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread"); } else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = new DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.start(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); } } ######OUT PUT#### t1 is Daemon thread t2 is User thread

Tuesday, 9 October 2018


  • Prototype pattern refers to creating duplicate object 
  • This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.
  • // Prototype pattern public abstract class Prototype implements Cloneable { public Prototype clone() throws CloneNotSupportedException{ return (Prototype) super.clone(); } } public class ConcretePrototype1 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype1)super.clone(); } } public class ConcretePrototype2 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype2)super.clone(); } }

Tuesday, 2 October 2018


  • Java collections framework belongs to java.util package       
  •          Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays.
  •      There are two "groups" of interfaces: Collection's and  Map's


  1.    Collection
    1. List
      1. The java.util.List interface is a subtype of the java.util.Collection interface
      2. It represents a n ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too.
      3. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list.
      4. You can also add the same element more than once to a List.
      5. The List Implementations are,
        1. Arraylist
        2. Vector
        3. Linkedlist
    2. Set
      1. It represents set of objects, meaning each element can only exists once in a Set.
      2. Internal datas structure of set is hashmap and unique key feature of hashmap made set accept only unique objects 
      3. The List Implementations are,
        1. HashSet
        2. LinkedHashSet
        3. TreeSet
    3. Queue
      1. A queue is also ordered, but you'll only ever touch elements at one end. All elements get inserted at the "end" and removed from the "beginning" (or head) of the queue. You can find out how many elements are in the queue, but you can't find out what, say, the "third" element is. You'll see it when you get there.
      2. The Queue Implementations are,
        1. Linkedlist
        2. PriorityQueue 
    4. Dequeue
      1. Deque is short for "double ended queue". With an ordinary queue, you add things to one end and take them from the other. With a double ended queue, you can add things to either end, and take them from either end.
      2. The Dequeue Implementations are
        1. Linkedlist
        2. ArrayDeque
    5. Stack
      1.  Stack is liner type data structure, i.e. they are arranging in liner manner. In stack whatever is stored first it comes out last. It works in LIFO manner(Last in first out)
      2. In stack you can’t add element in between. They are like a stack of coins, i.e. if you want to take the last coin, then all the upper coins have to be removed one by one.
  2.    Map
    1. Map Interface Store data as key value pair
      1. Hashmap
      2. Hashtable
      3. Treemap
      4. Linked Hashmap
  • Arraylist
    • ArrayList is implemented as a resizable array. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array.
    • When an element is inserted into an ArrayList, the object will need to expand its internal array if it runs out of room. the ArrayList increases its array size by 50 percent.
  • Vector
    • The chief difference from ArrayList is that its methods are synchronized (ArrayList's are not). That means it is easier to use in multi-threaded environments, but it does incur the synchronization overhead.
    • When an element is inserted into  a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array
  • Linkedlist
    •  A linked list is a data structure consisting of a group of nodes which together represent a sequence. Each     node is composed of a data and a reference to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence. 
    • In a singly linked list each node has only one link which points to the next node in the list.
  • HashSet
    • It makes no guarantees about the sequence of the elements when you iterate them
  • LinkedHashSet
    • LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet.
  • TreeSet
    • Guarantees the order of the elements when iterated, but the order is the sorting order of the elements.
  • PriorityQueue 
    • Stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.
  • ArrayDeque
    • ArrayDeque stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the ArrayDeque grows as needed, even if it stores its elements in an array
  • Stack
    • A Stack is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again.
    • This is also referred to as the "Last In First Out (LIFO)" principle.
  • Hashmap
    • HashMap maps a key and a value. It does not guarantee any order of the elements stored internally in the map
  • Hashtable
    • Hashtable is synchronized
    • Hashtable does not allow null keys or values.
  • Treemap
    • TreeMap also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values.
  • Linked Hashmap
    • Having order when iterate

Thursday, 19 October 2017

1.     What's New in JDK 8
a.      Lambda Expressions
b.      Functional Interfaces
c.       Default methods                                                            
d.      Static Methods
e.      Method Reference and Constructor reference using double column operator(::)
f.        Stream API
g.      Date and Time API(Joda API)
2.     Purpose of Java 8
a.      To  simplify programming
                                                              i.      Less code
                                                            ii.      Maintainable
                                                          iii.      Readable
b.      To get the benefits of the functional program in java, Java uses lambda expressions.
c.       To enable parallel processing

3.      Lambda expressions
a.      Lambda expressions are methods which are do not belong to a class. They are just functions exist in isolation and that function can be treated as values.
b.      Functions as Values
                                                              i.      Normally, We can assign a string or any objects into a variable.
                                                            ii.      Lambda expression is  a method which has assigned to a variable. If we are assigning we do not need other method signature. So the lambda expression signature will be like below code,
aVariable = ()-> {System.out.println("HIIII");}
                                                          iii.      Lambada expressions with parameters.
lambdaWithParamater = (int x)->{x= x+}
c.       Steps to create Lambda Expression Java
                                                              i.      Create an Interface with abstract method having the same signature of the lambda function and use it as the type for lambda expression variable. This interface must have only one method.
                                                            ii.      To run this action, call method in the interface.
                                                          iii.      Its just like implementation of singe function.
public interface LambdaType {
     void foo();
public static void main(String[] args) {   
LambdaType myLambmadaVoidNoParam = ()->{System.out.println("HIII");};
myLambmadaVoidNoParam.foo();     
   }
d.      Lambda Examples
e.      Why lambda expressions ?
                                                              i.      We are using lambda expression to enable functional programming in java.
                                                            ii.      To write more readable, maintainable and clean less code.
                                                          iii.      To use apis very easily effectively.
                                                           iv.      To enable processing also
4.     Function Interface
a.      Java.util.function has special interface like bleow, it contains generic methods used as type for lambda expression wirh same type and signature.
                                                              i.      Predecate Interface
1.      It is already having boolean method. So whenever we need a lambda expression with Boolean return type use Predicate as  type. No nned to create another interface.
2.      Lot of other interfaces available like this.

5.     Streams
List.stream().filter(student->getName().startWith(“C”)).foreach(p->System.out.println(p.getName())).

a.      Stream consists of 3 main elements
                                                              i.      Source
1.      Collection
                                                            ii.      Operations
1.      Filter(), used to give condition
                                                          iii.      end operations
1.      count()
b.      More succinct code, sometimes just one liner
c.       You can pass lambda expression, which gives you the immense flexibility to change what you do in the loop.
d.      .parallel() can be used for parallel operations.
e.       ForEach looping can be made parallel with minimal effort e.g. without writing a single line of concurrent code, all you need to do is call parallelStream() method. 
f.         forEach() method is defined at two places, on Iterable interface as well as on Stream class. which means list.forEach() and list.stream.forEach() both are valid.
g.      Prefer using forEach() with streams because streams are lazy and not evaluated until a terminal operation is called. 
h.      forEach() is a terminal operation, you cannot call any method on stream after this.
i.        When you run forEach() method on parallel stream the order on which elements are processed is not guaranteed, though you can use forEachOrdered() to impose ordering.
j.        forEach() method accepts a Consumer instance, which is a functional interface, that's why you can pass a lambda expression to it. 
6.     PUT vs POST
a.      PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)! 
b.      POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
c.       PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.
7.     JBOSS deployment
a.      JBoss AS 7: Copy the .war file to JBOSS_HOME/standalone/deployments.
b.      Actually, for the latest JBOSS 7 AS, we need a .deeploy marker even for archives. So add a marker to trigger the deployment. 
c.        To start server:
> cd bin
              > standalone.bat
      start tomcat
         cd bin
         startup.bat

8.     1.6 to 1.8 migration
a.      upgraded from Java 6 to Java 8, to benefit from improvements in speed, brevity of code, and lower memory usage.
b.      The JDK is backwards compatible, meaning that JDK 8 can run binaries produced by JDK 7 and JDK 6. The javac compiler can also produce binaries targeting earlier versions of the JDK. In planning to upgrade, we will use this capability.
c.       When upgrading infrastructure, it is important to segment the architecture. Rather than upgrading everything at the same time, separate it into different environments so that you can test each one on its own.
d.      Environment Variables for installation
                                                              i.      PATH – identifies which actual java executable your system will use when you call java. You can circumvent this by explicitly calling the executable via /opt/jdk8/bin/java or /opt/jdk7/bin/java commands. Just call the one you want to use at the time. If you use scripts that rely on environment variables, consider isolating your terminals if you change the environment.
                                                            ii.      JAVA_HOME – some applications use this variable to identify where Java is.
                                                          iii.      Test your upgrade the following commands:
1.      java -version
2.      This should reply back with 1.8 or 1.7 depending on which you want. Just make sure it is right

3.      echo $JAVA_HOME

Friday, 15 September 2017


public class DeadLockEx { private String str1 = "SPRING"; private String str2 = "HIBERNATE"; public static void main(String[] args) { DeadLockEx app = new DeadLockEx(); app.t1.start(); app.t2.start(); } Thread t1 = new Thread("Thead 1") { public void run() { while (true) { synchronized (str1) { synchronized (str2) { System.out.println(str1 + str2); } } } } }; Thread t2 = new Thread("Thead 2") { public void run() { while (true) { synchronized (str2) { synchronized (str1) { System.out.println(str2 + str1); } } } } }; }

Thursday, 7 September 2017


  • Need to find missing number between 1 to N with low time complexity O(n).
  • Step1: Get sum of natural numbers from 1 to N as N x(N+1)/2
  • Step2: Get sum of array elements
  • Step3: Missing number = natural numbers sum - array sum
      FindMissingNumber.java
public class FindMissingNumber { private static final int END_NUMBER = 10; private int getMissingNumber(int[] arr) { int missingNum = 0; int arrSum = 0; for (int i = 0; i < arr.length; i++) { arrSum += arr[i]; } int naturalSum = END_NUMBER * (END_NUMBER + 1) / 2; missingNum = naturalSum - arrSum; return missingNum; } public static void main(String[] args) { int[] arr = { 1, 2, 3, 0, 5, 6, 7, 8, 9, 10}; FindMissingNumber app = new FindMissingNumber(); int missingNum = app.getMissingNumber(arr); System.out.println("Missing Number = " + missingNum); } } ****** OUTPUT ******** Missing Number = 4 ******* OUTPUT ********


  • Abstraction is one among the oops concepts and it means hiding the implementation details.In java abstraction can be achieved by two methods.
    1. Abstract Class
    2. Interface
      Abstract Class
  • Abstract class contains both unimplemented and implemented methods. Abstratct class must have the keyword abstract and it may not contains any abstract method.
  • If it acontains any abstract method then all subclasses must have to implement it.
  • Abstarct classes can be initiated by exending it.
  • We can use abstract class when some functionalities are common across all subclasses and some of the functionlaties differs.
  • Consider we have Bank as abstarct class and it has implemented methods deposit() and withdraw(). Here deposit() and withdraw() are common across all banks. calcualte() is varies based on bank differs. So here we can use abstarct class.
      Bank.java
public abstract class Bank { public void deposit(double ammount) { System.out.println("Ammount has deposited, " + ammount); } public void withdraw(double ammount) { System.out.println("Ammount has withdrawn, " + ammount); } public abstract double calculateInterest(); }
      HDFC.java
public class HDFC extends Bank { private static final double MONTHLY_DEDUCTION = 12; private static final double YEARLY_DEDUCTION = 40; private double ammount = 1000; @Override public double calculateInterest() { double interest = ammount + MONTHLY_DEDUCTION + YEARLY_DEDUCTION; return interest; } }
      ICICI.java
public class ICICI extends Bank { private static final double MONTHLY_DEDUCTION = 12; private static final double QUARTARLY_DEDUCTION = 15; private double ammount = 1000; @Override public double calculateInterest() { double interest = ammount + MONTHLY_DEDUCTION + (QUARTARLY_DEDUCTION * 4); return interest; } }
      Interface
  • Interface is a blueprint of a class and it contains only public abstract methods and staic final variables(contants)
  • Sub classes able implemeting interface by implementing all nethods.
  • Interfaces can be use when we need to achieve muliple inheritance because it supports multiple inheritance.
Java 8
  • After being introduced Default Method, the Interfaces and abstract Classes seems similar, however, they still different concept in Java 8.
  •  Abstract Class can define constructor. They are more structured and can have a state associated with them. 
  • While in contrast, default method can be implemented only in the terms of invoking other Interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.

Search This Blog

Contact us

Name

Email *

Message *