What's the significant difference between Expressions vs Literals && Expressions vs Statements in Java? I'm aware that an expression represents a simple value or a set of operations that produces a value. However, literals can also be a simple value which makes it a little confusing to make difference between them. Could smb explain the differences? Thanks in advance!
Asked
Active
Viewed 1,871 times
2
-
3Any literal is an expression, but not every expression is a literal (e.g. `x+2` is an expression, where `x` is a variable, but not a literal. `123` is an integer literal, and also an expression (a very simple one). But I do not see the relation to statements in your question. – anol Mar 18 '15 at 18:51
-
But what is the difference between statements and expressions ?@anol – Shohin Mar 18 '15 at 18:56
-
Statements don't evaluate to values. `for` and `if/else` are statements, for example. – GriffeyDog Mar 18 '15 at 19:16
-
Some confusion may come from the fact that in some languages, some kinds of statements may return values (e.g. `i++` in C/Java). Anyway, [this question](http://stackoverflow.com/questions/19132/expression-versus-statement) explains the difference between statements and expressions, and there are several similar questions in Stack Overflow. – anol Mar 18 '15 at 23:10
1 Answers
2
A literal is a notation for representing a fixed value in source code. For example: 'a'
, "a"
, Object.class
, and 1
are all literals. Their value is known at compile-time, and they are expressions, since they evaluate to a single value.
Statements are complete units of execution. Most statements terminate with a semicolon. For example: new Object();
is a statement, while new Object()
is an expression that returns a reference to a newly created object. Examples of statements that don't terminate with a semicolon are blocks and control flow statements.

Giulio Meneghin
- 96
- 3
-
None of the examples you've given of statements that end with a semicolon is a 'unit of execution' at all, as they aren't executed. – user207421 Mar 18 '15 at 21:38
-
You are right. I edited the answer, but didn't elaborate further since the question posted in anol's comment has a quite comprehensive answer already. – Giulio Meneghin Mar 24 '15 at 17:00