Java Programming - Operators and Assignments - Discussion
Discussion Forum : Operators and Assignments - Finding the output (Q.No. 11)
11.
What will be the output of the program?
class SC2
{
public static void main(String [] args)
{
SC2 s = new SC2();
s.start();
}
void start()
{
int a = 3;
int b = 4;
System.out.print(" " + 7 + 2 + " ");
System.out.print(a + b);
System.out.print(" " + a + b + " ");
System.out.print(foo() + a + b + " ");
System.out.println(a + b + foo());
}
String foo()
{
return "foo";
}
}
Answer: Option
Explanation:
Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands.
Discussion:
12 comments Page 2 of 2.
Ganesh said:
7 years ago
Thanks all for explaining.
Naveen said:
3 years ago
@Naveen_bobby_ak.
Step1: " "+7+2+" " it's String Type not int o/t: 72
Step2: (a+b)=3+4=7 it's int type so addition o/t: 7.
Step3: " "+a+b+" " It's String Type (left to right)
" "+3+4+" " o/t: 34,
Step4: foo()+a+b+" " foo() method is String Type
foo+3+4+" " o/t: foo34.
Step5: a+b+foo() a+b is a integer type so addition will be performed (left to right)
o/t: 7foo.
Finally o/t: 72 7 34 foo34 7foo.
Step1: " "+7+2+" " it's String Type not int o/t: 72
Step2: (a+b)=3+4=7 it's int type so addition o/t: 7.
Step3: " "+a+b+" " It's String Type (left to right)
" "+3+4+" " o/t: 34,
Step4: foo()+a+b+" " foo() method is String Type
foo+3+4+" " o/t: foo34.
Step5: a+b+foo() a+b is a integer type so addition will be performed (left to right)
o/t: 7foo.
Finally o/t: 72 7 34 foo34 7foo.
(2)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers