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 #.
/*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
|
Enter some text, terminate with # abcde# The char before the # was e |
| Variables are used in a Java program to contain data that changes during the execution of the program. |
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'; |
| 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.. |
System.out.println("The char before the # was " + (char)ch2);
|
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. |
while( (ch1 = System.in.read() ) != '#') ch2 = ch1; |
The corresponding initialization statement in the C++ program was as
shown below.
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.
|
public static void main(String[] args) //define main method |
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. |
| The type determines the set of values that can be stored in the variable and the operations that can be performed on the variable. |
| In Java, all variables of type int contain signed values. |
| C++ supports the use of both signed and unsigned (all positive) integer types. |
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++. |
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 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. |
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.
|
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. |
In C++, any variable (or object) can be represented in any of three
ways:
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). |
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.
|
|
|
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:
|
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.
|
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.
|
| 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. |
int MyVar, UrVar = 6, HisVar; |
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.
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.
|
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:
A - The proper syntax is shown below:
A - The proper syntax is shown below:
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:
A - The proper syntax for manipulating the variable is shown below:
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:
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:
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.
|
/*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
|
/*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
|