Working With Reference Types


Working With Primitive Types

This section provides a detailed discussion of how to use Java primitive data types in your programs. I will begin by showing you how to declare and use primitive data type variables and constants in the main() method. I will then show you how to declare and use class and instance variables. It’s important to understand how the main() method and objects declared within its body relate to the enclosing class structure. Learning this stuff now will avoid a lot of confusion later.

During this discussion I will use several Java language operators to perform value assignments and simple arithmetic on the constants and variables. These operators include ‘=’ for assignment, and ‘+’ for addition. Other Java operators are discussed in detail later in the chapter.

Application Class Structure

Example 6.4 presents the source code for the application class named TestClassOne that I will use to present the concepts of primitive-type variables and constants.

Example 6.4: TestClassOne.java

image from book
 1     public class TestClassOne { 2 3     public static void main(String[] args){ 4 5 6      } 7     }
image from book

Before getting started I’d like to present you with a good working definition of the term variable.

Definition Of The Term “Variable”

A variable is a named location in memory whose value can be changed during the course of program execution.

Declaring And Using Variables In The Main() Method

Before you can use a variable in a Java program you must declare the variable by specifying its data type and its name. Example 6.5 shows an integer (int) variable being declared and used in the TestClassOne main() method.

Example 6.5: TestClassOne.java (mod 1)

image from book
 1     public class TestClassOne { 2                                            3       public static void main(String[] args){ 4         int int_variable = 0; 5         System.out.println(int_variable); 6       } 7     }
image from book

The name of the variable is int_variable and the value being assigned to it is zero. The variable is then being used as an argument to the System.out.println() method which prints its value to the console as shown in figure 6-3.

image from book
Figure 6-3: TestClassOne Mod 1 Output

Let’s add another variable declaration to the main() method as shown in example 6.6.

Example 6.6: TestClassOne.java (mod 2)

image from book
 1     public class TestClassOne { 2                                            3       public static void main(String[] args){ 4         int int_variable = 0; 5         int int_variable_2 = int_variable; 6 7         System.out.println(int_variable); 8         System.out.println(int_variable_2 ); 9       } 10    }
image from book

In this example another integer variable named int_variable_2 is declared and its value is initialized using the value of int_variable. Both their values are then printed to the console by the System.out.println() method. Notice how primitive type values are assigned directly to the variable name using the assignment operator =.

Example 6.7 adds a few more variables to the main() method and uses them to perform several arithmetic operations.

Example 6.7: TestClassOne.java (mod 3)

image from book
 1    public class TestClassOne { 2 3      public static void main(String[] args){ 4        int int_variable = 0; 5        int int_variable_2 = int_variable; 6        int total = 0; 7 8        int_variable   = 2; 9        int_variable_2 = 3; 10       total = int_variable + int_variable_2; 11 12 13       System.out.println(int_variable); 14       System.out.println(int_variable_2); 15       System.out.println(total); 16       System.out.println(int_variable + int_variable_2); 17     } 18   }
image from book

Figure 6-4 shows the output that results from running this program.

image from book
Figure 6-4: TestClassOne Mod 3 Output

Referring to example 6.7 above, notice how the variable declarations are grouped toward the top of the main() method. The variable named int_variable is declared first and is then used on the next line to initialize int_variable_2. This illustrates an important point — you must declare and initialize a variable before you can use it in your program. Once declared, it is available for use on the next line.

On lines 8 and 9 the values of int_variable and int_variable_2 are changed to 2 and 3 respectively. On line 10 the new values of int_variable and int_variable_2 are used to initialize the variable named total. The values of all three variables are then printed to the console as shown in figure 6-4 above.

Notice on line 16 that int_variable and int_variable_2 are added together within the parentheses of the System.out.println() method. This is acceptable because the result of the addition yields an integer value which is recognized by the println() method.

Definition Of The Term “Constant”

A constant is a named location in memory whose value, once set, cannot be changed during the course of program execution. A constant, in the Java programming language, is a variable that’s declared to be final. (i.e., a final variable)

Declaring And Using Constants In The Main() Method

Constant declarations begin with the final keyword. Their value must be initialized at the point of declaration and once set, cannot be changed during program execution. Example 6.8 shows a constant being declared and used in the TestClassOne main() method.

Example 6.8: TestClassOne.java (mod 4)

image from book
 1    public class TestClassOne { 2 3      public static void main(String[] args){ 4        final int CONST_VALUE = 25; 5        System.out.println(CONST_VALUE); 6      } 7    }
image from book

Figure 6-5 shows the results of running this program.

image from book
Figure 6-5: TestClassOne Mod 4 Output

You can use a variable or another constant to initialize a constant’s value as is shown by example 6.9.

Example 6.9: TestClassOne.java (mod 5)

image from book
 1    public class TestClassOne { 2      public static void main(String[] args){ 3        final int CONST_VALUE = 25; 4        final int CONST_VALUE_2 = CONST_VALUE; 5              int int_variable = CONST_VALUE_2; 6        final int CONST_VALUE_3 = int_variable + CONST_VALUE_2; 7        System.out.println(CONST_VALUE); 8        System.out.println(CONST_VALUE_2); 9        System.out.println(int_variable); 10       System.out.println(CONST_VALUE_3); 11     } 12   }
image from book

Figure 6-6 shows the results of running this program.

image from book
Figure 6-6: TestClassOne Mod 5 Output

Referring to example 6.9 above, notice how the constants are declared using all uppercase letters. Doing so sets them apart from variables and makes them easy to spot in the code. Constants, once declared and initialized, can be used like variables in your source code as is illustrated on line 6. The only difference is that any attempt to change a constant’s value after it has been declared and initialized will result in a compiler error. This is illustrated by the code shown in example 6.10 and the compiler error message shown in figure 6-7.

Example 6.10: TestClassOne.java (mod 6)

image from book
 1    public class TestClassOne { 2      public static void main(String[] args){ 3        final int CONST_VALUE = 25; 4        final int CONST_VALUE_2 = CONST_VALUE; 5              int int_variable = CONST_VALUE_2; 6        final int CONST_VALUE_3 = int_variable + CONST_VALUE_2; 7 8        CONST_VALUE = 5;  // This will result in a compiler error 9 10       System.out.println(CONST_VALUE); 11       System.out.println(CONST_VALUE_2); 12       System.out.println(int_variable); 13       System.out.println(CONST_VALUE_3); 14     } 15   }
image from book

image from book
Figure 6-7: Compiler Error Message Resulting From Attempt To Change A Constant’s Value

Getting Simple Input Into Your Program

Up to now I’ve shown you how to set the value of variables and constants in short programs and use those variables and constants to perform simple arithmetic operations. However, it would be nice to input values into the program when it starts running. Unfortunately, although Java makes it easy to print output to the console, it’s not so easy to accept input from the console without first digging deeper into the Java platform classes for help.

To avoid this I will take a different approach. I will show you how to use the main() method’s String array to get input from the console when the program first starts. This will tide you over until you formally learn how to create reference type objects in the next section.

Using The main() Method’s String Array To Accept Input At Program Startup

When a Java application is started from the console a series of arguments can be input into the program by way of the main() method’s String array. The name of the array parameter is usually named args which is short for arguments.

Example 6.11 gives the source code for image from book TestClassOne.java showing how the String array is used to accept three String values from the command line at program startup.

Example 6.11: TestClassOne.java (mod 7)

image from book
 1    public class TestClassOne { 2 3      public static void main(String[] args){ 4        int int_variable_1 = Integer.parseInt(args[0]); 5        int int_variable_2 = Integer.parseInt(args[1]); 6        int int_variable_3 = Integer.parseInt(args[2]); 7 8        int total = int_variable_1 + int_variable_2 + int_variable_3; 9 10       System.out.println(total); 11 12     } 13   }
image from book

This example also employs the services of a primitive type wrapper class named Integer. Let’s take a look at the program in action and then discuss what’s happening in the code. Figure 6-8 shows the results of running this program.

image from book
Figure 6-8: Results of Running TestClassOne with the Input 1 2 3

As figure 6-8 illustrates, the program is run from the command line with the java tool as usual, however, three digits follow the name of the class. These three digits are read into the main() method String array as string arguments and are converted into integer values by the Integer.parseInt() method.

Each position of the args array is accessed with the subscript operator[] and an integer value. The String array element args[0] represents the first element of the array and contains the value “1”. This is used on line 4 as an argument to the Integer.parseInt() method. The second element of the args array, args[1], contains the value “2”, and the third element, args[2], contains the value “3”. These are converted into int values with the Integer.parseInt() method on lines 5 and 6.

Once the Strings have all been converted to integer values the variables are added and the result is assigned to the total variable. The value of the total variable is then printed to the console as is shown by figure 6-8.

This program is a slight improvement upon previous programs but is still rather clunky because you must always enter three numbers to add — no more — no less. It will also cause a runtime error if one of the values supplied to the program on the command line does not translate into an integer. Figure 6-9 shows the results of running the program again with three different values.

image from book
Figure 6-9: Running TestClassOne Again with Different Input Values

In order to write more powerful programs you will have to master the use of reference data types.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net