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);
    }
}
  1. 3.5
    3.5
    b
    a1
    3345
  2. 3
    3.5
    98
    a1
    3345
  3. 3
    3.5
    98
    a1
    12345
  4. 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 / 2 is integer division → 3; one double operand makes it 3.5.
  • 'a' + 1 promotes the char to int (97) → 98.
  • Once a String appears, + concatenates: "" + 'a' → "a", then "a1".
  • + is left-associative: 1 + 2 → 3, then "33", "334", "3345".