Expressions and Statements

Overview


Why is it important to know about expressions and statements?
Because it helps us to:

Examples of Statements

For now, think of a statement as ending with a semicolon. Later we'll see that a statement can end with a block of code surrounded by curly braces.

Statements Notes
Variable Declaraion Statements:
	 int x;
	 double d;
	 char c;
	 boolean result;

	 

The behavior is that memory is allocated and a variable with a certain type is associated with the memory.

Assignment Statements:
x = 500; d = 20.49 + 30.5 * 24; c = 'X'; result = false;

The behavior is that the value on the right is assigned to the variable on the left.

NOTE: Assume we are using variables previously defined as above.

Combination
Declaration/Assignment
Statements:
int x = 500; double d = 20.49 + 30.5 * 24; char c = 'X'; boolean result = false;

Combining declaration and initialization in one statementis preferred over having two separate statements.

The behavior is the behavior of a declaration statement and an assignment statement.

Other Statements

We'll soon learn about other statements such as:

  • if statements, if-else statements
  • Loops: while loops, for loops, do-while loops
  • etc.

Examples of Expressions

Expression ValueComments
Examples of literals:
5
5 The value of a literal is itself.
300.5
300.5
true
true
'b'
'b'
Expressions with arithmetic operators:
	 5 + 2
	 
7  
	 5 + 2 * 3
	 
11 Why isn't it 21?
Because, as in algebra, multiplication and division have higher precedence than addition and multiplication. You can use parentheses to group operands as you like. For example, the value of the expression
      (5 + 2) * 3
is 21. Recommended: use parentheses for clarity. See the Operator Precedence Table on the Resources page.
	 5 - 2 - 3
	 
0 Why isn't it 6?
Because, as in algebra, the arithmetic operators are left associative. You can use parentheses if you wan them to be grouped differently. For example, the value of the expression
      5 - (2 - 3)
is 6. See the Operator Precedence Table on the Resources page.
	 x = 500
	 
500 The value of the expression is the value assigned.

 

Default Values

Instance variables that aren't assigned a value when they are declared are given a default value according to their type.
Type Default
Value
int
0
double
0.0
boolean
false
char
'\0'