Beginning Programming with Java For Dummies
Book image
Explore Book Buy On Amazon
There are a few things beginning Java programmers should know about variables and recycling. When you assign a new value to smallLetter, the old value of smallLetter gets obliterated. smallLetter is used twice, and bigLetter is used twice. That’s why they call these things variables.

First, the value of smallLetter is R. Later, the value of smallLetter is varied so that the value of smallLetter becomes 3. When the computer executes this second assignment statement, the old value R is gone.

Two results for the variable SmallLetter in a Java code.

Is that okay? Can you afford to forget the value that smallLetter once had? Yes, sometimes, it’s okay. After you’ve assigned a value to bigLetter with the statement

bigLetter = Character.toUpperCase(smallLetter);
you can forget all about the existing smallLetter value. You don’t need to do this:
// This code is cumbersome.
// The extra variables are unnecessary.
char smallLetter1, bigLetter1;
char smallLetter2, bigLetter2;
smallLetter1 = 'R';
bigLetter1 = Character.toUpperCase(smallLetter1);
System.out.println(bigLetter1);
smallLetter2 = '3';
bigLetter2 = Character.toUpperCase(smallLetter2);
System.out.println(bigLetter2);
You don’t need to store the old and new values in separate variables. Instead, you can reuse the variables smallLetter and bigLetter.

This reuse of variables doesn’t save you from a lot of extra typing. It doesn’t save much memory space, either. But reusing variables keeps the program uncluttered. Sometimes, you can see at a glance that the code has two parts, and you see that both parts do roughly the same thing.

In such a small program, simplicity and manageability don’t matter very much. But in a large program, it helps to think carefully about the use of each variable.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a computer science professor at Drew University. The author of Java Programming for Android Developers For Dummies, Beginning Programming with Java For Dummies, and Android Application Development All-in-One For Dummies, Barry also writes for Server Side (theserverside.com), Android Authority (androidauthority.com), InfoQ.com and numerous other online publications.

This article can be found in the category: