Statements, Expressions and Code Blocks

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 variablesoperators 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 –

Statements

A statement is a unit of execution. It is usually a collection of expressions and declarations. The following are common statement types –

  1. Declaration statement – inform the compiler and runtime about name and type of a variable
  2. Control flow statement – decision control structures
  3. Expression statements such as assignment
  4. Method invocation
  5. 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.

Leave a comment

Your email address will not be published.