Creating Variables


Creating Variables

Creating a usable variable is a two-step process. You must declare the variable and then initialize it. Unlike in C and Fortran, a Java variable can be declared anywhere in the code as long as it is declared before it is used. As we previously mentioned, Java is a strongly typed language (unlike, say, Microsoft Visual Basic) in that the type of the variable must be included in the variable declaration. The general syntax for declaring a primitive variable consists of the variable type followed by the variable name .

 variable_type variable_name; 

You can declare more than one instance of a variable of a given type on the same line. Commas separate the variable names .

 variable_type variable1_name, variable2_name; 

Primitive variables can be initialized when they are declared, but don't have to be. Initialization is different for primitive and reference type variables. Primitive variables are either assigned a value as a primitive literal or by the variable is assigned to another primitive variable. For example, the following are valid declaration-initialization statements.

 int j = 4; int k = j; 

Creating a reference type variable is a two-step process. This first step is to declare a variable of the desired type by writing the variable type followed by the variable name.

 variable_type variable_name; 

This creates a null reference to an object of the specified type. The second step of the process is to allocate memory for the reference variable using the new keyword and to initialize the nonstatic data members of the class by calling one of the class constructors.

 variable_name = new variable_type(arguments); 

The new keyword is a unary operator that takes as its operand the name of a constructor to call. Constructors are described in more detail in Chapter 7. The new operator returns a reference to the object that was created. The object reference is assigned to the variable name that was previously declared. The two parts of the reference variable creation syntax can be combined into one statement. For example, you could type the following ”

 StringBuilder name = new StringBuilder("Scott"); 

A String is a special reference variable type in that a String object can be given a value by assigning it to a String literal. For instance, instead of using a constructor, you can declare and initialize a String variable using the syntax

 String name = "Diana"; 

Class variables are also treated differently; they must be initialized when they are either declared or inside a static initialization block. Static initialization blocks are described in Chapter 7.

Example: Declaring Variables

Java provides a random number generator in the Random class from the java.util package. The Random class really defines a random number sequence so in that sense it is not a true random number generator. The starting point of the sequence can be specified by providing a Random object with a seed. Random number generation is important in probabilistic analysis techniques such as Monte Carlo methods .

The DeclareDemo class demonstrates some of the ways in which variables can be declared. The DeclareDemo class defines two instance variables ”a variable of type long that represents the seed and a Random object. The getSum() method defines two local variables. The sum variable contains the sum of a certain number of random numbers . The for loop defines an integer variable that serves as the loop control variable. Another integer variable is defined in the input parameter list of the getSum() method.

The one thing this example does not do is to declare a class variable, but you can see how this is done by looking at the "Using Instance and Class Variables" example earlier in this chapter.

 import java.util.*; public class DeclareDemo {   private long seed;   private Random random;   public DeclareDemo() {     seed = System.currentTimeMillis();     random = new Random(seed);   }   public double getSum(int number) {     double sum = 0;     for(int i=0; i<number; ++i) {       sum += random.nextDouble();     }     return sum;   }   public static void main(String args[]) {     DeclareDemo demo = new DeclareDemo();     System.out.println("sum is " + demo.getSum(2));   }     } 

Output (will vary) ”

 sum is 1.72326567814789 

Example: Initializing Variables

To demonstrate the different ways that variables can be given initial values, we will once again modify the SimpleGas class first seen in Chapter 7. The SimpleGas6 class defines six variables. Two of them are initialized when they are declared. The others are initialized in constructors. If the no-argument constructor is called, the variables are initialized using literal values. If the four-argument constructor is used, the variables are initialized by assigning them to the values of the arguments passed to the constructor.

 public class SimpleGas6 {   public static int MAX_SPECIES = 20;   private double pressure, temperature;   private int numSpecies;   private String name;   private String units = "MKS";   public SimpleGas6() {     numSpecies = 1;     pressure = 101325.0;     temperature = 207.4;     name = "air";   }   public SimpleGas6(int n, double p, double t,                                     String nm) {     numSpecies = n;     pressure = p;     temperature = t;     name = nm;   }   // These methods return the values of the variables   public String getName() {     return name;   }   public static void main(String args[]) {     SimpleGas6 gas =              new SimpleGas6(5, 21.95, 207.0, "air");     System.out.println("name of gas is " +                                 gas.getName());   } } 

Output ”

 name of gas is air 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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