Java Tricky Interview Questions

Sometime back I wrote an article on Top 50 Java Programming Questions. Our readers liked it a lot. So today we will look into some tricky interview questions in Java.

Java Tricky Interview Questions

These are programming questions but unless you have a deep understanding of Java, it will be hard to guess the output and explain it.

1. Null as Argument

We have overloaded functions and we are passing null. Which function will be called and what will be the output of the program?

public class Test {
	public static void main(String[] args) {
		foo(null);
	}
	public static void foo(Object o) {
		System.out.println("Object argument");
	}
	public static void foo(String s) {
		System.out.println("String argument");
	}
}

2. Use “L” for long

Can you guess the output of the below statements?

long longWithL = 1000*60*60*24*365L;
long longWithoutL = 1000*60*60*24*365;
System.out.println(longWithL);
System.out.println(longWithoutL);

Explanation of Null Argument Tricky Question

According to Java specs, in case of overloading, the compiler picks the most specific function. Obviously String class is more specific than Object class, hence it will print “String argument”. But, what if we have another method in the class like below.

public static void foo(StringBuffer i){
	System.out.println("StringBuffer impl");
}

In this case, the Java compiler will throw an error as “The method foo(String) is ambiguous for the type Test”. String and StringBuffer have no inheritance hierarchy. So none of them are more specific to others. A method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error. We can pass String as a parameter to Object argument and String argument but not to the StringBuffer argument method.

Explanation for Long Variable

The output of the code snippet will be:

31536000000
1471228928

We are explicitly creating the first variable as long by adding an “L” suffix. So the compiler will treat it as long and assign it to the first variable. For the second statement, the compiler will perform the calculation and treat it as a 32-bit integer. Since the output is outside the range of integer max value (2147483647), the compiler will truncate the most significant bits and then assign it to the variable. Binary equivalent of 1000*60*60*24*365L = 011101010111101100010010110000000000 (36 bits). After removing 4 most significant bits to accommodate in 32-bit int, the new value = 01010111101100010010110000000000 (32 bits). This is equal to 1471228928 and hence the output. Recently I have created a YouTube video series for java tricky programs.

You can checkout more java example programs from our GitHub Repository.

Source:
https://www.digitalocean.com/community/tutorials/java-tricky-interview-questions