Tutorial

Java Tricky Interview Questions

Published on August 3, 2022
author

Pankaj

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 23, 2013

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

- Rishi Raj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 29, 2014

    Nice explaination :)

    - Manjunath

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 30, 2014

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

      - Shiva

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 1, 2014

        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.

        - Karam

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 1, 2014

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

        - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 12, 2014

          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); }

          - Robin

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 1, 2014

            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.

            - Karam

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 30, 2014

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

            - Nagendra Varma Mudunuri

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 27, 2015

              if(a=true) is wrong statement ,so it will give error , if(a==true) should be there…

              - Narayan Choudhary

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 25, 2015

                good

                - abc

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 7, 2018

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

                  - farman

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 31, 2014

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

                    - suresh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      March 30, 2015

                      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.

                      - Harsh Rasogi

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 9, 2017

                      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

                      - Suraj Vishwakarma

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        April 14, 2015

                        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.

                        - Logan

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        April 14, 2015

                        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.

                        - Sabeer Abdul Khadir Kutty

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 31, 2018

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

                          - krishna

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            March 2, 2017

                            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?

                            - Rajesh pawar

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            September 25, 2017

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

                            - om

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              July 14, 2018

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

                              - reddy

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                October 23, 2018

                                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.

                                - Ankita

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  May 1, 2020

                                  Null is valid for both string and object. But string is the child class of object. So if the work is being completed at child level then it is not required to for parent level… that’s why here string will dominant on object.

                                  - Rakesh

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    December 4, 2018

                                    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

                                    - Chuck

                                      Try DigitalOcean for free

                                      Click below to sign up and get $200 of credit to try our products over 60 days!

                                      Sign up

                                      Join the Tech Talk
                                      Success! Thank you! Please check your email for further details.

                                      Please complete your information!

                                      Congratulations on unlocking the whale ambience easter egg!

                                      Click the whale button in the bottom left of your screen to toggle some ambient whale noises while you read.

                                      Thank you to the Glacier Bay National Park & Preserve and Merrick079 for the sounds behind this easter egg.

                                      Interested in whales, protecting them, and their connection to helping prevent climate change? We recommend checking out the Whale and Dolphin Conservation.

                                      Become a contributor for community

                                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                      DigitalOcean Documentation

                                      Full documentation for every DigitalOcean product.

                                      Resources for startups and SMBs

                                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                      Get our newsletter

                                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                      New accounts only. By submitting your email you agree to our Privacy Policy

                                      The developer cloud

                                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                      Get started for free

                                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                      *This promotional offer applies to new accounts only.