Continuing reading Java Language Specification turned to section Compound Assignment Operators
Can you please predict the output of this program?
public class CompoundAssignmentOperators {
public static void main(String[] args) {
short s=10;
s+=10.6;
String ss="init";
Person person=new Person();
int k=10;
k += (k + 2) * (k = 4) ;
System.out.println(k);
s+=(s=10);
System.out.println(s);
ss+=ss=(ss=m1(ss) + (ss=m1(ss)));
person.firstName+=person.firstName=(person.firstName=m1(ss) +(person.firstName=m1(ss)));
System.out.println(person.firstName);
System.out.println(ss);
System.out.println(ss.toString());
}
static short getShort(short s) {
return 10;
}
static String m1(String ss) {
return "Come";
}
@Override
public String toString() {
return "toString called";
}
}
class Person {
String firstName="prashant";
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
It Prints:
58
30
prashantComeCome
initComeCome
initComeCome
If we closely read what JVM Specification states
"
At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:
First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
"
Hence the expression s+=(s=10); evaluates to 30 because all we do in the rightHand Side expression is stored in a temp variable only. :-)
Also this k += (k + 2) * (k = 4); evaluates to 58 as k=4 in just like any other temp variable hence it evaluates to k=10 + (12*4)=58.
Similarly other expressions are evaluated.Also System.out.println(ss.toString()); will print "initComeCome" because we are calling toString() method on builtin String class and we have overrided toString() method for CompoundAssignmentOperators class only but not for String class.
Always remember The evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.
Ex:
int k = 1;
k += (k = 4) * (k + 2);
When printed k it prints 25.
Hope this explanation helps.Any suggestions most welcomed.
Tuesday, 4 September 2007
Subscribe to:
Post Comments (Atom)
2 comments:
Hi. Nice blog.
But the error is present in this article.
In order it to correct necessarily:
String ss="init";
or
in output write
58
30
prashantComeCome
ComeCome
ComeCome
P.s. Sorry for my bad english.))
Thanks Edward Corrected my error.
Post a Comment