Search code examples
javaexpressionterminology

Java statements which are also expressions, please explain


Please help me interpret this sentence from a purely terminological point of view:

"Technically, because variable assignments can be used as values for further assignments or operations, they can be considered to be both statements and expressions."

What does technically mean? What is not technically? In case of

a = (b = 1);

What we know:

a = (b = 1); 

is statement.

(b = 1) 

is an expression.

Question 1:

is a = (b = 1); also an expression? Or it is only an expression when written like this a = (b = 1) without semi colon and used in another statement or expression?

Quesion 2:

Is (b = 1) also a statement (given it is an assignment)? Or every statement must end with ; ?

Question 3.

Is b an expression within (b = 1) Or it is just a variable?

Is 1 an expression within (b = 1) Or it is just a literal?

Is a an expression within a = (b = 1) Or it is just a variable?

Regardin Q3 some clarification:

I guess literals and variables can be expressions when they are on their own. For example in the statement:

a = 1;

1 is an expression.

But is it also true for 1 inside expression of the example statement:

a = (b = 1); 

Solution

  • An expression is anything which can be evaluated to a value, so a = (b = 1) is an expression (it is an assignment expression where the right-hand operand is another assignment expression).

    The code a = (b = 1); is a statement; note the semicolon ; at the end of it. Specifically, it is an expression statement. An expression statement is a statement formed by writing an expression followed by a semicolon. (Not every type of expression is allowed as an expression statement, for example 1 + 1; is not a valid statement.)

    So strictly speaking, the semicolon makes the two pieces of code different. But if we are not being formal then we could say that a = (b = 1) can be written either as an expression or a statement.

    To answer the rest of your questions about what is or isn't a statement or an expression, I suggest checking the Java Language Specification: