Java Interview Questions - 10

Below are the few set of java interview questions to get more knowledge on core java basics. For most of the questioned we need to find the output and for few questions have to get any compile time error or run-time error??

QUESTION - 1 - Output ??

public class ArrayTest {

 public static void main(String[] args) {
  
  int[] arr = {1,2,3,4};
  myMethod(arr[1], arr);
  System.out.println(arr[1] +" : "+arr[2]);
 }
 
 static void myMethod(int val, int arr[]){
  arr[val] = 100;
  val = 500;
 }
}



QUESTION - 2 - Output ??

import java.util.ArrayList;
import java.util.Collection;

public class CollectionTest {

 public static void main(String[] args) {
  Collection<Object> coll = new ArrayList<Object>();
  myMethod(coll, "java");
  myMethod(coll, 123);
 }
 
 static void myMethod(Collection<Object> coll, Object val){
  coll.add(val);
  System.out.println(coll);
 }
}



QUESTION - 3 - Output ??

public class DoubleNumberTest<D extends Number> {

 private D d;
 
 public DoubleNumberTest(D d) {
  this.d = d;
 }
 
 public double getDouble(){
  return d.doubleValue();
 }
 
 public static void main(String[] args) {
  DoubleNumberTest<Integer> obj = new DoubleNumberTest<Integer>(new Integer(24));
  System.out.println(obj.getDouble());
 }
}



QUESTION - 4 - Will it compile without any error ?

public class EnumTest {

 public EnumTest() {
  System.out.println("Inside Constructor");
  enumList();
 }
 
 public void enumList(){
  public enum myEnum {HIGH, MEDIUM, LOW}
 }
 
 public static void main(String[] args) {
  new EnumTest();
 }
}



QUESTION - 5 - Will it compile without any error ?

public class ExceptionTest {

 public static void main(String[] args) {
  
  try{
   int val = 1000;
   val = val / 0;
  
  }catch(Exception e){
   e.printStackTrace();
  
  }catch (ArithmeticException e) {
   e.printStackTrace();
  }
 }
}



QUESTION - 6 - Output ??

class Parent{
 int val = 100;
 
 public void myMethod(){
  System.out.print("Im Parent");
 }
}

class Child extends Parent{
 int val = 200;
 
 public void myMethod(){
  System.out.print("Im Child");
 }
}

public class Inheritance1Test {
 
 public static void main(String[] args) {
  
  Parent obj = new Child();
  System.out.print(obj.val+", ");
  obj.myMethod();
 }
}



QUESTION - 7 - Output ??

class Class1{
 public Class1() {
  System.out.println("Inside Class1");
 }
}

class Class2{
 public Class2() {
  System.out.println("Inside Class2");
 }
}

class Class3{
 public Class3() {
  System.out.println("Inside Class3");
 }
}

public class InheritanceTest {

 public static void main(String[] args) {
  new Class3();
 }
}



QUESTION - 8 - Will it serialize ??

import java.io.Serializable;

class Car implements Serializable{
 
}

class Colors {
 private String color;
 public Colors(String color) {
  this.color = color;
 }
}

public class SerializableTest implements Serializable {

 private Car car;
 private Colors[] colors = new Colors[4];
 
 public SerializableTest() {
  car = new Car();
  colors[0] = new Colors("red");
  colors[1] = new Colors("blue");
  colors[2] = new Colors("white");
  colors[3] = new Colors("black");
 }
 
 public static void main(String[] args) {
  
  /*
   * If we serialize obj, will Colors class also get Serializable ??
   */
  SerializableTest obj = new SerializableTest();
  
 }
}



QUESTION - 9 - Output ??

import java.util.HashSet;
import java.util.Set;

public class SetTest {

 public static void main(String[] args) {
  
  Set mySet1 = new HashSet();
  Set mySet2 = new HashSet();
  
  int j = 0;
  short i = 0;
  
  for(;i<100;i++,j++){
  
   mySet1.add(i);
   mySet1.remove(i-1);
   
   mySet2.add(j);
   mySet2.remove(j-1);   
  }  
  System.out.println("Int Set Size   : "+mySet1.size());
  System.out.println("Short Set Size : "+mySet2.size());
 }
}



QUESTION - 10 - Output ??

public class StringCompare {

 public static void main(String[] args) {
  
  String s1 = "java";
  String s2 = s1.intern();
  
  if(s1.equals(s1) && s1 == s2){
   System.out.println("first");
  }
  if(s1.equals(s1) && s1 != s2){
   System.out.println("second");   
  }
  if(!s1.equals(s1) && s1 == s2){
   System.out.println("third");
  }
  if(!s1.equals(s1) && s1 != s2){
   System.out.println("fourth");
  }
 } 
}



QUESTION - 11 - Will it compile without any error ?

public class StringMethod {

 private void myMethod(String str){
  System.out.println("Inside String method");
 }
 
 private void myMethod(StringBuilder str){
  System.out.println("Inside StringBuilder method");
 }
 
 private void myMethod(StringBuffer str){
  System.out.println("Inside StringBuffer method");
 }
 
 public static void main(String[] args) {
  new StringMethod().myMethod(null);
 }
}



QUESTION - 12 - Output ??

public class Thread1Test extends Thread {

 @Override
 public void run() {
  System.out.println("Inside run");
 }
 
 public static void main(String[] args) {
  Thread thread = new Thread(new ThreadTest());
  thread.start();
  thread.start();
 }
}



QUESTION - 13 - Output ??

public class ThreadTest extends Thread {

 @Override
 public void run() {
  System.out.println("Inside run");
 }
 
 public static void main(String[] args) {
  Thread thread = new Thread(new ThreadTest());
  thread.start();
  try {
   thread.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}



QUESTION - 14 - Output ??

public class TwoDArrayTest {

 public static void main(String[] args) {
  
  int[][] val = {{1,2,3}, {4,5,6}};
  int[][] valClone = val.clone();
  
  valClone[0][0] = 100;
  System.out.println(val[0][0]);
  System.out.println(valClone[0][0]);
  
  valClone[1] = new int[]{111, 222, 333};
  System.out.println(val[1][1]);
  System.out.println(valClone[1][1]);
 }
}



QUESTION - 15 - Output ??

import java.util.ArrayList;
import java.util.Collection;

public class ValueOfTest {

 public static void main(String[] args) {
  
  myMethod(new ArrayList<Object>());
  
 }
 
 public static void myMethod(Collection<Object> coll){
  
  Number n = null;
  coll.add(n);
  coll.add(Integer.valueOf(100));
  coll.add(Float.valueOf(200));
  
  System.out.println(new ArrayList<Object>().addAll(coll));
 }
}


ANSWERS:

1. 2 : 100

2.  [java]
     [java, 123]

3. 24.0

4. Compilation error - The member enum myEnum can only be defined inside a top-level class or interface or in a static context

5. Compilation error - Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception

6. 100, Im Child

7. Inside Class3

8. Won't serialize and we will get "java.io.NotSerializableException" when we access Color class

9. Int Set Size   : 100
    Short Set Size : 1

10. first

11. Compilation error - The method myMethod(String) is ambiguous for the type StringMethod

12. Prints "Inside run" and "IllegalThreadStateException" while starting thread again.

13. Inside run

14.  100
       100
       5
       222

15. true

PriorityQueue based on custom Priority setting

 
Just by name "Queue" we can think of big "Q" for Movie tickets booking in our olden days or have read about FIFO order. But here "PriorityQueue" is little different and it follows same Queue functionality with Priority items are out first.
Lets take scenario where there are lot of incoming tickets in support system with multiple priorities (CRITICAL, HIGH, MEDIUM, LOW). Here support team needs to serve all tickets based on their priority than their logged order, like critical priorities first and then high, medium and low priority tickets at last.
Lets see simple example class which takes multiple Tickets along with priority and while we are reading critical tickets 1st, high tickets 2nd, medium tickets 3rd and low priority tickets at last.


Ticket.java

/*
 * Simple Ticket class takes input as ticket number, Ticket details
 * along with priority of each ticket
 */
public class Ticket implements Comparable<Ticket>{
 
 enum Priority{
  CRITICAL, HIGH, MEDIUM, LOW 
 }
 
 private int ticketId;
 private String task;
 private Priority priority;
 
 public Ticket(int ticketId, Priority priority, String task) {
  this.ticketId = ticketId;
  this.task = task;
  this.priority = priority;
 }
 @Override
 public String toString() {
  return ticketId +" : "+task;
 }
 
 @Override
 public int compareTo(Ticket o) {
  return this.priority.compareTo(o.priority) ;
 }
}



PriorityQueueExample.java

import java.util.PriorityQueue;
import java.util.Queue;

import com.pract.Ticket.Priority;

public class PriorityQueueExample {

 public static void main(String[] args) {
  
  // Adding 6 Tickets with different priority 
  Queue<Ticket> ticketQueue = new PriorityQueue<Ticket>();
  ticketQueue.offer(new Ticket(1, Priority.LOW, "Low priority task - Cleanup activity"));
  ticketQueue.offer(new Ticket(2, Priority.MEDIUM, "Medium priority task - Taking dump"));
  ticketQueue.offer(new Ticket(3, Priority.HIGH, "High priority task - Production update"));
  ticketQueue.offer(new Ticket(4, Priority.MEDIUM, "Medium priority task - Testing"));
  ticketQueue.offer(new Ticket(5, Priority.HIGH, "High priority task - Important bug fixing"));
  ticketQueue.offer(new Ticket(6, Priority.CRITICAL, "Critical priority task - Hacker Thread"));
  
  listTicketsBasedOnPriority(ticketQueue);
 }
 
 /*
  * Listing tickets based on priority like 
  * CRITICAL, HIGH, MEDIUM and then LOW tickets.
  */
 private static void listTicketsBasedOnPriority(Queue<Ticket> tickets){
  while (!(tickets.isEmpty()))
   System.out.println(tickets.poll());
 }
}




OUTPUT:

6 : Critical priority task - Hacker Thread
5 : High priority task - Important bug fixing
3 : High priority task - Production update
2 : Medium priority task - Taking dump
4 : Medium priority task - Testing
1 : Low priority task - Cleanup activity

Here in output we can see list of tickets printed by priority order wise.

Java 8 - StringJoiner

In Java-8 we got new class called StringJoiner to join multiple strings. Nothing new in StringJoiner class when we compare with already existing classes like StringBuffer and StringBuilder. Only the difference here we can set prefix and suffix along with delimiter, or we can set only delimiter by using different constructor. Lets see simple example as how to use StringJoiner from Java-8.
Java 8 - StringJoiner

public class StringJoinerExample {

 public static void main(String[] args) {
  
  StringJoiner sJoin = new StringJoiner(",");
  
  sJoin.add("java");
  sJoin.add("python");
  sJoin.add("C#");
  sJoin.add("scala");
    
  System.out.println(sJoin);
 }
}

OUTPUT:

java,python,C#,scala




public class StringJoinerExample {

 public static void main(String[] args) {
  
  StringJoiner sJoin = new StringJoiner("," ,"{" ,"}");
  
  sJoin.add("java");
  sJoin.add("python");
  sJoin.add("C#");
  sJoin.add("scala");
    
  System.out.println(sJoin);  
 }
}

OUTPUT:
{java,python,C#,scala}

Print Odd and Even number in sequence using two threads

 
One of the interview question on Thread to Print Odd and Even number in sequence using two threads. Below program will print odd and even numbers in sequential order using 2 threads. 1st thread will take care of printing odd numbers and 2nd thread will take care of printing even numbers. Here 1st thread will print odd number and go for waiting state after notifying to 2nd thread to print even number. Next 2nd thread will print even number and go for waiting state after notifying to 1st thread. Its goes on...
Print Odd and Even number in sequence using two threads



class Numbers implements Runnable{

 private int number = 1;

 @Override
 public void run() {
  
  Object lock = Thread.currentThread().getClass();
  
  if(Thread.currentThread().getName().equals("odd")){
   
   synchronized (lock) {
    while(true){
     System.out.println("ODD  : "+number++);
     lock.notify();
     try {
      Thread.sleep(100);// Just to print slowly
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
  }else{
   synchronized (lock) {
    while(true){
     try {
      Thread.sleep(100);
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("EVEN : " + number++);
     lock.notify();
    }
   } 
  }  
 }
}

public class SequenceNumber {
 
 public static void main(String[] args) throws InterruptedException {
  Numbers obj = new Numbers();

  Thread t1 = new Thread(obj, "even");
  Thread t2 = new Thread(obj, "odd");
  t1.start();
  Thread.sleep(500);
  t2.start();
 } 
}

OUTPUT:

ODD  : 1
EVEN : 2
ODD  : 3
EVEN : 4
ODD  : 5
EVEN : 6
ODD  : 7
EVEN : 8
ODD  : 9
EVEN : 10
ODD  : 11
EVEN : 12
ODD  : 13
EVEN : 14
ODD  : 15
EVEN : 16
ODD  : 17
EVEN : 18
ODD  : 19
EVEN : 20
ODD  : 21
EVEN : 22
ODD  : 23
EVEN : 24
ODD  : 25


Java Interview Questions - 9

Below are few java interview questions where candidate need to be more clear on basics and how it works when they asked simples questions. All these questions are programmatic questions and need to answer whether program will compile and run without any error and next what will be the out?


package com.pract;

import java.lang.reflect.Method;

class DeclaredMethodsPractBase {

 public void myParent1(){};
 protected void myParent2(){};
 private void myParent3(){};
}

public class DeclaredMethodsPract extends DeclaredMethodsPractBase{
 
 public void myChild11(){};
 protected void myChild12(){};
 private void myChild13(){};
 
 public static void main(String[] args) throws ClassNotFoundException {
  
  Class<?> classs = Class.forName("com.pract.DeclaredMethodsPract");
  
  Method[] methods = classs.getDeclaredMethods();
  
  for (Method method : methods) {
   System.out.print(method.getName() + ", ");
  }
 }
}

1. Runtime error
2. main, myChild11, myChild12, myChild13, myParent1,
3. main, myChild11, myChild12, myChild13, myParent1, myParent2,
4. main, myChild11, myChild12, myChild13, myParent1, myParent2, myParent3,



public class EnumPract {

 enum Numbers{ONE, TWO, THREE};
 
 public static void main(String[] args) {
  
  System.out.print((Numbers.ONE == Numbers.ONE) + ", ");
  System.out.print(Numbers.ONE.equals(Numbers.ONE));
 }
}

1. Compile time error
2. true, false
3. false, false
4. false, true
5. true, true



public class InternPract {

 public static void main(String[] args) {
  String a1 = "Java";
  String a2 = new String("Java");
  String a3 = a1.intern();
  
  System.out.print((a1 == a2) + ", "+(a1 == a3));
 } 
}

1. false, true
2. true, true
3. true, false
4. false, false



import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapObjectPract {

 public static void main(String[] args) {
  
  Map<String, String> map = new HashMap<String, String>();
  
  System.out.print((map instanceof Object) + ", ");
  System.out.print((map instanceof Map) + ", ");
  System.out.print((map instanceof HashMap) + ", ");
  System.out.print(map instanceof Collection);
 }
}

1. true, false, true, false
2. false, true, true, false
3. true, true, true, false
4. false, false, true, false



public class OperatorPract {

 public static void main(String[] args) {
  
  int i = 0;
  i = i++ + method(i);
  System.out.print(i);
 }
 
 static int method(int i){
  System.out.print(i+":");
  return 0;
 }
}

1. 1:0
2. 1:1
3. 0:1
4. 0:0



class Recursion{
 int method(int n){
  int result = method(n - 1);
  return result;
 }
}

public class RecuPract {

 public static void main(String[] args) {
  Recursion obj = new Recursion();
  int val = obj.method(10);
  System.out.println("completed : "+ val);
 }
}

1. completed : 0
2. compile time error
3. Runtime error
4. completed : -1



class Test implements Runnable{
 
 @Override
 public void run() {
  System.out.print("HELLO : "+Thread.currentThread().getName() + ", ");
 }
}

public class RunnablePract {

 public static void main(String[] args) {

  Test obj = new Test();
  
  Thread t1 = new Thread(obj, "T1");
  Thread t2 = new Thread(obj, "T2");
  
  t1.start();
  t1.join();
  t2.start();
 }
}

1. Runtime error
2. HELLO : T1, HELLO : T2,
3. HELLO : T2, HELLO : T1,
4. Compile time error



import java.util.HashSet;

public class SetPract {

 public static void main(String[] args) {
  
  HashSet<Integer> set = new HashSet<Integer>();
  for(int i=0;i<100;i++){
   set.add(i);
   set.remove(i - 1);
  }
  
  System.out.println("SET SIZE ::: "+set.size());
 }
}

1. SET SIZE ::: 100
2. SET SIZE ::: 1
3. SET SIZE ::: 99
4. SET SIZE ::: 0



public class StringArrayPract {

 private String[] array;
 
 public StringArrayPract() {
  array = new String[10];
 }
 
 public void setArray(String val, int i){
  array[i] = val;
 }
 
 public String getArray(int i){
  return array[i];
 }
 
 public static void main(String[] args) {
  
  StringArrayPract obj = new StringArrayPract();
  System.out.println("VALUE IS : "+obj.getArray(5));
 }
}

1. Runtime error
2. VALUE IS : null
3. Compile time error
5. VALUE IS :



import java.util.TreeSet;

public class TreeSetPract {

 public static void main(String[] args) {
  
  TreeSet<String> tSet = new TreeSet<String>();
  tSet.add("one");
  tSet.add("two");
  tSet.add("three");
  tSet.add("one");
  
  for (String string : tSet) {
   System.out.print(string+", ");
  }
 }
}

1. one, two, three,
2. one, two, three, one
3. one, one, three, two,
4. one, three, two,