1

I was going through some Java tutorials in a book and ran across code like this:

private void theMethod( MyObject table )
{
  SomeObject item1 = table.add(0,0,0,"Item 1");
  {
    item1.setWhatever = false;
    item1.setSomething = 15;
  }

  // More code here...
}

What is the purpose of the braces following the variable definition?

2
  • I would check out the books errata (probably on the publishers website). More than likely that's an error and they will have an updated example available. Commented Sep 14, 2011 at 20:19
  • I doubt it is errata. The code has no programming purpose, but that does not mean it is errata. Commented Sep 14, 2011 at 21:08

4 Answers 4

6

I use this braces sometimes in group when I'm using a lot of local variables. This way, they are out of scope and I can create variables with the same name.

I can't find immediately a good example, but I mean something like this:

/* Code block 0 */
{
    int localStuff = 9;
    boolean submit = false;
    // Do some IO, or whatever
}
/* Code block 1 */
{
    int localStuff = 4;
    boolean submit = false;
    // Do some IO, or whatever
}

/* Code block 2 */
{
    int localStuff = -1;
    boolean submit = true;
    // Do some IO, or whatever
}
Sign up to request clarification or add additional context in comments.

2 Comments

dup code spotted, what about wrapping your local scopes in a method? :p Anyway, +1
@AurélienRibon - Nice one!. The only talent required for becoming a decent programmer is the ability to find patterns and generalize :-) Sadly, most code tend to look like this example...
2

In this particular example, it doesn't do anything (maybe just improving the code's look, based on the coders' taste). But, it could be also a typo :)

BTW, braces can be helpful for limiting the scope:

private void theMethod( MyObject table )
{
  {
    SomeObject item1 = table.add(0,0,0,"Item 1");
    item1.setWhatever = false;
    item1.setSomething = 15;
  }
  // Item1 is not defined here anymore, so for example you can define another object    with the name item1
  // Though it's not a good practice.
  OtherClass item1;
  // More code here...
}

Comments

1

Are you sure it was like that? Although code blocks can be defined like that, it doesn't do much, except limiting the scope of local variables, which isn't exciting.

However, class-level anonymous code blocks are useful to initialise variables, and populate data structures, etc.

For example, this static anonymous block initialises a final static variable.

public class Snippet {

    private final static Map config;
        static {
            HashMap tmp = new HashMap();
            tmp.put("moo","foo");
            tmp.put("bar","baz");
            config = Collections.unmodifiableMap(tmp);
           }
    // rest of class here.
    }

It works int the same way for non-static blocks and instance variables, which is less useful, but handy if you want to make sure that all constructors and subclasses executes the same code.

I found this thread, which is not a duplicate, but related. Anonymous code blocks in Java

Comments

0

That's normal, the block is used just to organize the code, it's evaluated as a normal flow

class Foo{
    private void theMethod(String str )
    {
      {
        System.out.println(str);
        {}{}{}{}{}{}{}{}
      }
    }

    public static void main(String ...args){

        new Foo().theMethod("my string");
    }
}

Similar way with ;

class Foo{
    private void theMethod(String str )
    {
      {
        System.out.println(str);
        {;}{;}{;}{;}{;}{;}{;}{;}
      }
    }

    public static void main(String ...args){

        new Foo().theMethod("my string");;;;;;;;;;;;;;;;;
    }


}

1 Comment

I wouldn't call the given example normal. It is an actual code snippet from a book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.