Originally posted by ishmayel vemuru:
class Feline
{
public static void main(String[] args)
{
Long x = 42L;
Long y = 44L;
System.out.print(" " + 7 + 2 + " "); // line---1
System.out.print(foo() + x + 5 + " "); //line--2
System.out.println(x + y + foo()); //line--3
}
static String foo() { return "foo"; }
}
Out Put:
72 foo425 86foo
Can any one explain the Concatination operator " + " at line 1, line 2 performing as a string concatination but at line 3 that is performing as addition operator...I'm confusing with this Please help me any one as early as possible.
Thanks in advance...
Ishmayel.
Hi Ishmayel
The sum at line 3 gives an output of "86foo" because all atomic operations of the same kind are resolved from left to right (unless there are brackets, which change resolving order). This means that in
x + y is resolved before all, and since there are NO String OPERANDS (being x and y Long), the jvm read the '+' operator as a sum and not as a concatenation. After "x + y" is evaluated (giving a result of 86), the second '+' sign is read as a concatenation because method foo() returns the String operand needed for the jvm to behave this way and so the output is "86foo". The above code is equal to:
For the first 2 System.out.print(), all the '+' signs are read as concatenation operators because there is a String operand since the first atomic operation (" " and foo()), so they can be interpreted as:
Hope this helps
Regards
LR