Summary: Earlier modules have touched briefly on the topic of variables. This module discusses Java variables in depth.
Earlier modules have touched briefly on the topic of variables. This module discusses Java variables in depth.
I recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the images and listings while you are reading about them.
The first step
The first step in learning to use a new programming language is usually to learn the foundation concepts such as
This and several future modules concentrate on that foundation.
A sample program
The module begins with a sample Java program named simple1 . The user is asked to enter some text and to terminate with the # character.
(This program contains a lot of code that you are not yet prepared to understand. For the time being, just concentrate on the use of variables in the program. You will learn about the other aspects of the program in future modules.)
The program loops, saving individual characters until encountering the # character. When it encounters the # character, it terminates and displays the character entered immediately prior to the # character.
A complete listing of the program named simple1 is provided in Listing 1 . Discussions of selected portions of the program are presented later in the module.
| Listing 1: Source code for the program named simple1. |
|---|
|
Program output
The output produced by compiling and running this program is shown in Image 1 . The second line of text in Image 1 ending with the # character was typed by the user.
| Image 1: Screen output from the program named simple1. | |
|---|---|
|
Purpose
I will use the program shown in Listing 1 to discuss several important aspects of the structure of a Java program. I will also provide two additional sample programs that illustrate specific points not illustrated in the above program later in this module.
Variables are used in a Java program to contain data that changes during the execution of the program.
Declaring a variable
To use a variable, you must first notify the compiler of the name and the type of the variable. This is known as declaring a variable .
The syntax for declaring a variable is to precede the name of the variable with the name of the type of the variable as shown in Listing 2 . It is also possible (but not required) to initialize a variable in Java when it is declared as shown in Listing 2 .
| Listing 2: Declaring and initializing two variables named ch1 and ch2. |
|---|
|
The statement in Listing 2 declares two variables of type int , initializing the second variable (ch2) to the value of the zero character (0). (Note that I didn't say initialized to the value zero.)
The value of the zero character is not the same as the numeric value of zero, but hopefully you already knew that.
As an aside, characters in Java are 16-bit entities called Unicode characters instead of 8-bit entities as is the case with many programming languages. The purpose is to provide many more possible characters including characters used in alphabets other than the one used in the United States.
Initialization of the variable
Initialization of the variable named ch2 in this case was necessary to prevent a compiler error. Without initialization of this variable, the compiler would recognize and balk at the possibility that an attempt might be made to execute the statement shown in Listing 3 with a variable named ch2 that had not been initialized
| Listing 3: Display the character. |
|---|
|
Error checking by the compiler
The strong error-checking capability of the Java compiler would refuse to compile this program until that possibility was eliminated by initializing the variable.
Using the cast operator
You should also note that the contents of the variable ch2 is being cast as type char in Listing 3 .
(A cast is used to change the type of something to a different type.)
Recall that ch2 is a variable of type int , containing the numeric value that represents a character.
We want to display the character that the numeric value represents and not the numeric value itself. Therefore, we must cast it (purposely change its type for the evaluation of the expression) . Otherwise, we would not see the character on the screen. Rather, we would see the numeric value that represents that character.
As another aside, member variables in Java are automatically initialized to zero or the equivalent of zero. However, local variables , of which ch2 is an example, are not automatically initialized.
Why declare the variables as type int?
It was necessary to declare these variables as type int becausethe statement in Listing 4 (more specifically, the call to the System.in.read method) returns a value of type int .
| Listing 4: Beginning of a while loop. |
|---|
|
Java provides very strict type checking and generally refuses to compile statements with type mismatches.
(There is a lot of complicated code in Listing 4 that I haven't previously explained. I will explain that code later in this and future modules.)
Another variable declaration
The program in Listing 1 also makes another variable declaration shown by the statement in Listing 5 .
| Listing 5: Beginning of the main method. |
|---|
|
An array of String references
In Listing 5 , the formal argument list of the main method declares an argument named args (first cousin to a variable) as a reference to an array object of type String .
Capturing command-line arguments in Java
As you learned in an earlier module, this is the feature of Java that is used to capture arguments entered on the command line, and is required whether arguments are entered or not. In this case, no command-line arguments were entered, and the variable named args is simply ignored by the remainder of the program.
The purpose of the type of a variable
The type determines the set of values that can be stored in the variable and the operations that can be performed on the variable.
For example, the int type can only contain whole numbers (integers) . A whole host of operations are possible with an int variable including add, subtract, divide, etc.
Signed vs. unsigned variables
Unlike C++, all variables of type int in Java contain signed values. In fact, with the exception of type char , all primitive numeric types in Java contain signed values.
Platform independence
At this point in the history of Java, a variable of a specified type is represented exactly the same way regardless of the platform on which the application or applet is being executed.
This is one of the features that causes compiled Java programs to be platform-independent.
In Java, there are two major categories of data types:
Primitive variables contain a single value of one of the eight primitive types shown in Listing 2 .
Reference variables contain references to objects (or null, meaning that they don't refer to anything) .
The eight primitive types in Java?
The table in Image 2 lists all of the primitive types in Java along with their size and format, and a brief description of each.
| Image 2: Information about the primitive types in Java. | |
|---|---|
|
The char type
The char type is a 16-bit Unicode character value that has the possibility of representing more than 65,000 different characters.
Evaluating a primitive variable
A reference to the name of a primitive variable in program code evaluates to the value stored in the variable. In other words, when you call out the name of a primitive variable in your code, what you get back is the value stored in the variable.
Primitive types are not objects
Primitive data types in Java (int, double, etc.) are not objects. This has some ramifications as to how they can be used (passing to methods, returning from methods, etc.) .
The generic Object type
Later on in this course of study, you will learn that much of the power of Java derives from the ability to deal with objects of any type as the generic type Object . For example, several of the standard classes in the API (such as the powerful Vector class) are designed to work only with objects of type Object .
(Note that this document was originally published prior to the introduction of generics in Java. The introduction of generics makes it possible to cause the Vector class to deal with objects of types other than Object . However, that doesn't eliminate the need for wrapper classes.)
Converting primitives to objects
Because it is sometimes necessary to deal with a primitive value as though it were an object, Java provides wrapper classes that support object-oriented functionality for Java's primitive data types.
The Double wrapper class
This is illustrated in the program shown in Listing 6 that deals with a double type as an object of the class Double .
(Remember, Java is a case-sensitive language. Note the difference between the primitive double type and the class named Double .)
| Listing 6: The program named wrapper1. |
|---|
|
The operation of this program is explained in the comments, and the output from the program is shown in the comments at the beginning.
Once again, what is a primitive type?
Primitive types are types where the name of the variable evaluates to the value stored in the variable.
What is a reference type?
Reference types in Java are types where the name of the variable evaluates to the address of the location in memory where the object referenced by the variable is stored.
However, we can think of it that way. Depending on the particular JVM in use, the reference variable may refer to a table in memory where the address of the object is stored. In that case the second level of indirection is handled behind the scenes and we don't have to worry about it.
Why would a JVM elect to implement another level of indirection? Wouldn't that make programs run more slowly?
One reason has to do with the need to compact memory when it becomes highly fragmented. If the reference variables all refer directly to memory locations containing the objects, there may be many reference variables that refer to the same object. If that object is moved for compaction purposes, then the values stored in every one of those reference variables would have to be modified.
However, if those reference variables all refer to a table that has one entry that specifies where the object is stored, then when the object is moved, only the value of that one entry in the table must be modified.
Fortunately, that all takes place behind the scenes and we as programmers don't need to worry about it.
Primitive vs. reference variables
We will discuss this in more detail in a future module. For now, suffice it to say that in Java, a variable is either a primitive type or a reference type, and cannot be both.
Declaring, instantiating, initializing, and manipulating a reference variable
The fragment of code shown in Listing 7 , (which was taken from the program shown in Listing 6 that deals with wrappers) does the following. It
In Listing 7 , the variable named myWrappedData contains a reference to an object of type Double .
| Listing 7: Aspects of using a wrapper class. |
|---|
|
The rules for naming variables are shown in Image 3 .
| Image 3: Rules for naming variables. | |
|---|---|
|
The rules for legal identifiers are shown in Image 4 .
| Image 4: Rules for legal identifiers. | |
|---|---|
|
What is the scope of a Java variable?
The scope of a Java variable is defined by the block of code within which the variable is accessible.
(Briefly, a block of code consists of none, one, or more statements enclosed by a pair of matching curly brackets.)
The scope also determines when the variable is created (memory set aside to contain the data stored in the variable) and when it possibly becomes a candidate for destruction (memory returned to the operating system for recycling and re-use) .
Scope categories
The scope of a variable places it in one of the four categories shown in Image 5 .
| Image 5: Scope categories. | |
|---|---|
|
Member variable
A member variable is a member of a class (class variable) or a member of an object instantiated from that class (instance variable) . It must be declared within a class, but not within the body of a method or constructor of the class.
Local variable
A local variable is a variable declared within the body of a method or constructor or within a block of code contained within the body of a method or constructor.
Method parameters
Method parameters are the formal arguments of a method. Method parameters are used to pass values into and out of methods. The scope of a method parameter is the entire method for which it is a parameter.
Exception handler parameters
Exception handler parameters are arguments to exception handlers. Exception handlers will be discussed in a future module.
Illustrating different types of variables in Java
The Java program shown in Listing 8 illustrates
An illustration of exception handler parameters will be deferred until exception handlers are discussed in a future module.
| Listing 8: The program named member1. |
|---|
|
Declaration of local variables
In Java, local variables are declared within the body of a method or within a block of code contained within the body of a method.
Scope of local variables
The scope of a local variable extends from the point at which it is declared to the end of the block of code in which it is declared.
What is a "block" of code?
A block of code is defined by enclosing it within curly brackets as in { ... }.
Therefore, the scope of a local variable can be the entire method, or can reduced by declaring it within a block of code within the method.
Java treats the scope of a variable declared within the initialization clause of a for statement to be limited to the total extent of the for statement.
A future module will explain what is meant by a for statement or a for loop.
Initializing primitive local variables
Local variables of primitive types can be initialized when they are declared using statements such the one shown in Listing 9 .
| Listing 9: Initialization of variables. |
|---|
|
Initializing member variables
Member variables can also be initialized when they are declared.
In both cases, the type of the value used to initialize the variable must match the type of the variable.
Initializing method parameters and exception handler parameters
Method parameters and exception handler parameters are initialized by the values passed to the method or exception handler by the calling program.
This section contains a variety of miscellaneous information.
Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.
I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.
Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.
-end-