Predict the output · Java
Integer Division and String Concatenation
Easy Predict the output Seen at Oracle, Infosys, Accenture
What are the five lines of output?
What does this print?
public class Main {
public static void main(String[] args) {
System.out.println(7 / 2);
System.out.println(7 / 2.0);
System.out.println('a' + 1);
System.out.println("" + 'a' + 1);
System.out.println(1 + 2 + "3" + 4 + 5);
}
}
3.5 3.5 b a1 3345
3 3.5 98 a1 3345
3 3.5 98 a1 12345
3 3 b 98 3345
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
3 3.5 98 a1 3345
7 / 2is integer division →3; onedoubleoperand makes it3.5.'a' + 1promotes the char toint(97) →98.- Once a
Stringappears,+concatenates:"" + 'a'→"a", then"a1". +is left-associative:1 + 2→3, then"33","334","3345".
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium