I didn't know methods could have floating blocks like this:
class X {
public static void main( String [] args ) {
{ //<--- start
int i;
} //<-- ends
}
}
I was aware of floating blocks outside methods, but never tried them inside.
This could probably be used to define local scope or something.
Is there a use for floating blocks inside methods in Java?
Methods are also (generally) named and can be called from elsewhere in your code by that name. Blocks cannot, they can only be reached by following the flow of the code in your class (so generally through calling the method they're contained in and reaching the proper conditions for their execution).
A block statement is a sequence of zero or more statements enclosed in braces. A block statement is generally used to group together several statements, so they can be used in a situation that requires you to use a single statement.
Is there a use?
Yes - to limit the scope of local variables.
Is it a good idea?
Probably debatable (and likely will be).
The "pro" camp will say it never hurts to narrow the scope of variable. The "con" camp will say that, if you use it in a method and your method is long enough to warrant narrowing the scope of variables to specific sections, then it is probably an indication that you should make separate methods out of the different sections.
Personally, I use them, e.g.:
public void doGet(
final HttpServletRequest request,
final HttpServletResponse response)
throws IOException {
final PersistenceManager pm = PMF.get().getPersistenceManager();
final List<ToDoListGaejdo> toDoLists;
{
final Query query = pm.newQuery(ToDoListGaejdo.class);
query.setOrdering("listName asc");
toDoLists = (List<ToDoListGaejdo>) query.execute();
}
final List<ToDoItemGaejdo> entries;
{
final Query query = pm.newQuery(ToDoItemGaejdo.class);
query.setOrdering("listName asc, priority asc");
entries = (List<ToDoItemGaejdo>) query.execute();
}
final ServletOutputStream out = response.getOutputStream();
out.println("<head>");
out.println(" <title>Debug View</title>");
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With