Vidyalelo
Java Programming · Q40

Operators

Programming · Java Programming · question 40

Q40

Determine output: public class Test public static void main(String... args) int a=5 , b=6, c=7; System.out.println("Value is "+ b + c); System.out.println(a + b + c); System.out.println("String " + (b+c));

A.
Value is 67 18 String 13
Answer
B.
Value is 13 18 String 13
C.
Value is 13 18 String
D.
Compilation fails
E.
None of these

Answer: Option A

Solution

Answer: Option A
Solution:
Let's break down this Java code step-by-step to understand the output:
First, understand Operator Precedence : In Java, the "+" operator can mean addition (for numbers) or concatenation (joining strings). The order it's processed matters.
Line 1: `System.out.println("Value is "+ b + c);`
The Java compiler reads this expression from left to right.
It first sees `"Value is " + b`. Because `"Value is "` is a String, the `+` operator acts as String concatenation.
So, `b` (which is 6) is converted to a String and appended to `"Value is "`, resulting in `"Value is 6"`.
Next, it sees `"Value is 6" + c`. Again, because `"Value is 6"` is a String, `c` (which is 7) is converted to a String and appended.
The final result of this line is `"Value is 67"`, which is then printed to the console.
Line 2: `System.out.println(a + b + c);`
Here, `a`, `b`, and `c` are all integers (numbers).
Therefore, the `+` operator performs addition.
So, `5 + 6 + 7` is calculated, resulting in `18`.
This value (`18`) is then printed to the console.
Line 3: `System.out.println("String " + (b+c));`
Here we have `"String "` which is a String followed by `(b+c)` inside parenthesis.
The parentheses `()` force the expression inside to be evaluated first.
So `b + c` is computed which is `6 + 7 = 13`.
Then `"String " + 13`. Since `"String "` is a String, the `+` operator concatenates the String `"String "` with the number `13`.
This results in the String `"String 13"` which is then printed to the console.
Therefore, the correct output is:
Value is 67
18
String 13
So, the correct answer is Option A: Value is 67 18 String 13