Test Your Java Knowledge

Fundamentals, Part 5

Questions

By Richard G. Baldwin

Lesson 5

October 9, 2000


Welcome

The purpose of this series of tutorial lessons is to help you learn Java by approaching it from a question and answer viewpoint.

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.



1.  What is the syntax for the main() method?

Answer and Explanation
 

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

Answer and Explanation

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

Answer and Explanation

4.  What is the purpose of the reference to the array of String references in the argument list of the main() method?

Answer and Explanation

5.  What is the lifetime and scope of a local variable in Java?

Answer and Explanation

6.  What is the lifetime and scope of an instance variable in Java?

Answer and Explanation

7.  What is the lifetime and scope of a class variable in Java?

Answer and Explanation
 

8.  True or false?  All member variables and all local variables are automatically initialized in Java.

Answer and Explanation
 

9.  Member variables are automatically initialized to default values in Java.  What are those default values.

Answer and Explanation

10.  True or false?  In Java, primitives are passed by value and objects are passed by reference.

Answer and Explanation



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

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.

baldwin.richard@iname.com



 

Answers and Explanations

Answer 10

False.

Back to Question 10

Explanation 10

All variables are passed by value in Java.  According to Roberts, when Java passes an argument into a method call, it is actually a copy of the argument that gets passed.  This rule applies to both primitive variables and reference variables.

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.
 

Answer 9

See the answer in the following explanation.

Back to Question 9

Explanation 9

Object references are automatically initialized to null.  Thus unlike pointers in C and C++, a Java object reference will either contain null, or will contain a reference to an existing object.  It is not possible for a Java object reference to "point" to an arbitrary location in memory.

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

Answer 8

False.

Back to Question 8

Explanation 8

Although member variables (class variables and instance variables) are automatically initialized, local variables are not automatically initialized.

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.

Answer 7

See the answer in the explanation below.

Back to Question 7

Explanation 7

A class variable is a variable that is declared inside a class but not inside a method.  It must be declared static.  The fact that it is declared static is what differentiates it from an instance variable.

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.

Answer 6

See the answer in the explanation below.

Back to Question 6

Explanation 6

An instance variable is a variable declared inside a class definition but not inside a method.  An instance variable is not declared static.  If it is declared static, then it is a class variable and not an instance variable.

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

Answer 5

See the answer contained in the explanation below.

Back to Question 5

Explanation 5


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.

Answer 4

Transfer of command-line arguments.

Back to Question 4

Explanation 4

The reference to the array containing references to String objects provides access to the arguments entered by the user on the command line.  Each of the String objects referenced by the elements in the array contains one of the command-line arguments.  The object containing the first command-line argument is referenced by the contents of the element at index zero.

Answer 3

B.  A runtime error.

Back to Question 3

Explanation 3

While it is not necessary that the main() method be declared public, it is necessary that it be declared static.  Declaring a member of a class static makes that member available without a requirement to instantiate an object of the class.  The virtual machine does not instantiate an object of the controlling class before starting an application.  Rather, it searches the controlling class file to find a static method named main(), and attempts to execute that method if it finds it.

The runtime error is produced by this application is:

java.lang.NoSuchMethodError: main
 

Answer 2

C.  OK

Back to Question 2

Explanation 2

According to The Complete Java 2 Certification Guide by Roberts, Heller, and Ernest, the main() method is declared public by convention, but this is not a requirement.
 

Answer 1

The syntax usually seen for the main() method is one of the following:

public static void main(String[] args){ }
public static void main(String args[]){ }

Back to Question 1

Explanation 1

The reason that there are two common formats for the main() method results from the fact that there are two ways to declare a reference to a Java array.  As we saw in an earlier lesson, when you declare a reference to an array, you can place the square brackets either after the type specification or after the name of the variable (in this case a parameter).

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.



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without  express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

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.

baldwin.richard@iname.com

-end-