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.

 

Try out the above statements in the interactions pane. Example:

> int x;  //declare a variable x of type integer
> x = 5   // this is an expression. 5 is assigned to x.
5         // when DrJava is given an expression, it prints the expression's value
> x = 6;  // this is a statement
          // DrJava assigned 6 to x but didn't print 6 because it was given a 
          // statement (that was not a print statement)
> System.out.println(x);  //Is print statement, which prints the value of variable x
6
> x       //This is shortcut (only in interactions pane) to view the value of x
6

Default Values

Variables in Dr Java Interactions pane 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'

However, when writing Java programs this may not be the case and hence it is always a good practice to intialize variables before their use.