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";
}
}
[A].
9 7 7 foo 7 7foo
[B].
72 34 34 foo34 34foo
[C].
9 7 7 foo34 34foo
[D].
72 7 34 foo34 7foo
Answer: Option A
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.
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.
Anand H.R said:
(Tue, Jun 26, 2012 04:15:45 PM)
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...
Arjun said:
(Fri, Oct 19, 2012 12:15:23 AM)
Step1: s.o.p(""+7+2+""); this means adding with appending values 7+2=72 in this condition only.(Ans.72)
Step2: s.o.p(a+b) this means adding given values a=3,b=4 calculate a+b=7. (Ans.7)
Step3: s.o.p(""+a+b+""); this means adding with appending values 3+4=34 compare with step1.(Ans.34)
Step4: s.o.p(foo()+a+b+""); this means 1st applied to the foo() method. foo+3+4=foo34.(Ans.foo34).
Step5: s.o.p(a+b+foo()); this means adding to all values(only step5 values) ..3+4+foo=7foo(Ans.7foo)