File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes brackets enclosure Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "brackets enclosure" Watch "brackets enclosure" New topic

brackets enclosure

Klament J. Kruoghst
Ranch Hand

Joined: Oct 24, 2008
Posts: 37
Hi there,

I just saw in some code this:

Can someone explain to me the use of those brakets? I'm not sure if it's related to the Map or iterator declaration so that's why im putting it there, maybe it does maybe it doesn't
That doesn't look like an inner class and that doesn't look like an if/else statement, so what is it and why would someone want to use it.

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

I don't think it serves any purpose, really. Although, IIRC, if you declare a new variable inside them, it will go out of scope once you leave that block.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

The only advantage that this style could have is what Fred already mentions: any variables that you declare inside the block go out of scope when the block ends, so you could use this to control the scope of the variables. However, using braces just for this purpose is not something that is commonly done in Java. I would avoid this style of programming. It is probably better to put the whole block in a separate method and call that method instead.

Better: Put the block in its own method.

Even better, but not the point of this topic: Use foreach style for-loops.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: brackets enclosure
It's not a secret anymore!