Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a use of free floating block inside a method in Java?

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?

like image 385
OscarRyz Avatar asked Dec 22 '10 23:12

OscarRyz


People also ask

What is difference between method and block?

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).

Why do we need blocks in Java?

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.


1 Answers

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>");
    ....
like image 114
Bert F Avatar answered Nov 03 '22 08:11

Bert F