Java System.out.print – Printing Variable Values

javasemantics

Why does java print the value of the variable that is assigned it in the code below? I want understand what is happening here.

My thought is that the expression inside println() method is evaluated first. For the first example, 5 is assigned to int x. At that point, does x become available for the println() method to print its value?

This code confuses me. I wouldn't have thought expression like x=5 could return a value. Thank you.

Examples:

int x;
System.out.println(x=5); //prints 5

boolean isValid;
System.out.println(isValid = true); //prints true

String fruit;
System.out.println(fruit="Orange"); //prints orange

Best Answer

The parameter of of a method can be an expression.

System.out.println(x - y)

This works because x - y is an expression.

In most C like languages, the assignment operator is also part of an expression. For example in C# Why do assignment statements return a value? Eric Lippert points out the difference between a statement an an expression. An expression returns something. +, -, ! and so on - those operators return things. The = operator is no different in this respect, it returns something too.

That an assignment operator returns a value is idiomatic in C like languages. And while the original thoughts of why that was the case in C are lost, x = y is just as much of an expression as x - y is.

It turns out that x = 42 returns the value of 42 also. This is useful for side effects like x = y = z = 42 which is actually x = (y = (z = 42))). And here, z = 42 returns 42, which is then used in y = 42 and so forth.

You will also see the return value used in things such as:

while ((line = in.readLine()) != null) {
    processLine(++lineNo, line);
}

where the assignment to line is done and checked to see if it is not null.

This is perfectly idiomatic code for most languages that trace a linage back to C.

Further reading: Java Language Specification, section 15.26: Assignment Operators

Related Topic