Variables

Introduction

The first step in learning to use a new programming language is usually to learn the foundation concepts such as variables, types, expressions, flow-of-control, etc. This and several subsequent lessons concentrate on that foundation. In many cases, these concepts, as they apply to the Java language, are compared to the same concepts for the C++ language, identifying similarities and differences.

Much of this material should be straightforward and intuitive for persons who have completed the prerequisite for this course: CIS 1033, Pascal Programming, or equivalent. Therefore, it is not intended that large amounts of class time will be devoted to discussing this material.

The lesson begins with a sample Java program and a sample C++ program which mimics the Java program. In both cases, the user is asked to enter some text and to terminate with the # character. The program loops, saving individual characters until encountering the # character, at which time, it terminates and displays the character entered immediately prior to the #.

Sample Java Program

The sample Java program follows:
 
/*File simple1.java Copyright 1997, R.G.Baldwin

This Java application reads bytes from the keyboard until

encountering the integer representation of '#'.  At the end

of each iteration, it saves the byte received and goes back

to get the next byte.



When the '#' is entered, the program terminates input and

displays the character which was entered before the #.

**************************************************************/



class simple1 { //define the controlling class

  //It is necessary to declare that this method can throw

  // the exception shown below (or catch it).

  public static void main(String[] args) //define main method

            throws java.io.IOException {



    //It is necessary to initialize ch2 to avoid a compiler

    // error (possibly unitialized variable) at the statement

    // which displays ch2.

    int ch1, ch2 = '0';



    System.out.println("Enter some text, terminate with #");



    //Get and save individual bytes

    while( (ch1 = System.in.read() ) != '#') ch2 = ch1;



    //Display the character immediately before the #

    System.out.println("The char before the # was " + (char)ch2);

  }//end main

}//End simple1 class.  Note no semicolon required
The output from running this program is shown below with the user input shown in bold italics.
 
Enter some text, terminate with #

abcde#

The char before the # was e
.
 

Sample C++ Program 

The following C++ program is designed to mimic the previous Java program. In particular, in a Java application, the interpreter invokes the class method named main of the controlling class. The main method controls the subsequent flow of the program. 

In this C++ program, the required main function emulates the action of the Java interpreter, invoking a class method named classMain. There are no other statements in the main function. As in the previous Java application, the class method named classMain controls the subsequent flow of the program. This is different from a "typical" C++ program where the function named main controls the flow of the entire program. This approach will be used for illustration purposes in many of the example C++ programs in these lessons because of the manner in which it mimics the operation of a Java program. 
 
/*File simple1.cpp

This C++ application reads bytes from the keyboard until

encountering the # character.  At the end

of each iteration, it saves the byte received and goes back

to get the next byte.



When the '#' is entered, the program terminates input and

displays the character which was entered before the #.

**********************************************************/



#include<stdio.h> //use C-style input/output



class simple1 {

public:

  static void classMain();

};//End simple1 class definition.



//The while loop in this function requires the function to

// be defined outside class (loops not allowed in inline

// functions)

void simple1::classMain(){

  char ch1, ch2;

  printf("%s", "Enter some text, terminate with #\n");



  while( (ch1 = getchar()) != '#') ch2 = ch1; //input bytes



  //Display the character immediately before the #

  printf("%s %c","The char before the # was ",ch2);



}//end classMain



//=======================================================//



void main(){

  //call the class method named classMain

  simple1::classMain();

}//end main
The output from running this program is shown below with the user input in bold italics
 
Enter some text, terminate with #

abcde#

The char before the # was  e
 

.

Discussion of Sample Programs

We will use the sample Java application presented above to discuss several important aspects of the structure of a Java program, and make comparisons with a similar C++ program along the way. We will also provide additional sample programs which illustrate specific points not illustrated in the above programs.

Variables

Variables are used in a Java program to contain data that changes during the execution of the program.
To use variables, you must notify the compiler of the name and the type of the variable (declare the variable).

The syntax for declaring a variable in Java is to precede the name of the variable with the name of the type of the variable as shown below. It is also possible (but not required) to initialize a variable in Java when it is declared as shown.
 
int ch1, ch2 = '0';
This statement declares two variables of type int, initializing one of them to the value of the zero character (0).
 
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 named ch2 in this case was necessary to prevent a compiler error. Without initialization of this variable, the compiler recognized and balked at the possibility that an attempt might be made to execute the following statement with an unitialized variable named ch2.
 
System.out.println("The char before the # was " + (char)ch2);
The strong error-checking capability of the Java compiler refused to compile this program until that possibility was eliminated by initializing the variable.

You should also note that the variable ch2 is being cast as a char in the above statement. Recall that ch2 is a variable of type int, but we want to display the character that the numeric value represents. Therefore, we must cast it (purposely change its type for the evaluation of the expression). Otherwise, we should not see a character on the screen. Rather, we would see the numeric value that represents that character.
 
As another aside, instance 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.
It was necessary to declare these variables as type int because the highlighted portion of the following statement returns an int.
 
while( (ch1 = System.in.read() ) != '#') ch2 = ch1;
Java provides very strict type checking and generally refuses to compile statements with type mismatches.
 
The corresponding initialization statement in the C++ program was as shown below. 
char ch1, ch2;
In C++, the variables were initialized to type char which is the type normally used to store characters in C++, although characters can also be stored in variables of type int as well

Variables in C++ can also be initialized when declared. However, in this case, there was no requirement to initialize the variable. 

Even though it is also possible in the C++ program to reach the following statement without purposely storing a value in the variable named ch2, the C++ compiler is not alert to such potential problems and does not force good programming practice as is the case with Java. 
 
printf("%s %c","The char before the # was ",ch2);
There is essentially no difference in declaring and possibly initializing simple variables of primitive types between Java and C++ 

The Java program also makes another variable declaration identified in boldface in the following statement.
 
public static void main(String[] args) //define main method
In this case, the type of variable declared was an array of type String named args. (Unlike C and C++, arrays are first-class objects in Java.)

This is the feature of Java which 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 was simply ignored by the remainder of the program.
 
There was no corresponding variable declared in the C++ program because C++ does not require the declaration of variables to capture command-line arguments unless the use of command-line arguments is designed into the program. 
All variables in both languages must have a type.
 
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).
 
In Java, all variables of type int contain signed values. 
.
 
C++ supports the use of both signed and unsigned (all positive) integer types. 
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 which causes compiled Java programs to be platform-independent.
 
In C++ however, the way that a variable of a given type is represented may vary from one platform to the next and even from one version of a given brand of compiler to another version of the same brand compiler on the same hardware platform. These variations can lead to significant program portability problems in C++. 
.

Primitive Types

In Java, there are two major categories of data types: primitive types and reference (or object) types. Primitive types contain a single value. The following table lists all of the primitive types (as of JDK 1.1.3) in Java along with their size and format, and a brief description of each.
 
Type       Size/Format                 Description                

byte      8-bit two's complement     Byte-length integer        

short    16-bit two's complement     Short integer              

int      32-bit two's complement     Integer                    

long     64-bit two's complement     Long Integer               

float    32-bit IEEE 754 format      Single-precision floating point

double   64-bit IEEE 754 format      Double-precision floating point

char     16-bit Unicode character    Single character           

boolean  true or false               True or False  
The char type in Java is a 16-bit Unicode character which has the possibility of representing more than 65,000 different characters.
 
The char type in C++ is typically 8 bits, and is simply an 8-bit integer often used to store the ASCII (or other collating table) representation of a human-readable symbol. 

As of this writing in December of 1997, there is no boolean type in C++ (but rumors indicate that it may be added by the committee working on the evolving C++ standard). True and false in C++ is indicated simply by the value of an integer with a value of zero indicating false and a non-zero value indicating true

Although the names of the various types in C++ tend to match the names in the above Java table, the programmer can have no confidence that the size of (range of values for) a particular type will remain fixed as a program is ported from one platform to the next or that all of the types will actually be implemented on all platforms. 

In both languages, the name of a primitive variable evaluates to the value stored in the variable.

Object-Oriented Wrappers for Primitive Types

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.).

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, a number of the standard classes in the API (such as the powerful Vector class) are designed to work only with objects of type Object.

Because it is sometimes necessary to deal with a primitive variable as though it were an object, Java provides wrapper classes which support object-oriented functionality for Java's primitive data types. This is illustrated in the following program which deals with a double type as an object of type Double. The operation of this program is explained in the comments, and the output from the program is shown in the comments at the beginning.
 
/*File wrapper1.java

This Java application illustrates the use of wrappers for 

the primitive types.



This program produces the following output:



My wrapped double is 5.5

My primitive double is 10.5



**********************************************************/

class wrapper1 { //define the controlling class

  public static void main(String[] args){//define main method



    //The following is the declaration and instantiation of a

    // Double object, or a double value wrapped in an object.

    // Note the use of the upper-case D.

    Double myWrappedData = new Double(5.5);



    //The following is the declaration and initialization of

    // a primitive double variable. Note the use of the 

    // lower-case d.

    double myPrimitiveData = 10.5;



    //Note the use of the doubleValue() method to obtain the

    // value of the double wrapped in the Double object.

    System.out.println(

      "My wrapped double is " + myWrappedData.doubleValue());

    System.out.println(

               "My primitive double is " + myPrimitiveData );

  }//end main

}//End wrapper1 class.
.
 
C++ provides no such wrapper classes for the primitive types, but it is possible to create your own wrappers. The following program creates and uses such a wrapper class to mimic the previous Java program. 
/*File wrapper1.cpp

This C++ application illustrates the creation of a class

in C++ which mimics the behavior of a wrapper in Java.



The output from this program is:



My wrapped double is 5.5

My primitive double is 10.5



**********************************************************/



#include<iostream.h>

#include<new.h>

#include<stdlib.h>



//Create a wrapper class to instantiate a primitive double

// instance variable inside an object.

class Double {

  double data;//private data member inside the Double class

public:

  double doubleValue(){return data;}//method to return value

  Double(double inData){data = inData;}//constructor

};//end class Double



class wrapper1 { //mimics controlling class in Java program

public:

  static void classMain(){

    //Prepare for possibility of memory allocation failure.

    set_new_handler(0);



    //Declare, instantiate, and initialize an object of the

    // Double class.

    Double* ptr = new Double(5.5);

    if(!ptr) exit(1); //terminate on failure to allocate



         //Declare and initialize a variable of the primitive

         // double type.

    double primitiveDoubleValue = 10.5;



    //Display the value stored in the Double object and the

    // value of the primitive double variable.

    cout << "My wrapped double is "

      << ptr->doubleValue() << endl;

    cout << "My primitive double is "

      << primitiveDoubleValue << endl;

  }//end classMain



};//End wrapper1 class definition.



//=======================================================//



void main()

{

  //call the class method named classMain

  wrapper1::classMain();

}//end main



//End C++ program
 
.

Reference Types

Primitive types are types where the name of the variable evaluates to the value stored in the variable.

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.
 
At least we can think of it that way. In fact, depending on the particular JVM in use, the reference variable may reference 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 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.

We will discuss this in more detail in a subsequent lesson. For now, suffice it to say that in Java, a variable is either a primitive type or a reference type, and cannot be both. This leads to considerable simplification of the syntax involved in certain expressions relative to C++.
 
In C++, any variable (or object) can be represented in any of three ways: 
  • in a manner akin to a Java primitive type (name evaluates to value), 
  • by the address stored in a pointer variable, or 
  • by a reference similar to a reference type in Java. 
This provides considerable flexibility as to how programs are coded in C++, and can also lead to errors which are not detectable at compile time, but manifest themselves later at runtime. Java does not support pointers. Although a reference variable in Java contains an address, or a reference to an address (as does a pointer variable in C++) Java does not allow you to arbitrarily modify that address as is the case with pointer variables in C++. 

In addition to pointers, C++ also supports struct and union which are not supported by Java. The struct is redundant in C++, easily replaceable by use of a class. A union, on the other hand, is not redundant, in C++ and has its uses. It is unfortunate that Java does not support a union because there are some situations that can be handled very well with a union (such as conversion between big Endian and little Endian formats).

The following fragment of code from the previous Java program dealing with wrappers declares, instantiates, initializes, and manipulates a reference type named myWrappedData. In this case, myWrappedData is a reference to an object of type Double.
 
Double myWrappedData = new Double(5.5);

   . . .

//Note the use of the doubleValue() method to obtain the

// value of the double wrapped in the Double object.

System.out.println

  ("My wrapped double is " + myWrappedData.doubleValue() );
.
 
In comparison, the following code fragment from the previous C++ program dealing with wrappers declares, instantiates, initializes, and manipulates a pointer type named ptr. In this case, ptr is a pointer to an object of type Double
Double* ptr = new Double(5.5);

. . .

//Display the value stored in the Double object and the

// value of the primitive double variable.

cout << "My wrapped double is "<< ptr->doubleValue() << endl;
Reference variables in Java are similar to pointer variables in C++. However, reference variables in Java are easier to use, and are inherently safer because the value stored in a reference variable cannot be changed to some arbitrary location in memory as is the case with pointers in C++ 
.

Variable Names

The rules for Java variable names are as follows:
 
  • Must be a legal Java identifier (see below) consisting of a series of Unicode characters. Unicode characters are stored in sixteen bits, allowing for a very large number of different characters. A subset of the possible character values matches the 127 possible characters in the ASCII character set, and the extended 8-bit character set, ISO-Latin-1 (The Java Handbook, page 60, by Patrick Naughton). 
  • Must not be the same as a Java keyword and must not be true or false. 
  • Must not be the same as another variable whose declaration appears in the same scope. 
The rules for a legal identifier are:
 
  • In Java, a legal identifier is a sequence of Unicode letters and digits of unlimited length. 
  • The first character must be a letter. 
  • All subsequent characters must be letters or numerals from any alphabet that Unicode supports. 
  • In addition, the underscore character (_) and the dollar sign ($) are considered letters and may be used as any character including the first one. 
.

Scope

The scope of a Java variable is defined by the block of code within which the variable is accessible.

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).

The scope of a variable places it in one of the following four categories:
 
  • member variable 
  • local variable 
  • method parameter 
  • exception handler parameter 
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 of the class. This is generally true for both Java and C++.

A local variable is a variable declared within the body of a method or within a block of code contained within the body of a method.

Method parameters are the formal arguments of a method. (A method is a function defined inside of a class.) 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. This holds for both Java and C++.

Exception handler parameters are arguments to exception handlers. The exception handling mechanism for Java is considerably different from that for C++. Exception handlers will be discussed in a subsequent lesson.

The following Java program illustrates member variables (class and instance), local variables, and method parameters.

An illustration of exception handler parameters will be deferred until exception handlers are discussed in depth later.
 
/*File member1.java
Illustrates class variables, instance

variables, local variables, and method parameters.



Output from this program is:



Class variable is 5

Instance variable is 6

Method parameter is 7

Local variable is 8



**********************************************************/

class member1 { //define the controlling class

  //declare and initialize class variable

  static int classVariable = 5; 

  //declare and initialize instance variable

  int instanceVariable = 6; 



  public static void main(String[] args){ //main method

    System.out.println("Class variable is " 

                                          + classVariable);



    //Instantiate an object of the class to allow for 

    // access to instance variable and method.

    member1 obj = new member1();

    System.out.println("Instance variable is " 

                                   + obj.instanceVariable);

    obj.myMethod(7); //invoke the method



    //declare and intitialize a local variable

    int localVariable = 8; 

    System.out.println("Local variable is " 

                                          + localVariable);



  }//end main



  void myMethod(int methodParameter){

    System.out.println("Method parameter is " 

                                        + methodParameter);

  }//end myMethod

}//End member1 class. 
.
 
While C++ does support both class variables and instance variables, it does not support the direct initialization of member variables using code such as the following. 
static int classVariable = 5;

int instanceVariable = 6;
The following program is a C++ program which mimics the behavior of the above Java program. Note that in C++, it necessary to re-declare all static or class variables outside the class definition. The output from the program is shown in the comments at the beginning. 
 
/*File member1.cpp
Illustrates class variables, instance

variables, local variables, and method parameters.



The output from this program is:



Class variable is 5

Instance variable is 6

Method parameter is 7

Local variable is 8



**********************************************************/



#include<iostream.h>



class member1 {

public:

  static int classVariable; //declare class variable

  int instanceVariable;     //declare instance variable



  member1(){ //constructor

    instanceVariable = 6; //initialize instance variable

  }//end constructor



  static void classMain(){

    classVariable = 5; //initialize class variable

    cout << "Class variable is " << classVariable << endl;



    member1 obj;//instantiate an object of this type

         cout << "Instance variable is "

                           << obj.instanceVariable << endl;

    obj.myMethod(7); //call the method



    //declare and display a local variable

    int localVariable = 8;

    cout << "Local variable is " << localVariable << endl;

  }//end classMain



  //displays method parameter

  void myMethod(int methodParameter){

    cout << "Method parameter is "

                                << methodParameter << endl;

  }//end myMethod

};//End member1 class definition.



int member1::classVariable; //must be re-declared in C++

//=======================================================//



void main()

{

  //call the class method named classMain

  member1::classMain();

}//end main
 
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.

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.

As in C++, a block of code is defined by enclosing it within braces { ... }.
 
Thus, in Java, the scope can be the entire method, or can reduced by placing it within a block of code within the method. 
.
 
This scope-reduction feature is also supported in C++, at least that is true with the newest C++ compilers. This is illustrated by the following code fragment which will be presented as part of a complete C++ program in a subsequent lesson. 
/*File cleanup1.cpp
**********************************************************/

class cleanup1{ //simulates controlling class in Java

public:

  static void classMain(){//simulates main method in Java

    //prepare new operator for null return on failure

    set_new_handler(0);



    { //begin scope-reduction block

    //instantiate and initialize object

    newClass newObject(5);

    newObject.showData();  //display contents of object

    cout << "Leaving scope-reduction block. "

                             "Object will be destroyed.\n";

    } //end scope-reduction block



    cout << "No longer in scope-reduction block."

                                 "\nTerminating program\n";

  }//end classMain

};//End cleanup1 class definition.
It will be shown that when this program is compiled under Borland's version 5.0 compiler, the object goes out of scope and destroys when control leaves the block of code defined by the { ... }
In addition,
 
Java and some of the very latest C++ compilers treat 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. 
There are some minor differences between C++ and Java in this regard which will be discussed in more detail in a subsequent lesson which discusses the for statement.

Initialization of Variables

In Java and C++, local variables of primitive types can be initialized when they are declared using statements such as
 
int MyVar, UrVar = 6, HisVar;
In Java, member variables can also be initialized when they are declared, but this is not true in C++.

In both cases, the type of the value used to initialize the variable must match the type of the variable.

Method parameters and exception handler parameters are initialized by the values passed to the method or exception handler by the calling program.

Review Questions for Lesson 20

Q - Write a Java application which reads bytes from the keyboard until encountering the # character. Echo each character to the screen as it is read. Terminate the program when the user enters the # character.

A - The program follows:
 
/*File simple4.java

This application reads bytes from the keyboard until encountering 

the # character and echoes each character to the screen.

The program terminates when the user enters the # character.

*/

class simple4 { //define the controlling class

  public static void main(String[] args) //define main method

            throws java.io.IOException {

    int ch1 = 0;

    System.out.println("Enter some text, terminate with #");

    while( (ch1 = System.in.read() ) != '#') 

                                     System.out.print((char)ch1);

    System.out.println("Goodbye");

  }//end main

}//End simple4 class.
Q - What is the common name for the Java program element that is used to contain data that changes during the execution of the program?

A - variable

Q - What must you do to make a variable available for use in a Java program?

A - To use a variable, you must notify the compiler of the name and the type of the variable (declare the variable).

Q - In Java, you are required to initialize the value of all variables when they are declared: True or False?

A - False: In Java, it is possible to initialize the value of a variable when it is declared, but initialization is not required (note however that in some situations, the usage of the variable will require that it has been initialized).

Q - Show the proper syntax for declaring two variables and initializing one of them using a single Java statement.

A - int firstVariable, secondVariable = 10;

Q - As with C++, the Java compiler will accept statements with type mismatches provided that a suitable type conversion can be implemented by the compiler at compile time: True or False?

A - False. Fortunately, Java provides very strict type checking and generally refuses to compile statements with type mismatches.

Q - Show the proper syntax for the declaration of a variable of type String in the argument list of the main method of a Java program and explain its purpose.

A - The syntax is shown in boldface below:

public static void main(String[] args)

In this case, the type of variable declared is an array of type String named args. The purpose of the String array variable in the argument list is to make it possible to capture arguments entered on the command line.

Q - Describe the purpose of the type definition in Java.

A - All variables in Java must have a defined type. The type determines the set of values that can be stored in the variable and the operations that can be performed on the variable.

Q - Variables of type int can contain either signed or unsigned values: True or False?

A - False. In Java, all variables of type int contain signed values.

Q - What is the important characteristic of type definitions in Java that strongly supports the concept of platform independence of compiled Java programs?

A - In 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.

Q - What are the two major categories of types in Java?

A - Java supports both primitive types and reference (or object) types.

Q - What is the maximum number of values that can be stored in a variable of a primitive type in Java?

A - Primitive types contain a single value.

Q - List the primitive types in Java.

A - byte, short, int, long, float, double, char, and boolean

Q - Like C, C++, Pascal, and other modern programming languages, Java stores variables of type char according to the 8-bit extended ASCII table: True or False?

A - False. The char type in Java is a 16-bit Unicode character.

Q - In Java, the name of a primitive variable evaluates to the value stored in the variable: True or False?

A - True.

Q - Variables of primitive data types in Java are true objects: True or False?

A - False. Primitive data types in Java (int, double, etc.) are not true objects.

Q - Why do we care that variables of primitive types are not true objects?

A - This has some ramifications as to how variables can be used (passing to methods, returning from methods, etc.). For example, all variables of primitive types are passed by value to methods meaning that the code in the method only has access to a copy of the variable and does not have the ability to modify the variable.

Q - What is the name of the mechanism commonly used to convert variables of primitive types to true objects?

A - wrapper classes

Q - How can you tell the difference between a primitive type and a wrapper for the primitive type?

A - The name of the primitive type begins with a lower-case letter and the name of the wrapper type begins with an upper-case letter such as double and Double.

Q - Show the proper syntax for declaring a variable of type double and initializing its value to 5.5.

A - The proper syntax is shown below:

Q - Show the proper syntax for declaring a variable of type Double and initializing its value to 5.5.

A - The proper syntax is shown below:

Q - Show the proper syntax for extracting the value from a variable of type Double.

A - The proper syntax is shown below:

where doubleValue() is a method of the Double class.

Q - In Java, the name of a reference variable evaluates to the address of the location in memory where the variable is stored: True or False?

A - True.

Q - Show the proper syntax for declaring, instantiating, and initializing a reference variable of type Double.

A - The proper syntax is shown below:

Q - Show an example of manipulating the reference type variable described in the previous question.

A - The proper syntax for manipulating the variable is shown below:

where doubleValue() is a method of the Double class.

Q - What is a legal identifier in Java?

A - In Java, a legal identifier is a sequence of Unicode letters and digits of unlimited length. The first character must be a letter. All subsequent characters must be letters or numerals from any alphabet that Unicode supports. In addition, the underscore character (_) and the dollar sign ($) are considered letters and may be used as any character including the first one.

Q - What are the rules for variable names in Java?

A - The rules for Java variable names are as follows:

Q - What is meant by the scope of a Java variable?

A - The scope of a Java variable is the block of code within which the variable is accessible.

Q - What are the four possible scope categories for a Java variable?

A - The scope of a variable places it in one of the following four categories:

Q - What is a member variable?

A - 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 of the class.

Q - Where are local variables declared in Java?

A - 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.

Q - What is the scope of a local variable in Java?

A - 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.

Q - What defines a block of code in Java?

A - A block of code is defined by enclosing it within braces { ... }.

Q - What is the scope of a variable that is declared within a block of code that is defined within a method and which is a subset of the statements that make up the method?

A - In Java, the scope can be reduced by placing it within a block of code within the method.

Q - What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide an example code fragment.

A - 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 sample code fragment follows:

for(int cnt = 0; cnt < max; cnt++){
//do something
}//end of for statement

Q - What are method parameters and what are they used for?

A - Method parameters are the formal arguments of a method. Method parameters are used to pass values into and out of methods.

Q - What is the scope of a method parameter?

A - The scope of a method parameter is the entire method for which it is a parameter.

Q - What are exception handler parameters?

A - Exception handler parameters are arguments to exception handlers which will be discussed in a subsequent lesson.

Q - Write a Java application that illustrates member variables (class and instance), local variables, and method parameters.

A - See the application named member1 earlier in this lesson for an example of such an application..

Q - Can member variables of a Java class be initialized when the class is defined?

A - Yes in Java, but not in C++.

Q - How are method parameters initialized in Java?

A - Method parameters are initialized by the values passed to the method.

Q - Write a Java program that meets the following specification.
 
/*File SampProg04.java

Without reviewing the solution that follows, write a Java 

application that puts the following prompt on the screen:



Enter some text, terminate with #  



Then it echoes each character that you enter (when you press

the <Enter> key.  However, it doesn't echo the # character.

When you enter the # character, the program terminates and

displays your name.



Does your program insert extra blank lines?  If so, can you

explain why?

=============================================================  

*/

class SampProg04 { 

  public static void main(String[] args) //define main method

            throws java.io.IOException {

    int ch1;

    System.out.println("Enter some text, terminate with #");

    while( (ch1 = System.in.read() ) != '#')

      System.out.println("" + (char)ch1);

    System.out.println("Terminating, Bill Gates");

  }//end main

}//End SampProg04 class.
Q - Write a Java program that meets the following specification.
 
/*File SampProg05.java from lesson 20

Without reviewing he following solution, write a java 

application that wraps the value 3.14 in a Double object, 

and then displays two times the value using the 

doubleValue() method of the object.



Also have the application create a primitive double

variable containing 3.14 and display twice the value

contained in the variable without using a wrapper.



Provide appropriate text in the output.



Also display your name on the screen along with a 

terminating message.

=========================================================

*/

class SampProg05 { 

  public static void main(String[] args){ 

    Double myWrappedData = new Double(3.14);

    double myPrimitiveData = 3.14;

    System.out.println

      ("Twice my wrapped double is " + 

        2*myWrappedData.doubleValue() );

    System.out.println

      ("Twice my primitive double is " + 

        2*myPrimitiveData );

    System.out.println("Terminating, Dick Baldwin");

  }//end main

}//End SampProg05 class.  Note no semicolon required
Q - Write a Java program that meets the following specification.
 
/*File SampProg06.java from lesson 20

Without reviewing the following solution, write a Java application

that illustrates the use of member variables, local variables, and

method parameters.  Make all of them type double.



Illustrate two different member variables:  a class variable and

and instance variable.



Display each of them along with appropriate text, and also display 

a terminating message along with your name.

==================================================================

*/

class SampProg06 {

  static double classVariable = 3.14; 

  double instanceVariable = 2*3.14; 



  public static void main(String[] args){ 

    System.out.println("Class variable is " + classVariable);

    SampProg06 obj = new SampProg06();

    System.out.println("Instance variable is " 

                                          + obj.instanceVariable);

    obj.myMethod(3*3.14); 



    //declare and intitialize a local variable

    double localVariable = 4*3.14; 



    System.out.println("Local variable is " + localVariable);

    System.out.println("Terminating, Dick Baldwin");

  }//end main



  void myMethod(double methodParameter){

    System.out.println("Method parameter is " + methodParameter);

  }//end myMethod

}//End SampProg06 class.  Note no semicolon required