Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Feb 1, 2005



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;}
Asaf Ronen
Thanks for your registration, follow us on our social networks to keep up-to-date