Monday, 2 February 2015

Java Curly Braces

I wanted to produce the output below 5 times:

Flip
Flop

So I tried to do it like this:

andrew@UBUNTU:~/Java$ cat Curly_Braces1.java
class Curly_Braces1
  {
  public static void main(String args[])
    {
    for (int x=1; x<=5; x++)
      System.out.println("Flip");
      System.out.println("Flop");
    }
  }
andrew@UBUNTU:~/Java$ javac Curly_Braces1.java
andrew@UBUNTU:~/Java$ java Curly_Braces1
Flip
Flip
Flip
Flip
Flip
Flop
andrew@UBUNTU:~/Java$


Java only executes one line of code each time a for loop executes. The line displaying Flop was therefore only executed once, after the for loop had finished.

To achieve the desired effect, I started the code to be executed with a left-hand curly brace and finished it with a right-hand curly brace. Java then treated the two lines as a single block of code and executed them both for every iteration of the loop:

andrew@UBUNTU:~/Java$ cat Curly_Braces2.java
class Curly_Braces2
  {
  public static void main(String args[])
    {
    for (int x=1; x<=5; x++)
      {
      System.out.println("Flip");
      System.out.println("Flop");
      }
    }
  }
andrew@UBUNTU:~/Java$ javac Curly_Braces2.java
andrew@UBUNTU:~/Java$ java Curly_Braces2
Flip
Flop
Flip
Flop
Flip
Flop
Flip
Flop
Flip
Flop
andrew@UBUNTU:~/Java$