Expressions, Statements, and Blocks

Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks.

Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

Examples for expressions:

int cadence = 0;
int result = 1 + 2; 
System.out.println("You are " + age + " years old");

Characteristics of expressions:

  • The data type of the value returned by an expression depends on the elements used in the expression.

  • compound expressions can be constructed from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other

  • specify exactly how an expression will be evaluated using balanced parenthesis: "(" and ")".

  • If no explicit order for the operations to be performed is given, the order is determined by the precedence assigned to the operators in use within the expression.

Statements

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. There are three types of statements:

Expression statements

Expression statements can be made into a statement by terminating the expression with a semicolon (;):

aValue = 8933.234; // assignment statement
aValue++; // increment statement
System.out.println("Hello World!"); // method invocation statement

Declaration statements

A declaration statement declares a variable:

int number = 2;

Control flow statements

Control flow statements regulate the order in which statements get executed:

if(condition){
  Statement(s);
}

Blocks

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed:

boolean condition = true;
if (condition) { // begin block 1
    System.out.println("Condition is true.");
} // end block 1
else { // begin block 2
    System.out.println("Condition is false.");
} // end block 2

Source:

results matching ""

    No results matching ""