Lesson 5
October 9, 2000
I recommend that you also make use of my online Java tutorial lessons, which are designed from a more conventional textbook approach. Those tutorial lessons are published at Gamelan.com.
For your convenience, I also maintain a consolidated Table of Contents on my personal web site that links to the individual lessons on the Gamelan site.
Insofar as possible, I will make use of Sun Java in these lessons. However, it will not be possible for me to go back and do a full update each time Sun releases a new version, so over the course of time, I expect to use different versions of Sun Java.
Just in case you would like to sneak a peek, the answers to the questions, and the explanations of those answers are located (in reverse order) at the end of this file.
The questions and the answers are connected by hyperlinks to make it
easy for you to navigate from the question to the answer and back.
It is recommended that you make your first pass through the questions in
the order that they appear so as to avoid inadvertently seeing the answer
to a question before you provide your own answer.
2. What output is produced by the following program? Note that the main() method is not declared public.
class Q005_02{ static void main(String args[]){ System.out.println("OK"); }//end main() }//end class definition |
3. What output is produced by the following program? Note that the main() method is not declared static.
class Q005_03{ public void main(String args[]){ System.out.println("OK"); }//end main() }//end class definition |
4. What is the purpose of the reference to the array of String references in the argument list of the main() method?
5. What is the lifetime and scope of a local variable in Java?
6. What is the lifetime and scope of an instance variable in Java?
7. What is the lifetime and scope of a class variable in Java?
8. True or false? All member variables and all local variables are automatically initialized in Java.
9. Member variables are automatically initialized to default values in Java. What are those default values.
10. True or false? In Java, primitives are passed by value and objects are passed by reference.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
As a result of this, if a reference variable is
passed to a method, the code in method can use the copy of the reference
variable to gain access to the object to which it refers. However,
the code in the method cannot cause the original reference variable to
refer to a different object.
Primitive numeric variables are initialized to zero in the proper format for the type of the variable.
Primitive boolean variables are initialized to false.
Primitive char variables are initialized to a value consisting of 16 bits, all of which have the value zero. This can be described in Unicode hexadecimal notation as the character '\u0000'.
However, even though local variables are not automatically initialized, the compiler will not allow you to use a local variable until you either purposely initialize it or assign a value to it. If you try to do so, you will get a compiler error. This is to protect you from inadvertently processing garbage data that may have been in the memory space occupied by the local variable when the program started.
Apparently the lifetime of a class variable extends from the first reference to the class (causing the class to be loaded into memory) until the class is removed from memory for whatever reason.
No matter how many objects are instantiated from the class, only one copy of the class variable exists, and that copy is shared among all the objects instantiated from the class.
A class variable can be accessed by any method in any object instantiated from the class, and can also be accessed by any method in any other object simply by joining the name of the class to the name of the class variable (provided that its access is not otherwise restricted through the use of private or protected).
Java does not support the concept of global variables. A class variable is about as close as you can get to a global variable in Java.
Some of the accessibility characteristics of a
class variable are illustrated in the following program.
//File Q005_07.java import java.awt.Color; class Q005_07{ public static void main( String args[]){ System.out.println(Color.green); new Q005_07().aMethod(); }//end main() //---------------------------------// void aMethod(){ System.out.println(Color.red); }//end aMethod() }//end class definition |
The standard Java class named Color has a number of public class variables named red, green, blue, yellow, etc. This program accesses two of those class variables in different ways.
Because it is declared static, the main() method is a class method. (I will have a lot more to say about class methods and instance methods in a subsequent lesson.) A statement in the main method accesses (and displays) the class variable named green in the class named Color simply by joining the name of the variable to the name of the class. This statement produces the following output:
java.awt.Color[r=0,g=255,b=0]
Unless you know how colors are handled in Java, this output won't mean much to you. Suffice it to say that this is an indication of a color consisting of no red, 100% green, and no blue.
Then the main method instantiates an object of the controlling class and invokes an instance method named aMethod() on that object. The behavior of that instance method is to access and display the class variable named red in the class named Color by joining the name of the variable to the name of the class. This statement produces the following output:
java.awt.Color[r=255,g=0,b=0]
As an aside, these class variables in the Color class are also declared final, meaning that their values cannot be modified, but that is not a technical requirement for a class variable.
For a variety of good design reasons, class variables should be used very sparingly if at all. Excessive and inappropriate use of class variables can sometimes lead to a poor design. The use of final class variables in the Color class is a good example of the appropriate use of class variables.
An instance variable of a class is created when the instance (object) is created, and has a lifetime that is the same as the lifetime of the object.
The instance variable is directly accessible by any instance method belonging to the object.
Depending on the use of public, private, and protected, it may be accessible to methods in other objects as well, but in that case, it is only accessible via the object to which it belongs.
Some of these considerations are illustrated in
the following program.
//File Q005_06.java class Q005_06{ public static void main( String args[]){ AClass ref1 = new AClass(5); AClass ref2 = new AClass(10); ref1.directShow(); ref2.directShow(); ref1.getAndShow(ref2); }//end main() }//end class definition //-----------------------------------// class AClass{ private int x;//instance variable AClass(int x){//constructor this.x = x; }// end constructor //An instance method void directShow(){ System.out.print(x + " "); }//end directShow() //An instance method void getAndShow(AClass ref){ System.out.print(ref.x + " "); }//end getAndShow() }//end class AClass |
This program defines a class named AClass that has a private instance variable named x. The constructor for the class receives an incoming parameter and stores it in the private instance variable. The class also defines two instance methods named directShow() and getAndShow().
The main method of the controlling class instantiates two objects of type AClass passing parameter values of 5 and 10 to the constructor. Thus, two objects of the class AClass come into existence. The private instance variable of one contains the value 5. The private instance variable of the other contains the value 10.
Then the main method invokes the method named directShow() on each of the objects. The behavior of directShow() is to display the value of the instance variable named x of the object to which it belongs. This is possible even if the instance variable is private, because instance methods have direct access to all instance variables of the object to which they belong, even if the instance variable is private.
In this case, the method directly accesses the private instance variable belonging to the object to which the instance method belongs, and displays the value of the instance variable.
Then the main method invokes the method named getAndShow() on one of the objects, passing a reference to the other object as a parameter. The behavior of this method is to attempt to access the instance variable named x belonging to the object whose reference is received as a parameter. In this case, even though the instance variable is private, the access is successful because both objects were instantiated from the same class. (This point is probably not widely understood.) An instance method in an object has access to all instance variables in all other objects instantiated from the same class even if they are private.
The output from the program was:
5 10 10
A local variable is a variable declared inside
of a method in Java. All local variables in Java are automatic
variables. Unlike C and C++, Java does not support the concept of
static
local variables that persist from one invocation of the method until the
next invocation of the same method.
A local variable is created when control reaches the point where it is declared, exists only during execution of the method, and is accessible only within the method. Furthermore, accessibility of a local variable can be further restricted by placing it inside a block within the method. The variable is accessible only within the block within which it declared where a block consists of one or more statements surrounded by curly braces.
The variable must be declared before it can be accessed. In other words, forward references to undeclared local variables are not allowed.
The runtime error is produced by this application is:
java.lang.NoSuchMethodError:
main
public
static void main(String[] args){ }
public
static void main(String args[]){ }
The formal argument list for the main() method specifies a single parameter, which is a reference to an array of references to String objects. Thus, either version shown above is acceptable. Of course, the name of the parameter (args in this case) can vary from case to case so long as it is a valid parameter name.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-