top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Create Blocks of Code in Java

+2 votes
326 views

A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for Java’s if and for statements. Consider this if statement:

if(w < h) {
 v = w * h;
 w = 0;
}

Here, if w is less than h, both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block. Code blocks allow many algorithms to be implemented with greater clarity and efficiency.

Here is a program that uses a block of code to prevent a division by zero:

/* Demonstrate a block of code. Call this file BlockDemo.java. */
class BlockDemo {
  public static void main(String args[]) {
    double i, j, d;
    i = 5;
    j = 10;
    // the target of this if is a block
    if(i != 0) {
      System.out.println("i does not equal zero");
      d = j / i;
      System.out.print("j / i is " + d);
    }
    //The target of the if is this entire block.
  }
}


The output generated by this program is shown here:

i does not equal zero
j / i is 2.0


In this case, the target of the if statement is a block of code and not just a single statement. If the condition controlling the if is true (as it is in this case), the three statements inside the block will be executed. Try setting i to zero and observe the result.

References

Book: Java : A Beginner’s Guide by Herbert Schildt
posted Jan 12, 2016 by Kavana Gowda

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...