Return a Value and Clear It Without a Temporary Variable

Have you ever implemented a method and wanted to return the value of a variable and then clear (or change) the variable? Since you can’t typically execute another line of code after your “return” statement, most people use a temporary variable to accomplish this:

private String var;public String getAndClear () {   String temp = var;   var = null;   return temp;}

However, you can also accomplish the same thing without using the local temp variable:

private String var;public String getAndClear () {   try {return var;} finally {var = null;}}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: