Expressions, statements and code blocks are the basic constituents of a Java program. Expressions, statements and code blocks are used to define program’s execution flow.
Expressions
An expression is a syntactically valid combination of variables, operators and methods which on a left to right evaluation condenses to a single value. Pretty dense, right? Actually, it’s simpler than it sounds. An expression is a piece of code that at runtime will turn into a single value. Consider these examples of expressions –
1 2 3 4 5 6 7 8 9 10 11 12 13 | int politicianCode = 210 * 2; // 210 * 2 is an expression, evaluates to, well, 420 System.out.println ("Those who were left behind in evolutionary race became " + " politicians."); // The expression here is // "Those who were left behind in evolutionary race became " + " politicians." // Because it evaluates to // "Those who were left behind in evolutionary race became politicians." |
Statements
A statement is a unit of execution. It is usually a collection of expressions and declarations. The following are common statement types –
- Declaration statement – inform the compiler and runtime about name and type of a variable
- Control flow statement – decision control structures
- Expression statements such as assignment
- Method invocation
- Object creation
Code Blocks
A block is a group of zero or more statements that are contained with in braces – { and }. In Java, you can use a code block wherever a statement is permitted. A code block is also a scope structure. Variables declared inside a code block cannot be accessed outside the block. Thus a code block governs the life span of variables. Consider the code below
12345678910111213141516 | // consider following code in a method in Politician class if (electionsApproaching) { // beginning a code block int amount = 100; appearFriendly(); reduceTaxes(); donate(amount); } // marks the end of code blockelse { // another code block cheatPeople(); take(amount); // ERROR: amount is not visible here } |
Here the variable amount declared in if block is not visible in else block. All looping constructs, conditional statements, class and method declarations introduce their respective code blocks.