Interview Questions


In this blog, we are going to discuss popular java theoretical interview questions and also JAVA dumps which you will face almost every online coding interview rounds. 


******************************JAVA Snippets**************************************

1. What would be the output of the following snippet?

public class Dump1 {
  public static void main(String[] args) {
    char c='a';
    Integer val1=new Integer(c);
    Character val2=new Character(c);
     if(val1.equals(val2))
         System.out.println("Equals");
    else if(val1.intValue()==val2.charValue())
         System.out.println("Eq");
    else
         System.out.println("Outside");
 }
}

Answer==> Here output would be "Eq"

Explanation==> val1.equals(val2) will not work here as equals() method check whether the contents are same and both the object belong to same class, here we are checking Integer equals with Character which will return false.

val1.intValue()==val2.charValue(), this will work here as we checking 97=='a', that means internally it will check the ASCII value 'a' which is 97, so it returns TRUE.

2. What would be the output of the following snippet?

public class MyThred1 extends Thread{
public MyThred1() {
System.out.println("Hi");
}
public void run()
{
System.out.println("bye");
}
public void run(String s)
{
System.out.println("bss");
}

public static void main(String[] args) {
Thread t1=new MyThred1(){
public void run()
{
System.out.println("foo");
}
};
t1.start();
}
}

Answer=> Output would be as below:
Hi
foo

Explanation: Default constructor will always execute first here and nested run() method will get preferences here. 

3. What would be the output of the following snippet?

public class MyThreadTest extends Thread{
private  String threadName;
public MyThreadTest(String name){
threadName=name;
}
public void run(){
while(true){
System.out.println(this.threadName);
}
}
public void start(){
System.out.println("Hi");
}
public static void main(String[] args) {
MyThreadTest t1=new MyThreadTest("SM");
MyThreadTest t2=new MyThreadTest("MM");
t1.start();
t2.start();
}
}

Answer=> As we have overridden start() method of Thread class, it will never invoked run() method. So output would be:
Hi
Hi 

4. What would be the output of the following snippet?

public class MyThread2 implements Runnable {
private int x;
private int y;
@Override
public synchronized void run() {
for(;;)
System.out.println("X is: "+ x++ +"Y: "+y++ +"Thread name: "+ Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread2 t2=new MyThread2();
new Thread(t2).start();
new Thread(t2).start();
}
}

Answer=> As both the Threads are pointing to the same object as t2 and for loop does not have specific condition to stop. When thread 0 is executing, as the method is synchronized, so it will run for infinite time and Thread 1 will never get executed. Here output would be like below:

X is: 1132653Y: 1132653Thread name: Thread-0
X is: 1132654Y: 1132654Thread name: Thread-0
X is: 1132655Y: 1132655Thread name: Thread-0
X is: 1132656Y: 1132656Thread name: Thread-0

...............................................................................

5. What would be the output of the following snippet?

public class MethodOverLoading {
public void print(Object ob)
{
System.out.println("Object class");
}
public void print(String st)
{
System.out.println("String class");
}

public static void main(String args[])
{
MethodOverLoading ml=new MethodOverLoading();
ml.print(null);
}
}

Answer=> As we are passing NULL as method parameter so it will go print(String st) method. Output would be:
String class

6. What would be the output of the following snippet?

public class ExceptionTest2 {
public void method2(){
try{
throw new NullPointerException();
}finally{
System.out.println("Hey");
}
}
public static void main(String[] args) {
ExceptionTest2 test2=new ExceptionTest2();
test2.method2();
}
}

Answer=> Finally will always get executed here even though exception has been raised in try block. If we call System.exit() in try block then finally block will never get executed.
Here output would be:
Hey
Exception in thread "main" java.lang.NullPointerException
at com.sourin.dumps.ExceptionTest2.method2(ExceptionTest2.java:6)
at com.sourin.dumps.ExceptionTest2.main(ExceptionTest2.java:13)

7.  What would be the output of the following snippet?

public class ExceptionTest {
public static void test1(){
throw new NullPointerException();
}
public static void main(String[] args) {
try{
test1();
}catch(Exception e){
System.out.println("Hi");
test1();
}
}
}

Answer=> Here output would be:
Hi
Exception in thread "main" java.lang.NullPointerException
at com.sourin.dumps.ExceptionTest.test1(ExceptionTest.java:5)
at com.sourin.dumps.ExceptionTest.main(ExceptionTest.java:12)

8.  What would be the output of the following snippet?

public class Constructor {
static String str;
public void Constructor()
{
System.out.println("Hi");
str="hello";
}
public static void main(String args[])
{
boolean b1=true;
boolean b2=false;
boolean b3=true;
if(b1& b2 | b2&b3 |b2)
System.out.println("h");
if(b1&b2| b2&b3|b2|b1)
System.out.println("hi");
}
}

Answer=> Here output would be:
hi

9. What would be the output of the following snippet?

public class Test1 {
public void run1()
{
System.out.println("Hellow world: ");
}
}

public interface Test3 {
public void run1();
}

public interface Test4 extends Test3{

}

public class Test2 extends Test1 implements Test4{
public static void main(String args[])
{
new Test2().run1();
}
}

Answer=> Here compiler will try to find out the run1() method as its there in Test3 interfaces. Test1 class already has run1() method which is extended by Test2 class. So here compiler will not complain any thing and it will print like below:
Hellow world:

10. What would be the output of the following snippet?

public class ExceptionTest3 {
public static int method()
{
try{
System.out.println("Hi");
return 2;
}catch(Exception e)
{
return 3;
}finally
{
return 5;
}
}
public static void main(String[] args) {
System.out.println(method());
}
}

Answer=> finally would always get executed as it get more preference over try and catch block. Here output would be:
Hi
5

11. What would be the output of the following snippet?

public class ParentOverrriden {
public void display(){
System.out.println("Parent class");
}

}

public class ChildOverride extends ParentOverrriden {
private void display()
{
System.out.println("Child class");
}
public static void main(String args[])
{
ParentOverrriden ov=new ChildOverride();
ov.display();
}
}

Answer: We will get compilation error here we we are reducing the visibility of parent method as private in child class. During compilation time, we will get "Cannot reduce the visibility of the inherited method from ParentOverrriden".

So output would be compilation error.

12. What would be the output of the following snippet?

public class ParentOverrriden {
private void display(){
System.out.println("Parent class");
}

}

public class ChildOverride extends ParentOverrriden {
public void display()
{
System.out.println("Child class");
}
public static void main(String args[])
{
ParentOverrriden ov=new ChildOverride();
ov.display();
}
}

Answer: Dynamic plymorphism will happen during run time, but here during compilation time we will get error because display() method is private in  ParentOverrriden  class, so while creating object of this class, this method would be invisible outside of this class. The output would be compilation error as: "The method display() from the type ParentOverrriden is not visible".

13. What would be the output of the following snippet?

public class ParentOverride {
public static void display()
{
System.out.println("Hey, in parent class");
}

}

public class ChildOverriden extends ParentOverride {
public static void display(){
System.out.println("Hi, in child class");
}
public static void main(String[] args) {
ParentOverride pv=new ChildOverriden();
pv.display();
}
}

Answer: Static method can not be overridden in JAVA, that means dynamic polymorphism will not work in case of static method.
Output would be as:
Hey, in parent class

14. What would be the output of the following snippet?

public class ChildOverriden{
public static void display(int a){
System.out.println("Hi, in child class"+a);
}
public static void display(int a,int b){
System.out.println("Hi, in child class"+a+" b is:"+b);
}
public static void main(String[] args) {
ChildOverriden cd=new ChildOverriden();
cd.display(10);
}

}

Answer: Method over loading can work in case of static methods. So output would be:
Hi, in child class10

15. What would be the output of the following snippet?

public class MyThreadTest3 extends Thread{
public void run(){
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThreadTest3 t3=new MyThreadTest3();
t3.start();
t3.start();
}
}

Answer: Here same start() method is called two times by the same thread, so we will get IllegalThreadStateException while calling second time start() method. Output would be:

Thread is running
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at com.sourin.dumps.MyThreadTest3.main(MyThreadTest3.java:12)

16. What would be the output of the following snippet?

public class MyThreadTest3 extends Thread{
public void run(){
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThreadTest3 t3=new MyThreadTest3();
t3.start();
t3.run();
}

}

Answer: Here we will have two Threads, main thread and t3 thread. The moment we call t3.start() it will be running a new Thread. t3.run() will be running in same thread. Output would be:

Thread is running
Thread is running

17. What would be the output of the following snippet?

public class OverLoadingTest {
public void m1(int a, float f){
System.out.println("int and Float args");
}
public void m1(float f,int a){
System.out.println("float and int args");
}
public static void main(String[] args) {
OverLoadingTest test=new OverLoadingTest();
test.m1(10, 10f);
test.m1(10f, 20);
test.m1(10, 10);
}
}

Answer: For Overloading, JAVA up cast the data type which is int-->long-->float-->double. In our snippet, compiler shows compilation error at test.m1(10, 10) because this can be converted to m1(int a, float f) as well as m1(float f,int a).

So compiler will not be able to decide here which method it should get converted. It will show below compilation error:

"The method m1(int, float) is ambiguous for the type OverLoadingTest"

18. What would be the output of the following snippet?

public class StaticCheck {
static{
System.out.println("Display 1");
}
{
System.out.println("Diplay 2");
}

public static void main(String args[])
{
{
System.out.println("diplay main");
}
{
System.out.println("Display 4");
}
}

}

Answer: Static block does not depend on Object, static block load at the time of class loading. Normal blocks  which are outside of main() method, are loading at the time of object creation.
So here output would be:

Display 1
diplay main
Display 4

19. What would be the output of the following snippet?

public class StaticCheck {
static{
System.out.println("Display 1");
}
{
System.out.println("Diplay 2");
}
static{
System.out.println("Display 3");
}

public static void main(String args[])
{
StaticCheck chk=new StaticCheck();
{
System.out.println("diplay main");
}
{
System.out.println("Display 4");
}
}

}

Answer:  Static block does not depend on Object, static block load at the time of class loading. Normal blocks  which are outside of main() method, are loading at the time of object creation.
So here output would be:

Display 1
Display 3
Diplay 2
diplay main
Display 4

20. What would be the output of the following snippet?

public class ArgumentNull {
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}

}

Answer: As we are sending NULL argument here, the class will get compiled and nothing will be printed on the console.



Why String is Immutable in Java?
String is Immutable due to below reasons.
a)Suppose we have 3 objects like:
String one="JAVA";                  
String two="JAVA";
String three="JAVA";

So there is one object "JAVA" in String pool and one, two, three will point the same object.

So now if we update String one by calling
one.toLowerCase(), then String one is "java",
now what will happen for String two and three?

To solve this problem, String is immutable in java.

So if anybody is updating String one by calling  one.toLowerCase() then one will point to a new Object called "java" but String two and three will point the same object "JAVA".

b) String is widely used as java parameters for different classes like JDBC connection and others where we are passing username, password, hostName etc to open database connection.

So if String is not immutable then somebody can easily change the username and password which can override the functionality and that will cause a security issue.

Security and String pool are the main reasons of  String Immutable.

----------------------------------------------------------------------------------------

Advantage of String Immutable

Advantages of String Immutable are:
Re-usability:  This is one of the biggest advantage of String Immutable. String pool is a storage area in java heap where all the String objects resides. When a String is created, it first check in String pool, if the object is already there in String Pool then only reference of that object sent back, else a new Object will be created. So from the above diagram we can see that one, two and three are pointing to same object "JAVA", so we can use the same object for different variables which can save lot of memory as well.

Thread safe: As String is declared as final, so it is thread safe. That means one String can be shared between multiple threads which increases the readability of code.

Efficiency/ Caching: The hashcode of the string is frequently used in Java. Being Immutable, in HashMap if we use String as key, so java ensures that its hascode will always  be same and it can be cached without worrying the changes. It means there is no need to calculate hascode for same String key in HashMap.

------------------------------------------------------------------------------------------


How many String objects are created when String s=new String("JAVA")?

It will create two objects. first String s=new String("JAVA") create an object on heap and second String s="JAVA" creates in String pool.

While creating the second String compiler will check whether its there in String Pool or not. If the Object is present in String pool then reference will be sent back else new object will be created in pool.

----------------------------------------------------------------------------------------

How to create a immutable object in JAVA like String?


Below are the requirement to make an object Immutable:
       a) Declare the class as Final so that no other class can inherit it.
       b) Make all the members of that class as Final and private , set its value explicitly
            through constructor.
       c) We should not provide any setter method of that class just to ensure its member values
            can not be updated.
       d) We may provide only getter methods to fetch members variables.

Below one is the sample example of Immutable object:

public final class Immutable {
private final String name;
private final Integer age;

public Immutable()
{
this.name=null;
this.age=null;
}
public Immutable(String name, Integer age)
{
this.name=name;
this.age=age;
}

public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public static void main(String[] args) {
Immutable s1=new Immutable("Abc",20);

}
}

---------------------------------------------------------

Difference between StringBuffer and StringBuilder in JAVA

StringBuffer and StringBuilder both are mutable which means we can change its value.

StringBuffer has the same methods as like as StringBuilder but all are synchronized which means StringBuffer is ThreadSafe where StringBuilder is not.

We can use StringBuffer where the buffer can be shared between multiple threads, StringBuilder we can use only in Single threaded application.

As StringBuffer is Thread safe, so all its methods are synchronized, that is why performance wise it slower than StringBuilder which is not thread safe.

----------------------------------------------------------------------------------------------------------

Why do we need StringBuffer or StringBuilder over String?

StringBuffer and StringBuilder are mutable objects where String Immutable object that means every time we update the content of String, it will create a new Object which can cause memory issue in heap.

String s1="Add me ";  // here s1 is pointing to String object "Add me".
String s1=s1+"Linkedin"// now due to String Immutability, s1 is pointing to new object called "Add                                            //me Linkedin" instead of "Add me" .
To solve this problem we can use StringBuffer or StringBuilder which can ensure there will be one object.

StringBuilder sb=new StringBuilder("Add me");
sb.append("Linkedin");      // Here only one object is there in memory.

So, if we are not sure that object content will be updated frequently or not in that case we should use StringBuffer/StringBuilder rather than String.

----------------------------------------------------------------------------------------------------------------

What is Singleton pattern?

Singleton pattern ensures that class has only one instance and it provides a global point to access it.
Real time example of Singleton pattern is JDBC  getConnection() method.
Below one is the sample implementation of Singleton class:

public class SingleTon {
private static SingleTon singletonObj;
//constructor should be always private ,else somebody can easily     //creates its object.
private SingleTon()
{

}
public static SingleTon getInstance()
{
if(singletonObj==null)
singletonObj=new SingleTon();

return singletonObj;

}

}

For more details click on Singleton






No comments:

Post a Comment

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...