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.
Anand H.R said:
1 decade ago
Sytem.out.print(foo()+a+b+"");- in this first it will evaluated from left to right so function will return string , if any thing add with string it will be string only so the answer is foo34.
System.out.print(a+b+foo());- in this it will be evalueated from left to right and fist it will add a and b both are int type and intermediat result is 7 so then this 7 append with string foo.
hope now u got...
System.out.print(a+b+foo());- in this it will be evalueated from left to right and fist it will add a and b both are int type and intermediat result is 7 so then this 7 append with string foo.
hope now u got...
Arun kumar said:
1 decade ago
I didn't get why its giving different answers. Any one please explain me.
System.out.print (foo () + a + b + " ") ;
System.out.println (a + b + foo () ) ;
Ans : foo34 7 foo.
System.out.print (foo () + a + b + " ") ;
System.out.println (a + b + foo () ) ;
Ans : foo34 7 foo.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers