devxlogo

Using Braces Effectively in Java

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();      usingBraces.proceed();         }      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 UsingBracesi: 0i: 1i: 5*/ 
Image

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.