devxlogo

Return a Value and Clear It Without a Temporary Variable

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;}}
See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist