56.5k views
0 votes
What is the output of the program segment below?

int var1 = 100;
String var2 = "100";
System.out.println(var1 + var1);
System.out.println(var2 + var1);
(A) 200
200
(B) 100100
100100
(C) 200
100100
(D) Error message

User Blgt
by
7.8k points

1 Answer

6 votes

Final answer:

The program prints '200' from adding two integers and '100100' from concatenating a String with an integer. Integer addition and String concatenation in Java produce different results based on operand types.

Step-by-step explanation:

The output of the program segment provided is as follows:

  • 200: This is the result of var1 + var1, since var1 is an integer, the addition operation sums the two values numerically.
  • 100100: This is the result of var2 + var1, since var2 is a String, the addition operation concatenates the integer to the string, resulting in a new String.

Therefore, the correct output is:

  1. 200
  2. 100100

As we can see, integer addition and String concatenation are two different operations in Java, and the type of the operands dictates which operation is performed. No error message is produced by this code segment.

User JianMing Wang
by
8.5k points