Home

Tips for Beginning Java Programmers: Variables and Recycling

|
|  Updated:  
2022-01-05 19:27:37
Java Essentials For Dummies
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:
<b>// This code is cumbersome.</b>
<b>// The extra variables are unnecessary.</b>
char <b>smallLetter1</b>, bigLetter1;
char <b>smallLetter2</b>, bigLetter2;
<b>smallLetter1</b> = 'R';
bigLetter1 = Character.toUpperCase(smallLetter1);
System.out.println(bigLetter1);
<b>smallLetter2</b> = '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:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.