Java Programming Interview Questions

Filed Under: Interview Questions
Java Programming Interview Questions

Java Programming Interview Questions are always deciding factor in any Java interview. Recently I am taking a lot of interview for my organization. So I was in the search of some java programming interview questions that are a little bit tricky also.

Java Programming Interview Questions

Here I am providing some of the Java interview programs I found interesting and need a closer look to understand.

The explanation will be provided after the questions. Test your knowledge of java by trying to provide the answer to the below java interview test questions.

  1. Java Programming Interview Question 1

    What is the output of the below statements?

    
    String s1 = "abc";
    String s2 = "abc";
    System.out.println("s1 == s2 is:" + s1 == s2);
    
  2. Java Programming Interview Question 2

    What is the output of the below statements?

    
    String s3 = "JournalDev";
    int start = 1;
    char end = 5;
    System.out.println(start + end);
    System.out.println(s3.substring(start, end));
    
  3. Java Programming Interview Question 3

    What is the output of the below statements?

    
    HashSet shortSet = new HashSet();
    for (short i = 0; i < 100; i++) {
    	shortSet.add(i);
    	shortSet.remove(i - 1);
    }
    System.out.println(shortSet.size());
    
  4. Java Programming Interview Question 4

    What will be the boolean “flag” value to reach the finally block?

    
    try {
    	if (flag) {
    		while (true) {
    		}
    	} else {
    		System.exit(1);
    	}
    } finally {
    	System.out.println("In Finally");
    }
    
  5. Java Programming Interview Question 5

    What will be the output of the below statements?

    
    String str = null;
    String str1="abc";
    System.out.println(str1.equals("abc") | str.equals(null));
    
  6. Java Programming Interview Question 6

    What will be the output of the below statements?

    
    String x = "abc";
    String y = "abc";
    x.concat(y);
    System.out.print(x);
    
  7. Java Programming Interview Question 7

  8. What will be the output of below program?

    
    public class MathTest {
    
    	public void main(String[] args) {
    		
    		int x = 10*10-10;
    		
    		System.out.println(x);
    	}
    
    }
    
  9. Java Programming Interview Question 8

  10. What will be the output when below java program is compiled and executed?

    
    public class Test {
    
    	public static void main(String[] args) {
    		try {
    			throw new IOException("Hello");
    		}catch(IOException | Exception e) {
    			System.out.println(e.getMessage());
    		}
    	}
    }
    

Java Programming Interview Questions Answers

I hope you have looked into the above questions before looking at the answers and explanation.

  1. Java Programming Interview Question 1 Answer and Explanation

    The given statements output will be “false” because in java + operator precedence is more than == operator. So the given expression will be evaluated to “s1 == s2 is:abc” == “abc” i.e false.

  2. Java Programming Interview Question 2 Answer and Explanation

    The given statements output will be “ourn”. First character will be automatically type caste to int. After that since in java first character index is 0, so it will start from ‘o’ and print till ‘n’. Note that in String substring function it leaves the end index.

  3. Java Programming Interview Question 3 Answer and Explanation

    The size of the shortSet will be 100. Java Autoboxing feature has been introduced in JDK 5, so while adding the short to HashSet<Short> it will automatically convert it to Short object. Now “i-1” will be converted to an int while evaluation and after that it will autoboxed to Integer object but there is no Integer object in the HashSet, so it will not remove anything from the HashSet and finally its size will be 100.

  4. Java Programming Interview Question 4 Answer and Explanation

    The finally block will never be reached here. If flag will be TRUE, it will go into an infinite loop and if it’s false it’s exiting the JVM. So finally block will never be reached here.

  5. Java Programming Interview Question 5 Answer and Explanation

    The given print statement will throw java.lang.NullPointerException because while evaluating the OR logical operator it will first evaluate both the literals and since str is null, .equals() method will throw exception. Its always advisable to use short circuit logical operators i.e “||” and “&&” which evaluates the literals values from left and since the first literal will return true, it will skip the second literal evaluation.

  6. Java Programming Interview Question 6 Answer and Explanation

    The statements will print abc. Notice that x.concat(y); will create a new string but it’s not assigned to x, so value of x is not changed.

  7. Java Programming Interview Question 7 Answer and Explanation

    This is a tricky question, it looks like the test is about the order of execution of the mathematical operators and syntax of main method will get overlooked. It will produce Runtime error because main method is not static, something like below.

    
    pankaj:bin pankaj$ java MathTest
    Error: Main method is not static in class MathTest, please define the main method as:
       public static void main(String[] args)
    
  8. Java Programming Interview Question 8 Answer and Explanation

    No, it won’t print Hello. It will be a compile time error as The exception IOException is already caught by the alternative Exception.

I hope that the above scenarios will help a bit in understanding some of the java concepts. Please try these java programming interview questions before going to the solution and comment to let me know your score. 🙂

UPDATE: Head over to some more java coding interview questions.

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

You can check out more java programming interview questions at our GitHub Repository.

Comments

  1. Vaibhav says:

    Thanks For these good Questions

  2. Yugaank says:

    Hi,
    Nice questions.
    Just wanna add one thing to question 4,
    if you do something like-
    if (flag=1/0==1) {
    it will run the finally block.

  3. Nagaraju says:

    Thank you very much Pankaj., good Job.
    It will really helps lot.

  4. Anurag Singh says:

    this example helps me a lot.
    thank you for this nice post

  5. Hi, You have written a very nice article. I acquired good knowledge about Java. Keep it up! I will follow up your for future post.
    Could you explain the difference between Array and ArrayList in Java?

  6. Manqoba Ledwaba says:

    Hi pankaj,

    thank you do much for your work pankaj you are a star.

    have a great day

  7. uttam says:

    awesome tricky questions. post more. love to read all.

  8. Aafreen says:

    what I learned before is equals compares content and == compares reference. but how s1== s2 will give true.
    And operator precedence question is really smart. Thank yu fa sharing this.

  9. pooja says:

    Thanks Pankaj for such a wonderful site.
    I appreciate your hard work and dedication towards Java.

    It really helps number of students.

    Keep sharing:-)

    Good Job!!!

  10. Ashutosh says:

    score was 2 (:)

  11. Eswar says:

    String s3=”ab”+”c”;
    System.out.println(“3) s1 == s3 is: ” + (s1 == s3));

    Here it is true and it is direct concatenation.

    can you brief it in deatil??

    1. ss says:

      there is i didnt find s1

  12. Naveen says:

    Thanks for the questions.
    My score was 1/5 🙁

  13. Greg says:

    Your answer to question 2 is wrong. You forgot the first System.out.

  14. Lakshay says:

    What is the output of the below statements?

    1
    2
    3
    String s1 = “abc”;
    String s2 = “abc”;
    System.out.println(“s1 == s2 is:” + s1 == s2);

    This question will return true as they are pointing to the same memory location.

    1. Sharma says:

      Hi Lakshay,
      This will return true if we put s1==s2 in parentheses otherwise + will take priority over ==.

    2. Steve says:

      No, as explained as operator precedence puts “+” before “==” it will not evaulate as you believe. What will happen is first concatenation of “s1==s2 is:” to s1 which will first resolve to the string “s1==s2 is:abc” then it will evaluate the ==, thus it will follow:

      – “s1==s2 is:abc” == “abc”
      for for example, think of it like.
      str1 = “s1==s2” + “abc”; //s1==s2 is: abc”
      str2 = “abc”;

      str1 == str2 // false

      which is obviously falsw

      1. SQS says:

        Nice explanation Steve!

  15. krishna says:

    Tricky questions ….good work.

    if possible try to put some more questions related to Multi threading .

  16. Pawan Soni says:

    Excellent Set of Questions 🙂

  17. TIM says:

    I need more questions on strings like this….
    tq

  18. Yogesh says:

    Really nice set of questions. Thanks.

  19. Rishika says:

    Cool..

  20. Rishi Raj says:

    This is a very great share. I must appreciate!
    My score is: 2/5.
    I got Q.2 and Q.4 right, rest I could not make out.

    Thanks a lot for sharing.

    1. Pankaj says:

      thanks for appreciating it.

  21. sreenivas says:

    String s1 = “abc”;
    String s2 = “abc”;
    System.out.println(“s1 == s2 is:” + s1 == s2);

    the output for s1==s2 is false
    because if you use == it always meant for reference comparison only
    if you use s1.equals(s2) it gives true
    because .equals() method is always meant for content comparison

    String s3 = “JournalDev”;
    int start = 1;
    char end = 5;
    System.out.println(start + end);
    System.out.println(s3.substring(start, end));

    here output is
    6
    ourn

    because
    start+end in this start is int and end is char in this it selects max datatype coverts all into that type(widowning)
    if use string+something then it always converts into string type only.

    1. Rishi Raj says:

      Hi,

      Thanks for explanation, but do you mean “widening” in place of “widowning” as in:
      “start+end in this start is int and end is char in this it selects max datatype coverts all into that type(widowning)”?

    2. dumbAss says:

      the output for s1==s2 is not always fasle use the below code and check if it is
      String s1 = “abc”;
      String s2 = “abc”;
      System.out.println(s1 == s2);
      the output is true
      By now you have to agree that you have given wrong information , dont mislead people assuming u know everything. incorrect information is dangerous than no information.

      1. Pankaj says:

        Can you point out where I am saying that above will be false always. If you check the Question 1, it’s returning false because of operator precedence and it’s a trick question. In your example there is no + operator so it will return true because both the string objects are referring to the same object in the string pool.

        Please avoid providing comments like this without any base, if I have written something wrong point me out and I would be happy to correct it.

        1. Manivasagam.M says:

          well said Mr.pankaj :).Your explanation is too good for this question.

        2. ARVIND AGGARWAL says:

          Dear Pankaj,

          First of all, I appreciate your hard work for job-aspirants and professionals into JAVA world.
          I expect more clarification n explanation from your side on all Questions as I am a regular reader of your website.
          As I understand that U should add all string questions in ascending order then nobody will confuse like this.
          Please explain ques3 n 5 in more detail….so that it can be understandable.

          Regards
          Arvind

      2. Anurag says:

        String s1 = “abc”;
        String s2 = “abc”;
        System.out.println(“s1 == s2 is:” + s1 == s2);

        i wanna explain you in details…..

        here first happens like “s1==s2 is”+s1 ———-> “s1==s2 is:abc”

        then happens like “s1==s2 is:abc”==s2 ———->”s1==s2 is:abc”==”abc”

        so Answer is false. ( it is operator precedence )

      3. Raaju says:

        the output for s1==s2 is not always fasle use the below code and check if it is
        String s1 = “abc”;
        String s2 = “abc”;

        what answer explained by Sharma was correct, here one thing he is trying to explaining:the thing is:

        case 1:

        System.out.println(s1 == s2);
        the output is true

        Case 2:

        System.out.println(“some text” +s1 == s2);
        the output is false. because “+” operator is more precedence than the “==” opertaor.this case the meaning(+s1 == s2) completely changed.

  22. Ankit Jain says:

    Thanks for these questions they are really tricky.

    I want more questions like these please help me from where I can get them any site or link will be helpful.

    Thanks in Advance.

  23. oleg says:

    Test Question 4:
    “In Finally” will be reached if flag is null.

    Console:
    ===================
    In Finally

    Exception in thread “main” java.lang.NullPointerException
    at people.oleg.test.Test1.main(Test1.java:51)
    ===================

    public class Test1 {
    public static void main(String[] args)
    {
    Boolean flag = null;
    try {
    if (flag) {
    while (true) {
    }
    } else {
    System.exit(1);
    }
    } finally {
    System.out.println(“In Finally”);
    }
    }
    }

    Exception in thread “main” java.lang.NullPointerException
    at people.oleg.test.Test1.main(Test1.java:51)
    In Finally

    1. Pankaj says:

      I agree that your program will reach to Finally block but there is a huge difference between boolean and Boolean.

      As mentioned in the question:

      What will be the boolean “flag” value to reach the finally block?

      1. oleg says:

        Yes, I agree, there is a difference between “boolean” and “Boolean”.

        1. Vikash Singh says:

          Keep flag= true and It will go in infinite loop , At some point of time JVM will throw StackOverflowException then it will go in finally block

    2. Rishi Raj says:

      Hi,

      Thanks for sharing “third view”. It’s really helpful.
      Still I want to add my bit to it.

      In your example code, you have declare variable flag as a wrapper object:
      Boolean flag = null;

      Declaring it as a primitive (notice small ‘b’ in ‘boolean’):
      boolean flag = null;

      the program flow does not reach finally. It only throws exception. See below for code and exception:-
      Code:

      public class FlagFinallyNull {
      public static void main(String[] args) {
      boolean flag = null;
      try{
      if(flag){
      while(true){}
      }
      else{
      System.exit(1);
      }
      }
      finally{
      System.out.println(“finally”);
      }
      }
      }

      Exception in output:
      Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      Type mismatch: cannot convert from null to boolean

      at FlagFinallyNull.main(FlagFinallyNull.java:4)

    3. amar says:

      How could you use Boolean flag=null;

      did you write the program?

      Boolean flag=null; is not a valid statement. as boolean flag requires boolean type variable but its getting null type.

      and if u have done it..kindly explain

      1. Pankaj says:

        It’s a valid statement, check below code.


        Boolean flag = null;
        try {
        if (flag) {
        while (true) {
        }
        } else {
        System.exit(1);
        }
        } finally {
        System.out.println("In Finally");
        }

        Above code will produce following output.


        In Finally
        Exception in thread "main" java.lang.NullPointerException
        at Test.main(Test.java:19)

    4. nuthan says:

      value of flag needs to be “true”
      and within while put a break so that it doesnt go for infinite loop.

      static Boolean flag = true;

      public static void main(String[] args) {
      try {
      if (flag) {
      while (true) {
      break;
      }
      } else {
      System.exit(1);
      }
      } finally {
      System.out.println(“In Finally”);
      }
      }

      try this guys…..

  24. Adrian Redgers says:

    Q1 For me the interesting thing is not operator precedence but string comparison.
    So explicitly bracket the == in the last line:
    System.out.println(“s1 == s2 is: ” + (s1 == s2));
    and it will return:
    s1 == s2 is: true
    But replace
    String s2 = “abc”;
    with
    String s2 = “ab”;
    s2 = s2 + “c”;
    and it will return
    s1 == s2 is: false
    This is because Java optimizes by giving the strings it knows at compile time the same hash code, but is doesn’t know what s2 is at compile time – so the second “abc” string gets a different hash code.

    1. Pankaj says:

      I didn’t understood what are you trying to say here. Can you please post a sample program for better understanding?

      1. Adrian Redgers says:

        String s1 = “abc”;
        String s2 = “abc”;
        System.out.println(“1) s1 == s2 is: ” + (s1 == s2));
        s2 = “ab”;
        s2 = s2 + “c”;
        System.out.println(“2) s1 == s2 is: ” + (s1 == s2));

        Output:
        1) s1 == s2 is: true
        2) s1 == s2 is: false

        1. Pankaj says:

          Thanks for the code, actually in String direct concatenation, it always create new Strings, so the address are different and hence == returns false in second case.

          1. Amol says:

            yup that’s right but if you want to compare value’s then following is for you

            String a=”ab”;
            String b=”abc”;
            a+=”c”;
            System.out.println(a.equals(b)); //true
            System.out.println(a==b); //false

  25. Sandeep says:

    Really confusing for those who don’t pay attention to the language syntax and semantics.

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