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.
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.
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);
3) Consider the following code and find the output.
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?
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?
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?
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 . 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?
Explanation: The Unicode declaration must be enclosed in single quotes: '\u004e'.
8) What will be the output of the following code and why?
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?
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?
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?
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?
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?
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?
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?
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( ; ; )
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.
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?
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.
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?
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.