nerdexam
Oracle

1Z0-819 · Question #157

Given: public class Tester { public static void main(String[] args) { int x = 4; int y = 2; System.out.println("x+y=" + (x+y)); } } What is the result?

The correct answer is B. x+y=6. Option B is correct because (x+y) is wrapped in parentheses, forcing arithmetic addition first - 4 + 2 = 6 - and the result 6 is then concatenated with the string "x+y=", producing x+y=6. Why the distractors fail: C (x+y=42) is the classic trap: without parentheses, Java would…

Working with Java Data Types

Question

Given: public class Tester { public static void main(String[] args) { int x = 4; int y = 2; System.out.println("x+y=" + (x+y)); } } What is the result?

Options

  • AAn exception is thrown at runtime.
  • Bx+y=6
  • Cx+y=42
  • Dx+y=x+y

How the community answered

(41 responses)
  • A
    12% (5)
  • B
    78% (32)
  • C
    2% (1)
  • D
    7% (3)

Explanation

Option B is correct because (x+y) is wrapped in parentheses, forcing arithmetic addition first - 4 + 2 = 6 - and the result 6 is then concatenated with the string "x+y=", producing x+y=6.

Why the distractors fail:

  • C (x+y=42) is the classic trap: without parentheses, Java would concatenate left-to-right, treating 4 and 2 as strings and producing "x+y=42" - but the parentheses prevent this.
  • D (x+y=x+y) would only occur if x and y were literal strings rather than int variables; since they are integers, their values are used.
  • A (exception) is wrong because this is valid, compilable Java with no runtime errors.

Memory tip: In Java string concatenation, parentheses = math first. Think of it as the compiler doing the arithmetic homework inside the parentheses before joining it to the string.

Topics

#String concatenation#Operator precedence#Arithmetic operators#Type coercion

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice