mike
mike

Reputation: 5055

How are chained assignments in java defined? Is there a difference between value and reference types?

How are chained assignments in java defined, considering following points:

E.g.

Integer a, b = new Integer(4);

In JLS 15.26 Assignment Operators it says

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

So a == b should be true.

Is there a way to achieve

Integer a = new Integer(4)
Integer b = new Integer(4)

in one line so that a != b, since a and b are different objects.

Additional Info

The question is already answered, but I felt it was not clear enough, so here some code to clarify it.

Integer a = null, b = null, c = null;
System.out.println(a + " " + b + " " + c); // null null null
a = b = c = new Integer(5); // <-- chained assignment
System.out.println(a + " " + b + " " + c); // 5 5 5
System.out.println(a.equals(b)); // true
System.out.println(b.equals(c)); // true
System.out.println(a == b); // true
System.out.println(b == c); // true

Upvotes: 1

Views: 2877

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500505

Sure:

Integer a = new Integer(4), b = new Integer(4);

Personally I think that's less readable than using two separate declarations though, and there's no way of doing it without either repeating the new Integer(4) or extracting that to some other method which you then call twice.

Upvotes: 2

Related Questions