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

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

By Barry Burd

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.


import java.util.Scanner;
class ReverseWord {
 public static void main(String args[]) {
 Scanner keyboard = new Scanner(;
 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);

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.


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.


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.”