Java Tricky Interview Questions

Filed Under: Java

Sometime back I wrote an article with 8 java tricky programming questions and my friends liked it a lot. Today we will look into some java tricky interview questions.

Java Tricky Interview Questions

Recently I got two java questions that I will be explaining here.
java tricky interview questions

Java Tricky Interview Question 1

What is the output of the below program?


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

Java Tricky Programming Question 2

What will below statements print?


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

*****************************

Java Tricky Interview Question 1 Answer with Explanation

As we know that we can assign null to any object, so doesn’t compiler complains about this program? According to java specs, in case of overloading, compiler picks the most specific function. Obviously String class is more specific than Object class, hence it will print “String impl”.
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, java compiler will throw an error as “The method foo(String) is ambiguous for the type Test” because String and StringBuffer, 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 StringBuffer argument method.

Java Tricky Programming Question 2 Answer with Explanation

The output of the code snippet will be:


31536000000
1471228928

In case of the first variable, we are explicitly creating it as long by placing an “L” at the end, so the compiler will treat this at long and assign it to the first variable.

In the second case, the compiler will do 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)
Removing 4 most significant bits to accommodate in 32-bit int, value = 01010111101100010010110000000000 (32 bits)
Which is equal to 1471228928 and hence the output.

Recently I have created YouTube videos for java tricky programs, you should check them out. Also subscribe to my YouTube Channel to get notified when I add new videos.

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

Comments

  1. Chuck says:

    I think your explanation of question 2 is not complete, you don’t make it clear that the L modifies only the constant 365.. The multiplications are executed left to right, so in the first line of the example 1000*60*60*24 is computed in 32-bit arithmetic (it fits). The last operation multiplies that result by a long (365L) which forces the promotion to 64 bit.

    Observe:

    jshell> 1000*60*60*24
    $4 ==> 86400000

    jshell> 1000*60*60*24*365L
    $5 ==> 31536000000

    jshell> 1000*60*60*24*365*1L
    $6 ==> 1471228928

    jshell> 1000*60*60*24*365
    $7 ==> 1471228928

  2. Rajesh pawar says:

    public class Test
    {
    public static void main(String args[])
    {
    nullCheck(null);
    }
    public static void nullCheck(String s)
    {
    System.out.println(“string”);
    }
    public static void nullCheck(Object s)
    {
    System.out.println(“object”);
    }

    }

    //output
    String

    can anyone explain to me why out is String?

    1. om says:

      String is “More specifc” than object.Please read the above blog, this scenario is very beautifully explained.

    2. reddy says:

      string is more specific than object that’s y it will be print the ‘string’

    3. Ankita says:

      in method overloading first preference is given to the child class.
      as String is child class of object and they are related(parent –>child)
      hence method with string parameter will be executed.

  3. Logan says:

    public static void main(String[] args) {
    method(null);
    }

    public static void method(Object o) {
    System.out.println(“Object impl”);
    }

    public static void method(int s) {
    System.out.println(“Integer impl”);
    }

    public static void method(String s) {
    System.out.println(“String impl”);
    }

    could you explain to my Why the System print “String impl”. I couldn’t no understand it. I am sorry ab this silly question. bcoz im noob on java.
    Many thank.

    1. Sabeer Abdul Khadir Kutty says:

      The method with String argument is taking precedence over the method with int argument is because of the primitive nature of int. If you decalre a method with the wrapper class pointed, then it will show you the same error with ambiguity.

      1. Yubraj Subedi says:

        This is not about taking the precedence by String over int.
        It is clearly stated that there are three methods –
        with Object argument, with String argument and with int argument… and the value that is passed from main method is null which is of type ‘Object’. Since the type is Object, the overloaded method with int argument automatically disqualifies and the contest is now in between method with Object argument and String argument. Now, since the String is the more specific that the available Object argument/parameter, it qualifies for the execution.
        Thanks!

    2. krishna says:

      you should put value in
      method(null);
      method(0);
      method(” “);
      i think u clearly know about opp’s Rule

  4. Harsh Rasogi says:

    public class HelloWorld {
    public static void main(String args[]){
    boolean a = false;

    if(a=true){
    System.out.println(“a is true”);
    }else{
    System.out.println(“a is false”);
    }
    }
    }
    No one can prove this is an incorrect question. In the if part you are first assigning a is to true & then the if condition will be examined & it is found true.

    1. Suraj Vishwakarma says:

      ye the output of this program is true

      public class conditionalstate
      {
      public static void main(String args[])
      {
      boolean a = false; //without any change

      if(a=true)
      {
      System.out.println(“a is true”);
      }
      else
      {
      System.out.println(“a is false”);
      }
      }
      }
      o/p
      a is true

      1. Bishnu says:

        “a=true” is an assignment operation and not a relational operator. “a=true”, would return the value as true. Hence, you are getting a is true.

  5. suresh says:

    2 problem, compile time error..if(a==true), but u made it only =

  6. Karam says:

    In my interview with Chetu India, there was one simple question which made me think twice:

    public class HelloWorld {
    public static void main(String args[]){
    boolean a = false;

    if(a=true){
    System.out.println("a is true");
    }else{
    System.out.println("a is false");
    }
    }
    }


    So, i hope this would help someone.

    1. Nagendra Varma Mudunuri says:

      you can’t assign a null object to boolean first of all. You used if(a=null) supposed to be if(a==null)

      1. Ajit sharma says:

        It will print “a is true” because while jvm comes to if condition it will return true value so when if condition is true go to inside if block and print.

    2. Narayan Choudhary says:

      if(a=true) is wrong statement ,so it will give error ,

      if(a==true) should be there..

      1. Ponsuyambu says:

        if(a=true) ==>> a = true; if(a)

        So a is true will be printed

      2. Sudhansu says:

        Thats no a “wrong statement”. true gets assigned, and the if block will get executed!!

      3. Avani says:

        it will not through any error it will simply run and print true.

    3. farman says:

      a=true
      a assign value =true in variable a
      answer is a is true

  7. Karam says:

    Answer to question 1 is wrong. Kindly correct.

    public class NullArgumentTest {

    public static void main(String[] args) {
    method(null);
    }

    public static void method(Object o){
    System.out.println(“Object imple”+o);
    System.out.println(“test”);

    }

    public static void method(String s){
    System.out.println(“object impl”+ s);
    }

    }

    /*****Output*******/
    object implnull

    So, Kindly reply.

    1. Pankaj says:

      What’s wrong there, your output is same as mine.

    2. Robin says:

      Your method is wrong as you are printing Object impl in case of string also.

      public static void method(String s){
      System.out.println(“object impl”+ s);
      }

      1. Anshul says:

        lol 😛

        that guy a noob 😛

      2. Ankit says:

        hi is printing
        (“object impl”+ s) and (“object imple”+ s)
        in case of object he is printing 2 statements

  8. Shiva says:

    Crystal Clear Explanation! but in the second case you converted the value to boolean, how can we achieve it in a min, any shortcuts?

  9. Manjunath says:

    Nice explaination 🙂

  10. Rishi Raj says:

    Great share. Thanks a lot!
    My score: 1/2. I could not answer Long prob right.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages