Published: May 30, 2008
By Richard G. Baldwin
Homeschool Programming Notes # 302
This tutorial lesson is part of a continuing series that is designed specifically for teaching computer programming to homeschool students and their parents. Even though the series is designed for homeschool students, everyone is welcome to use the lessons to learn computer programming.
I will begin by reviewing some of what you learned in an earlier Scratch lesson regarding memory, variables, and literals. Then I will partially explain a Java program that illustrates those same topics. I will defer an explanation of some parts of the program until future lessons. Along the way, I will explain allowable variable names, legal identifiers, and literals in Java.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com.
In an earlier lesson titled Memory, Variables, and Literals (see Resources), I explained those topics in the context of the Scratch programming language. However, that explanation was sufficiently general to apply to Java programming as well. In this lesson, I will simply update the material to make it more specific to the Java programming language.
Also, in that earlier lesson, as a preview of future lessons, I presented the source code for a Java program that illustrates the use of memory, variables, and literals. However, you probably didn't have the necessary Java programming tools installed on your computer at that time to compile and execute the program. I am assuming that you do have those tools installed now. I won't repeat the general discussion from the earlier lesson regarding memory, variables, and literals, but I will pick up where the earlier lesson left off insofar as Java is concerned.
Listing 1 presents a sample Java program that illustrates the use of memory, variables, and literals. According to the jargon, the text that you see in Figure 1 is often referred to as program code or source code.
Listing 1. A sample Java program.
//File Memory01.java class Memory01{ public static void main(String[] args){ int beans; beans = 25; System.out.println(beans); }//end main }//End Memory01 class |
You should be able to use your source-code editor to copy the source code for this program into a file named Memory01.java. Then you should be able to compile and execute it. When you do, the program should display 25 on your computer screen.
|
No color allowed
Note that I used the color blue to emphasize certain code in Listing 1. I did that to make it easy to refer to that code in this discussion. However, you must never include color in the actual Java source code that you are going to compile.
Variables
According to common programming jargon, the term variable is used as a general description of the chunks of memory that are allocated for temporary storage of program data.
The blue text
The use of variables is illustrated by the blue text in the Java program shown in Listing 1. (We will ignore the other text in the program at this time and come back to it later.)
Declaring a variable
In Scratch, Alice, and Java, it is necessary to declare the name of a variable before you can use it. (That is not the case in some programming languages such as Python.) In Alice and Java, it is also necessary to declare the type of data that will be stored in the variable. (As you learned from the early lessons in this series, Scratch variables can only contain data of a numeric type so no type declaration is required in Scratch.)
When you declare a variable in Java, a small chunk of computer memory is set aside, given the specified name, and associated with the specified type. For example, the first blue statement in the Java program in Listing 1 sets aside a small chunk of memory, gives it the name beans, and associates it with the type int.
In programmer jargon, this is referred to as declaring a variable. The process of declaring a variable causes memory to be set aside to contain a value, and causes that chunk of memory to be given a name. That name can be used later to refer to the value stored in that chunk of memory.
The declaration in Listing 1 also specifies that the values stored in the variable must be of type int. Don't worry about what type means at this point. I will discuss the concept of type in detail in future lessons. (For the curious, however, int in Java specifies that the data values will always be integer numeric values in a particular storage format.)
Variable declaration syntax
The syntax for declaring a variable consists of the name of the type followed by the name of the variable with the two separated by one or more spaces. You can declare more than one variable in the same statement by starting with the name of the type and following that with a list of the variable names separated by commas. In both cases, the statement must be terminated by a semicolon as shown in Listing 1.
Automatic initialization of Java variables
Although the variable declaration in Listing 1 doesn't do so, it is possible to specify an initial value for a variable when it is declared. If an initial value is not specified when the variable is declared, the value stored in the variable will be automatically initialized to a default value. This is a very important and useful feature of Java that doesn't exist is some other programming languages, such as C++ for example.
The default initialization value for all numeric types and for the char type is zero. The default initialization value for the boolean type is false. The default initialization value for types identified by classes (a topic for a future lesson) is null.
Storing a value in the variable
A value of 25 is stored in the variable named beans in the second blue statement in Listing 1.
In programmer jargon, this is referred to as assigning a value to a variable. From this point forward, when the code in the program refers to the variable named beans, depending on how the name is used, the reference to the variable will either:
Retrieving a value from the variable
The third line containing blue text in Listing 1 retrieves the value currently stored in the variable named beans by referring to the variable by name.
This statement also causes that value to be displayed on your computer screen. At this point, you shouldn't worry about what causes it to be displayed. You will learn those details in future lessons. Just remember that when used in this manner, the reference to the variable by name retrieves the value stored in the variable.
Don't be concerned about the other details
Don't be concerned at this point about the other details in the program shown in Listing 1. They are there to make it possible for you to compile and execute the program if you elect to do that. You will learn about them in future lessons.
Two ways of thinking
There are at least two ways to think about variables:
In the conceptual view, a variable can be thought of as being analogous to one of the terms in an algebraic formula or expression.
An example
For example, if you work as a manager of a retail store, you might think in terms of the relationship between the cost and the price of a product as shown in Figure 1.
Figure 1. Relationship between cost and price of a product.
price = cost + markup; |
Why the semicolon?
The semicolon is there to make it a valid programming statement in the Java programming language. I will have a lot more to say about the specific syntax of Java programs in future lessons. Although you didn't have to worry about syntax when programming in Scratch and Alice, syntax becomes a big issue when programming in Java, C#, C++, and other similar programming languages.
Think of the terms as variables
If you were to write a computer program that evaluates the relationship shown in Figure 1, you would probably consider price, cost, and markup all to be variables.
As you already know, every variable has a name and a value. The value of a variable may change as the program executes. (That's why it is called a variable instead of a constant.)
Case sensitivity
The name of a variable is case sensitive in Java (but the name may not be case sensitive in other programming languages). In other words, the name avariable is not the same as the name aVariable in case sensitive programming languages. If both names were used in the same program, they would refer to two different variables.
Figure 2 shows the rules for variable names in Java.
Figure 2. Rules for variable names in Java.
An allowable name for a variable in Java:
|
Figure 3. Rules for legal identifiers in Java.
|
Use names to access values
Variables have names like price, cost, and markup. The names of the variables give us easy access to the values of the variables.
Some operations cause the value of a variable to change while other operations simply access the value without changing it.
Evaluating a statement
The evaluation of the statement shown in Figure 1 by a computer program might go something like the following:
Only the value of price is modified
Only the value of the variable named price is modified by the execution of the statement in Figure 1. The values of the variables named cost and markup are not modified by executing the statement.
The physical view of a variable takes us back to an earlier description of how memory is used in a computer program.
In the physical view, a variable is a chunk of memory to which a name (and possibly a type) has been assigned, and in which a value can be stored. The name of the chunk of memory is the name of the variable. The value stored in the chunk of memory is the value of the variable.
Storing and retrieving
As the program executes, the values stored in those chunks of memory can be replaced by other values. In that way, the values of the variables can change as the program executes.
It is also possible to retrieve the value stored in a chunk of memory without modifying it. In that way, the values of variables can be used to evaluate expressions without modifying those values.
Declaration of a variable
As mentioned earlier, it is necessary to declare the name of a variable before you can use it in Java. It is also necessary to declare the type of data that will be stored in the variable. A small chunk of computer memory is set aside and given the specified name when the variable is declared. That chunk of memory then becomes the physical manifestation of the variable.
To learn more about variables
To learn more about variables, see the link to my earlier tutorial titled 20 Variables in Resources.
Where does data originate?
The data used by a computer program can originate from a variety of sources. For example, it can be entered from the keyboard. It can be read from a disk file. It can be downloaded from a web site, etc.
Hard-coded data
The data values can also be coded into the program when the program is written. In this case, we would call it a literal or a literal value.
For example, the value 25 in Listing 1 is a literal value. It was hard-coded into the program when the program was written. As another example, the Java code fragment in Figure 4 declares a variable named pi and then assigns a literal numeric value of 3.14159 to that variable. (Don't worry about the type named double at this point. You will learn all about it in future lessons. For the time being, suffice it to say that it is a variable that can contain values that are not required to be whole numbers.)
Figure 4. An example of literal data.
double pi; pi = 3.14159; |
Do you recognize this value?
You may recognize this as the value of the numeric constant named pi, which is commonly used for doing calculations with circles. However, literals don't have to be famous values. A literal can be any value such as the age of a person or the price of a can of beans as in Listing 1.
Calculations with circles
Having executed the two statements in the code fragment in Figure 4, we could then use the value stored in the variable named pi to perform arithmetic such as calculating the area of a circle. (Actually, the value of pi is already defined in the standard Java math library, but it makes a pretty good example for explanation of literals anyway since most people recognize it.)
A value coded into the program...
That is just about all there is to understanding literals. There are some special rules that come into play in certain situations, and I will discuss those rules at the appropriate points in time. For now, just remember that a literal is a value that is coded into the program when the program is written.
I encourage you to copy the code from Listing 1 into your source-code editor. Compile the code, and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.
Write, compile, test, and debug if necessary a Java program named MyName02. This program declares a value of type String named myName. It assigns your name to the variable and then causes the contents of the variable to be displayed on the command-line screen.
I began by reviewing some of what you learned in an earlier Scratch lesson regarding memory, variables, and literals. Then I partially explained a Java program that illustrates those same topics. I deferred an explanation of some parts of the program until future lessons. Along the way, I explained allowable variable names, legal identifiers, and literals in Java.
In the next lesson, you will learn about Java methods.
Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-