JavaTest Your Java Knowledge: Fundamentals, Part 6

Test Your Java Knowledge: Fundamentals, Part 6

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


Questions

Lesson 6


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.  True or false?  Because all parameters are passed by value in Java, methods in Java are incapable of modifying the values stored in original objects passed into a method.

Answer and Explanation
 

2.  Given the code in the following simple program, which of the following will be displayed by the program?

  • A.  12 1
  • B.  12 12
//File Q59.java
class Q59{
  String myString = “1”;//instance var  
  
  public static void main(
                        String args[]){
    Q59 myObj = new Q59();
    myObj.stringModifier(
                       myObj.myString);
    System.out.println(” ” + 
                       myObj.myString);
  }//end main()
    
  void stringModifier(
                     String theString){
    //concatenate
    theString = theString + “2”;
    System.out.print(theString);
  }//end stringModifier
}//end class Q59

Answer and Explanation

3.  What output is produced by the following program?  Note that the instance variable named x is declared private.

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  10
//File Q57.java
class Q57{
  public static void main(
                        String args[]){
    AClass ref1 = new AClass(5);
    AClass ref2 = new AClass(10);

    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 getAndShow(AClass ref){
    System.out.print(ref.x + ” “);
  }//end getAndShow()

}//end class AClass

Answer and Explanation

4.  True or false?  As a consequence of automatic garbage collection, the problem of “memory leaks” prevalent in C and C++ is completely eliminated in Java.

Answer and Explanation

5.  How can you prevent the kind of memory leaks described in the previous question?

Answer and Explanation

6.  True or false?  Execution of System.gc() or Runtime.gc() will force garbage collection to take place.

Answer and Explanation

7.  True or false?  The range of values for the primitive byte type is from -128 to +128.
Answer and Explanation
 

8.  Select the valid identifiers from the following list:

  • A. ThisIs01LongIdentifierJustForShow
  • B. $ThisIsAnotherIdentifier
  • C. _HereIsAnother
  • D. 2beOrNot2beIsTheQuestion
  • E. recommendedVariableNameStyle
  • F. recommendedMethodNameStyle
  • G. RecommendedClassNameStyle
  • H. RecommendedInterfaceNameStyle

Answer and Explanation
 

9.  What output is produced by the following program?

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  5
  • D.  10
//File Q61.java
class Q61{
   public static void main(
                        String args[]){
     MyClass refToObj = new MyClass();
     refToObj.instanceVar = 5;
     refToObj.addFive(refToObj);
     System.out.println(
                 refToObj.instanceVar);
   }//end main()
 }//end Q61

 class MyClass{
   int instanceVar;
   void addFive(MyClass param){
     param.instanceVar+=5;
   }//end addFive()
 }//end MyClass

Answer and Explanation

10.   What output is produced by the following program?

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  5
  • D.  10
//File Q62.java
class Q62{
  public static void main(
                        String args[]){
    int localVar = 5;
    MyClass refToObj = new MyClass();
    refToObj.addFive(localVar);
    System.out.println(localVar);
  }//end main()
}//end class Q62

class MyClass{
  public void addFive(int param){
    param += 5;
  }//end addFive
}//end class MyClass

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

C.  5

Back to Question 10

Explanation 10

This problem illustrates another extremely important concept in Java.  In particular, because all variables are passed by value, although the code in a method can change the value of the copy of the variable that is passed to the method, it cannot change the value stored in the original variable.  In this case, a copy of a local variable is passed to a method named addFive().  The method adds five to the copy.  However, when the value stored in the local variable is displayed after return from the method, its value hasn’t changed.  Only the copy was changed.

Answer 9

D.  10

Back to Question 9

Explanation 9

This problem illustrates an extremely important concept in Java programming.  In particular, even though all variables are passed by value (meaning that a copy of the variable is passed to a method), if you pass a copy of a reference variable to a method, that method can use the copy to gain access to the object.  In this case, a copy of a reference to an object is passed to the method named addFive().  The method uses the copy of the reference to gain access to an instance variable in the object to which the reference refers, and to add five to the value stored in that instance variable.

Answer 8

All but D are valid.

Back to Question 8

Explanation 8

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 the character (_) and the dollar sign ($) are considered letters and may be used as any character including the first one.

Answer 7

False.

Back to Question 7

Explanation 7

That this is false can be easily demonstrated by running the following simple program.
 

//File Q58.java
class Q58{
  public static void main(
                        String args[]){
    System.out.println(Byte.MAX_VALUE);
    System.out.println(Byte.MIN_VALUE);
  }//end main()
}//end class Q58

The output from this program is:
-128 127

The following Java types are signed integers that use two’s complement notation:  byte, short, int, and long.

It is a characteristic of two’s complement notation that the largest magnitude that can be accommodated for negative integers is greater (by one) than the largest magnitude that be accommodated for positive integers.  For example, here are the ranges for the other integer types:

short:
-32768
 32767

int:
-2147483648
 2147483647

long:
-9223372036854775808
 9223372036854775807
 

Answer 6

Apparently false.

Back to Question 6

Explanation 6

According to Roberts, “It is not possible to force garbage collection reliably…Even these (methods) cannot be relied upon in general (to force garbage collection), since some other thread might prevent the garbage thread from running.”

Here is what Sun has to say about the method System.gc():

“Runs the garbage collector.  Calling the gc method suggests that the Java Virtual Machine expend effort toward  recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call: Runtime.getRuntime().gc()

Answer 5

Purposely assign null to all reference variables that refer to an object when you no longer need that object.

Back to Question 5

Explanation 5

An object becomes eligible for garbage collection when there are no live references to the object.

As an extreme case, consider the following example.  Assume that you instantiate an array object, populate it with 500 references to very large String objects, and assign the reference to the array object to an ordinary reference variable.

Assume further that this array object is instantiated in the main() method and that the reference is assigned to a local variable in main() so that the reference variable containing the reference to the array object won’t go out of scope until the program terminates.

When you no longer need access to those string objects, you should assign null to the reference variable containing the reference to the array object.  This will cause the array object and all of the String objects referred to by the elements in the array to become eligible for garbage collection.  Otherwise, they will continue to occupy memory until the program terminates.

When an object containing references to other objects becomes eligible for garbage collection, the objects to which it refers also become eligible for garbage collection (assuming there are no other live references to those objects).

The truth of this can be easily demonstrated by running the following program.
 

//File Q60.java
class Q60{
  static int count = 0;
  
  public void finalize(){
    System.out.print(++count + ” “);
  }//end finalize
  
  public static void main(
                        String[] args){
    //Instantiate 5-element array obj
    Q60[] var = new Q60[5];
    
    //Populate array with refs to
    // objects.
    for(int cnt = 0; cnt < var.length;
                                cnt++){
      var[cnt] = new Q60();  
    }//end for loop
    
    //Overwrite ref to array object
    var = null;
    
    //Request garbage collection
    System.gc();
    System.out.println(“Terminating”);
  }//end main
}//end class Q60

This program creates an array object containing references to five objects instantiated from the class Q60.  The Q60 class overrides the finalize() method to increment and display a counter each time an object of the class is finalized (immediately prior to garbage collection).  Assuming that the call to System.gc() succeeds in causing the garbage collector to run and to collect all eligible objects, the program output is as shown below:

1 2 3 4 5 Terminating

This illustrates that making the array object eligible for garbage collection (by overwriting its reference with null) causes all of the objects referred to in the array object to also become eligible for garbage collection and to be collected.
 

Answer 4

False.

Back to Question 4

Explanation 4

According to The Complete Java 2 Certification Guide by Roberts, Heller, and Ernest, “You can still get memory leaks.  If you allow live, accessible references to unneeded objects to persist in your programs, then those objects cannot be garbage collected.”

Answer 3

C.  10

Back to Question 3

Explanation 3

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 an instance method named 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 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.  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.

Answer 2

A. 12 1.

Back to Question 2

Explanation 2

While a method can use a copy of a reference variable to access the contents of an object, it cannot use the copy to cause the original reference variable to refer to a different object.  The stringModifier() method of this program causes the copy of the reference to refer to a new String object, (which is then displayed by the method), but does not cause the original reference variable, (which is displayed upon return to main) to refer to the new String object.  This is a fairly subtle aspect of argument passing in Java.

Answer 1

False.

Back to Question 1

Explanation 1

A copy of a reference variable is just as useful as the original reference variable for the purpose of gaining access to an object.  Therefore, a method can use a copy of the reference variable to modify values stored in an object provided access to the instance variables of the object is not prevented through the use of access-control modifiers.


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

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories