Block of code in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Wednesday, October 24, 2018

Block of code in Java

Block of code in Java

Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between the open and closed curly braces.

  • Every block of code in Java start with open curly brace { and ends with close curly brace }.
  • There is no limit of statement inside the block of code.
  • There is no restriction on the number of blocks inside a block and level of nesting the block, means blocks can be nested and can be included inside any other block.
  • Block of code in Java is commonly used in if statement, for loop, and while loop.
  • All classes and methods contents are inside the blocks.
  • Indent Java code inside the block of code, so it will help in resolving the compile time errors faster and make the code more readable.

For example, a block can be java's if and for statements.

Consider the block of if statement:

if (x < y) {
  int temp = x;
  x = y;
  y = temp;
}

Here, if x is less than y then statements inside the curly braces (block of code) will be executed. Mostly in real time application, you will write block of code. It creates logical unit, and one statement can't execute without the other statement also executing.

Consider the block of for loop:

for (x = 10, y = 20; x < y; x++) {
  System.out.println("Value of x in for loop:: " + x);
  System.out.println("Value of y in for loop:: " + y);
  y = y - 2;
}

Here, x, and y are loop control variable in initialisation portion of for loop. You can declare and initialise multiple loop control variables by comma-separated.

/*
Demonstrate the block of code.
Call this file as BlockOfCodeDemo.java
compile: javac BlockOfCodeDemo.java
Run: java BlockOfCodeDemo
 */
public class BlockOfCodeDemo {
  public static void main(String[] args) {
    int x, y;
    x = 10;
    y = 20;
    // block of if statement:
    // swap the value of x and y
    if (x < y) {
      int temp = x;
      x = y;
      y = temp;
    }
    System.out.println("Value of x:: " + x);
    System.out.println("Value of y:: " + y);

    // block of for statement:
    // Value of x is increased by 1 and value of y is decreased by 2
    // in every loop iteration
    for (x = 10, y = 20; x < y; x++) {
      System.out.println("Value of x in for loop:: " + x);
      System.out.println("Value of y in for loop:: " + y);
      y = y - 2;
    }
  }
}

When you run this program. output of this program shown below.

Value of x:: 20
Value of y:: 10
Value of x in for loop:: 10
Value of y in for loop:: 20
Value of x in for loop:: 11
Value of y in for loop:: 18
Value of x in for loop:: 12
Value of y in for loop:: 16
Value of x in for loop:: 13
Value of y in for loop:: 14

No comments :

Post a Comment