[course03] 01 Blocks and If Branches

Blocks

The block is the simplest type of structured statement. Its purpose is simply to group a sequence of statements into a single statement. The format of a block is:

{
     statements
}

Java is what is called a free-format language. There are no syntax rules about how the language has to be arranged on a page. So, for example, you could write an entire block on one line if you want. But as a matter of good programming style, you should lay out your program on the page in a way that will make its structure as clear as possible.

{
   System.out.print("The answer is ");
   System.out.println(ans);
}
  
 
{  // This block exchanges the values of x and y
   int temp;      // A temporary variable for use in this block.
   temp = x;      // Save a copy of the value of x in temp.
   x = y;         // Copy the value of y into x.
   y = temp;      // Copy the value of temp into y.
}

The Basic If Statement

An if statement tells the computer to take one of two alternative courses of action, depending on whether the value of a given boolean-valued expression is true or false.

or

exchanges the value of two variables, x and y, but only if x is greater than y to begin with.

an example of an if statement that includes an else part

examples:

Multiway Branching

example

Last updated

Was this helpful?