Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jan 31, 2005

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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap