https://www.math.uni-hamburg.de/doc/java/tutorial/java/nutsandbolts/expressions.html
Expression
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. You've already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2) System.out.println("value1 == value2");
Each expression performs an operation and returns a value, as shown in the following table.
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 |
compound expression:
1 * 2 * 3
x + y / 100 // ambiguous
(x + y) / 100 // unambiguous, recommended
x + (y / 100) // unambiguous, recommended
Statement
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.- Expression Statement: statement forms a complete unit of execution (expression + ';').
// assignment statement aValue = 8933.234; // increment statement aValue++; // method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myBike = new Bicycle();
- Declaration statement: declares a variable.
double aValue = 8933.234;
- Control flow statements regulate the order in which statements get executed
- decision-making statements (
if-then
,if-then-else
,switch
), - the looping statements (
for
,while
,do-while
), - the branching statements (
break
,continue
,return
)
Block
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } }
Quiz:
- Operators may be used in building expressions, which compute values.
- Expressions are the core components of statements.
- Statements may be grouped into blocks.
- The following code snippet is an example of a compound expression.
1 * 2 * 3- Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a semicolon.
- A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
No comments:
Post a Comment