Tips for Beginning Java Programmers: When Not to Reuse a Variable

Sometimes in Java, the reuse of variables make a program slick and easy to read. But, as with most things, there is flip side. The problem at hand forces you to create new variables.

Suppose that you’re writing code to reverse the letters in a four-letter word. You store each letter in its own separate variable.

image0.jpg
import java.util.Scanner;
class ReverseWord {
 public static void main(String args[]) {
 Scanner keyboard = new Scanner(System.in);
 char c1, c2, c3, c4;
 c1 = keyboard.findWithinHorizon(".", 0).charAt(0);
 c2 = keyboard.findWithinHorizon(".", 0).charAt(0);
 c3 = keyboard.findWithinHorizon(".", 0).charAt(0);
 c4 = keyboard.findWithinHorizon(".", 0).charAt(0);
 System.out.print(c4);
 System.out.print(c3);
 System.out.print(c2);
 System.out.print(c1);
 System.out.println();
 keyboard.close();
 }
}

The trick in the code is as follows:

  • Assign values to variables c1, c2, c3, and c4 in that order.

  • Display these variables’ values on the screen in reverse order: c4, c3, c2, and then c1.

    image1.jpg

If you don’t use four separate variables, then you don’t get the result that you want. For example, imagine that you store characters in only one variable. You run the program and type the word pots. When it’s time to display the word in reverse, the computer remembers the final s in the word pots. But the computer doesn’t remember the p, the o, or the t.

image2.jpg

Sorry, there are no 12 simple rules to help you decide when and when not to reuse variables. It all depends on what you’re trying to accomplish. So how do you figure out on your own when and when not to reuse variables? Like the guy says to the fellow who asks how to get to Carnegie Hall, “Practice, practice, practice.”

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com