The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

Expressions, Statements, and Blocks

Variables and operators, which you met in the previous two sections, are basic building blocks of programs. You combine literals, variables, and operators to form expressions — segments of code that perform computations and return values. Certain expressions can be made into statements — complete units of execution. By grouping statements together with braces — { and } — you create blocks of code.

Expressions

Expressions perform the work of a program. Among other things, expressions are used to compute and to assign values to variables and to help control the execution flow of a program. The job of an expression is twofold: to perform the computation indicated by the elements of the expression and to return a value that is the result of the computation.


Definition:  An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value.

As discussed in the previous section, operators return a value, so the use of an operator is an expression. This partial listing of the MaxVariablesDemo (in a .java source file) program shows some of the program's expressions in boldface:

...
//other primitive types
char aChar = 'S';
boolean aBoolean = true;

//display them all
System.out.println("The largest byte value is "
                   + largestByte);
...

if (Character.isUpperCase(aChar)) {
    ...
}
Each expression performs an operation and returns a value, as shown in the following table.

Some Expressions from MaxVariablesDemo
Expression Action Value Returned
aChar = 'S' Assign the character 'S' to the character variable aChar The value of aChar after the assignment ('S')
"The largest byte value is " + largestByte Concatenate the string "The largest byte value is " and the value of largestByte converted to a string The resulting string: The largest byte value is 127
Character.isUpperCase(aChar) Call the method isUpperCase The return value of the method: true

The data type of the value returned by an expression depends on the elements used in the expression. The expression aChar = 'S' returns a character because the assignment operator returns a value of the same data type as its operands and aChar and 'S' are characters. As you see from the other expressions, an expression can return a boolean value, a string, and so on.

The Java programming language allows you to construct compound expressions and statements from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:

x * y * z
In this particular example, the order in which the expression is evaluated is unimportant because the results of multiplication is independent of order; the outcome is always the same, no matter what order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first:
x + y / 100     //ambiguous
You can specify exactly how you want an expression to be evaluated, using balanced parentheses — ( and ). For example, to make the previous expression unambiguous, you could write:
(x + y)/ 100    //unambiguous, recommended
If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent:
x + y / 100
x + (y / 100) //unambiguous, recommended
When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This pratice will make your code easier to read and to maintain.

The following table shows the precedence assigned to the operators in the Java platform. The operators in this table are listed in precedence order: The higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right. Assignment operators are evaluated right to left.

Operator Precedence
postfix operatorsexpr++ expr--
unary operators++expr --expr +expr -expr ~ !
multiplicative* / %
additive+ -
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
logical AND&&
logical OR||
conditional? :
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

Statements

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;): These kinds of statements are called expression statements. Here are some examples of expression statements:
aValue = 8933.234;                      //assignment statement
aValue++;                               //increment       "
System.out.println(aValue);             //method call     "
Integer integerObject = new Integer(4); //object creation "
In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. You've seen many examples of declaration statements.
double aValue = 8933.234;             //declaration statement
A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements. You’ll learn about control flow statements in the section Control Flow Statements (in the Learning the Java Language trail).

Blocks

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following listing shows two blocks from the MaxVariablesDemo (in a .java source file) program, each containing a single statement:
if (Character.isUpperCase(aChar)) {
    System.out.println("The character " + aChar
                       + " is upper case.");
} else {
    System.out.println("The character " + aChar
                       + " is lower case.");
}

Summary of Expressions, Statements, and Blocks

An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value. You can write compound expressions by combining expressions as long as the types required by all of the operators involved in the compound expression are correct. When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first.

If you choose not to use parentheses, then the Java platform evaluates the compound expression in the order dictated by operator precedence. The table in section Expressions, Statements, and Blocks (in the Learning the Java Language trail) shows the relative precedence assigned to the operators in the Java platform.

A statement forms a complete unit of execution and is terminated with a semicolon (;). There are three kinds of statements: expression statements, declaration statements, and control flow statements.

You can group zero or more statements together into a block with braces: { and }. Even though not required, we recommend using blocks with control flow statements even if only one statement is in the block.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.