Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Tuesday Sep 18th 2018 by M S Sridhar

Language:Java, Expertise: Intermediate - Although using braces is a a common practice, it can sometimes be very misleading

Although using braces is a a common practice, it is sometimes very misleading and it can take hours to figure out what is wrong.

A simple way to avoid such problems is to use the curly braces ({}) as needed to avoid ambiguity.

Below is a simple code sample that does not have braces, and hence, there are problems during compilation.

class UsingBraces
   public static void main(String args[])
      UsingBraces usingBraces = new UsingBraces();
   private void proceed()
      for (int i=0;i           System.out.println("i: " + i); System.out.println("i: " + 5);
      //In the above line, the statement System.out.println("i: " + 5); is not part of the loop. 
      //If you try replacing the value 5 as i, the compiler itself throws an error indicating that the variable i cannot be identified.


Expected output:

[root@mypc]# java UsingBraces
i: 0
i: 1
i: 5

Mobile Site | Full Site