Java Reference
In-Depth Information
Expressions
Thepreviouslydeclaredvariableswerenotexplicitlyinitializedtoanyvalues.Asares-
ult,theyareeitherinitializedtodefaultvalues(e.g.,0for
int
and0.0for
double
)or
remainuninitialized,dependinguponthecontextsinwhichtheyappear(declaredwithin
classes or declared within methods).
Chapter 2
discusses variable contexts in terms of
fields, local variables, and parameters.
Javaprovidestheexpressionsfeatureforinitializingvariablesandforotherpurposes.
An
expression
isacombinationofliterals,variablenames,methodcalls,andoperators.
Atruntime,itevaluatestoavaluewhosetypeisreferredtoastheexpression'stype.If
theexpressionisbeingassignedtoavariable,theexpression'stypemustagreewiththe
variable's type; otherwise, the compiler reports an error.
Java classifies expressions as simple expressions and compound expressions.
Simple Expressions
A
simple expression
isa
literal
(avalueexpressedverbatim),avariablename(contain-
ingavalue),oramethodcall(returningavalue).Javasupportsseveralkindsofliterals:
string, Boolean
true
and
false
, character, integer, floating-point, and
null
.
Note
A method call that doesn't return a value—the called method is known
as a
void method
—is a special kind of simple expression; for example,
Sys-
tem.out.println("hello, world!");
. This standalone expression cannot
be assigned to a variable. Attempting to do so (as in
int
i
=
Sys-
tem.out.println("x");
) causes the compiler to report an error.
A
string literal
consistsofasequenceofUnicodecharacterssurroundedbyapairof
doublequotes;forexample,
"the quick brown fox jumps over the lazy
dog." It
mightalsocontain
escape sequences
,whicharespecialsyntaxforrepres-
entingcertainprintableandnonprintablecharactersthatotherwisecannotappearinthe
literal.Forexample,
"the quick brown \"fox\" jumps over the lazy
dog."
uses the
\"
escape sequence to surround
fox
with double quotes.
Table 1-2
describes all supported escape sequences.