Javatpoint Logo
Javatpoint Logo

Java Tricky Programs | Tricky Java Interview Questions

Tricky Java interview questions are those questions that require some extra efforts to solve the questions. If we try to answer a tricky question with common sense, we will fail because they require some specific knowledge. Most of the tricky Java questions come from confusing concepts like loop, multithreading, overloading, overriding, etc.

Sometimes we get puzzled in solving the questions while the question is not much difficult. Sometimes we write code in haphazard way while the solution to the question is very easy.

We can solve the question by using our analytical thinking even if we do not know the answer. In this section, we will cover some tricky Java programs and tricky interview questions.

1) Consider the following code and guess the output.

  1. Hello
  2. hello
  3. HELLO
  4. Error
  5. \u000dhello

Answer: b

Explanation: As we see the print statement it seems that the statement is commented but not so. // \u000d is a new line Unicode character.


2) Consider the following code and guess the output.

  1. 77
  2. 33
  3. 27
  4. 76
  5. 66

Answer: a

Explanation: In the program, the operators are just for puzzle someone. The operators are neither pre or post increment. The statement can be written and solved as follows:

int i=20+ (+9)- (-12)+ (+4)- (-13)+ (+19);

i=20+9+12+4+13+19

i=77


3) Consider the following code and find the output.

  1. true is printed out exactly once.
  2. true is printed out exactly twice.
  3. true is printed out exactly three times.
  4. true is printed out exactly four times.
  5. The code does not compile.

Answer: c

Explanation: Because String literals are used from the string pool. It means that s1 and s2 refer to the same object and are equal. Therefore, the first two print statements print true. The third print statement prints false because the toString() method uses a method to compute the value and it is not from the string pool. The final print statement again prints true because equals() looks at the values of String objects.


4) What is the output of the following code snippet?

  1. abe
  2. abce
  3. abde
  4. abcde
  5. An uncaught exception is thrown.

Answer: d

Explanation: Because the code starts running and prints a and b on lines 13 and 15. Line 16 throws an exception, which is caught on line 17. After line 18 prints c, the finally block is run and d is printed. Then the try statement ends and e is printed on line 22.


5) What will be the output of the following code and why?

  1. Compiler error at line 1.
  2. Compiler error at line 2.
  3. Compiler error at line 4.
  4. Compiler error at line 5.
  5. Compiler error at line 8.

Answer: e

Explanation: The local variables require assignment before referencing them. Option E is incorrect because class and instance variables have default values and allow referencing. a_b defaults to a null value. Options A, B, C, and D are incorrect because identifiers may begin with a letter, underscore, or dollar sign. If a_b was an instance variable, the code would compile and output 0null.


6) What will be the output of the following code and why?

  1. [8]
  2. [9]
  3. Something like [Ljava.lang.String;@160bc7c0
  4. An exception is thrown.
  5. The code does not compile.

Answer: b

Explanation: The array is allowed to use an anonymous initializer because it is in the same line as the declaration. The ArrayList uses the diamond operator allowed since Java 7. It specifies the type matches the one on the left without having to re-type it. After adding the two elements, list contains [6, 8]. We replace the element at index 1 with 9, resulting in [6, 9]. Finally, we remove the element at index 0, leaving [9]. Option C is incorrect because arrays output something like that rather than an ArrayList.


7) What will be the output of the following code and why?

  1. true true
  2. true false
  3. false true
  4. false false
  5. Compilation fails

Answer: e

Explanation: The Unicode declaration must be enclosed in single quotes: '\u004e'.


8) What will be the output of the following code and why?

  1. Output of Memory Error
  2. Stack Overflow Error
  3. Orphaned Case Error
  4. Assertion Error
  5. IO Error

Answer: c

Explanation: Because Java does not allow us to compare values in the case statements. An error occurred due to invalid switch statement is called Orphaned case error.


9) What will be the output?

  1. ONE3TWOTHREE7FOURFIVE5
  2. ONE12TWOTHREE7FOURFIVE5
  3. ONE3TWOTHREE34FOURFIVE5
  4. ONETWOTHREEFOURFIVE15
  5. ONE12TWOTHREE34FOURFIVE5

Answer: e

Explanation: Because the number defined is of type string, so they will not add together. Hence, the above code prints the same string as it is.


10) What will be the output?

  1. 0
  2. 0.0
  3. Null
  4. ArithmaticException
  5. Compilation Error

Answer: b

Explanation: In the Integer class, the MIN_VALUE is negative (i.e. -231), both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2-1074, a double constant whose magnitude is the least among all double values.

So, unlike the noticeable answer, this program will print 0.0 because of Double.MIN_VALUE is greater than 0.


11) Evaluate the following two statements and find the output?

  1. 31536000000 and 1726327040
  2. 3.1536e10 and 1.72632704e9
  3. 31536000000L and 1726327040
  4. Compile Time Error
  5. Arithmetic Exception

Answer: a

Explanation: The calculation is simple. First statement having L at last that denotes the exact explicitly long value i.e. 31536000000. On the other hand, the second statement does not have L at last, so it gives a different value as a result. Because it treated as integer and evaluates result in integer. But the result goes beyond the boundary of the integer range. Hence, it starts truncating the value i.e. 1726327040. Therefore, the purpose of L is that it explicitly denotes the long value.


12) Consider the following code and evaluate the output?

  1. 1
  2. 2
  3. 1110
  4. 1109
  5. 11

Answer: b

Explanation: We know that the static block executed first. Therefore, the post decrement value of x will be 1111 and the pre decrement value will be 1109 and the difference between the values is 2 and the same will print on the console. Note that the block after the static block will never get executed.


13) Consider the following code and evaluate the output?

  1. Rock
  2. Scissors
  3. Paper
  4. Syntax Error
  5. Exception

Answer: d

Explanation: In the above program, the switch statement makes a random choice among three possible alternatives. Recall that the value of the expression (int)(3*Math.random()) is one of the integers 0, 1, or 2, selected at random with equal probability, so the switch statement below will assign one of the values "Rock", "Scissors", "Paper" to computerMove, with probability 1/3 for each case. Although the switch statement in this example is correct, this code segment as a whole illustrates a subtle syntax error.

We probably haven't spotted the error, since it's not an error from a human point of view. The computer reports the last line to be an error, because the variable computerMove might not have been assigned a value. In Java, it is only legal to use the value of a variable if a value has already been definitely assigned to that variable. It means that the computer must be able to prove, just from looking at the code when the program is compiled, that the variable must have been assigned a value. Unfortunately, the computer only has a few simple rules that it can apply to make the determination. In this case, it sees a switch statement in which the type of expression is int and in which the cases that are covered are 0, 1, and 2. For other values of the expression, computerMove is never assigned a value. So, the computer thinks computerMove might still be undefined after the switch statement. Now, in fact, this isn't true: 0, 1, and 2 are actually the only possible values of the expression (int)(3*Math.random()), but the computer is not smart enough to figure that out. The easiest way to fix the problem is to replace the case label case 2 with default.

The computer can see that a value is assigned to computerMove in all cases. More generally, we say that a value has been definitely assigned to a variable at a given point in a program if every execution path leading from the declaration of the variable to that point in the code includes an assignment to the variable. This rule takes into account loops and if statements as well as switch statements.


14) What will happen if we try to compile and run this?

  1. It will fail to compile
  2. Runtime error
  3. Compiles and runs with no output
  4. Compiles and runs printing Hello
  5. Error at line at 6

Answer: d

Explanation: The program will compile and run successfully. Does not matter the Test class is empty.


15) In double brace initialization what is the meaning of first and second pair of braces?

  1. The first set of brace creates a new anonymous inner class and the second set of brace creates an instance initializer like static block in class.
  2. The second set of brace creates a new anonymous inner class and the first set of brace creates an instance initializer like static block in class.
  3. Neither first set of brace creates a new anonymous inner class nor the second set of brace creates an instance initializer like static block in class.
  4. The use of double brace initialization is not allowed in Java.
  5. None of the above

Answer: a

Explanation: First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.

And Second set of braces are nothing but instance initializers. Recall the concept of core Java where we can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects we create.


16) Which of the following statement runs infinitely?

i. for( ; ; )
ii. for( ; true; )
iii. for( ; false; )
iv. for( ; 2==2; )
v. for(int i=1; i>=1; i++)

  1. Only i
  2. ii and v
  3. i, ii, and iii
  4. i, ii, iv, and v
  5. i, ii, iii, iv, and v

Answer: d

Explanation: The loops i, ii, iv, and v runs infinitely because the first for loop by default picks true value at condition place, the second for loop specifies that the condition is true, the fourth for loop compares the values and returns true, the fifth for loop also returns true at each iteration. Therefore, the for loop i, ii, iv, and v runs infinitely.


17) Consider the following program.

Select the correct output.

  1. Static Block-1, Static Block-2, Main Method
  2. Static Block-2, Static Block-1, Main Method
  3. Main Method, Static Block-1, Static Block-2
  4. Static Block-1, Main Method, Static Block-2
  5. Main Method, Static Block-2, Static Block-1

Answer: a

Explanation: If a Java program have both static blocks and main() method, in such a case all the static block will execute first then the main() method. Therefore, option A is correct.


18) Consider the following program.

What will be print on the console?

  1. [Java\\ Python\\ Hadoop]
  2. [Java|Python|Hadoop]
  3. [Java\\|Python\\|Hadoop]
  4. [Java, Python, Hadoop]

Answer: d

Explanation: The String.split() method splits the string with the specified delimiter (|). The following statement also does the same.


19) Consider the scenario.

If we put System.exit(0) on try or catch block in such a case Will finally block execute or not? Also specify the reason.

  1. It is an invalid situation.
  2. It skips the finally block.
  3. JVM exit with SecurityException and finally block will execute.
  4. JVM exit without SecurityException Exception and finally block will not execute.
  5. The finally block may or may not be executed.

Answer: e

Explanation: By Calling System.exit(0) in try or catch block, we can skip the finally block. System.exit(int) method can throw a SecurityException.

If System.exit(0) exits the JVM without throwing the exception then finally block will not execute. But, if System.exit(0) does throw SecurityException then finally block will be executed.


20) Which exception is thrown by the following Java program?

  1. ArrayIndexOutOfBoundsException
  2. ArrayStoreException
  3. NegativeArraySizeException
  4. NullPointerException
  5. ClassCastException

Answer: b

Explanation: ArrayStoreException is a runtime exception. Array must contain the same data type elements. It exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. In other words, if you want to store the integer Object in an Array of String you will get ArrayStoreException.





You may also like:


Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA