JavaEnterprise JavaTest Your Java Knowledge #4: Fundamentals, Part 4

Test Your Java Knowledge #4: Fundamentals, Part 4

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


Questions

By Richard G. Baldwin

Lesson 4

September 23, 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 specifying the size of an array in Java?

Answer and Explanation

2.  What output is produced by the following program”

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  10
  • D.  20
class Q004_02{
  public static void main(
                        String args[]){
    long size = 10;
    int[] array = new int[size];
    size = 20;
    System.out.println(array.length); 
  }//end main()
}//end class definition

Answer and Explanation

3.  What output is produced by the following program”

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  10
  • D.  20
class Q004_03{
  public static void main(
                        String args[]){
    byte size = 10;
    int[] array = new int[size];
    size = 20;
    System.out.println(array.length);
  }//end main()
}//end class definition

Answer and Explanation

4.  True or false?  Element values in Java arrays are automatically initialized when the array is constructed using the new operator.

Answer and Explanation

5.  When an array of char elements is constructed, the elements are automatically initialized to which of the following values:

  • A.  ‘0’
  • B.  ‘u0000’

Answer and Explanation

6.  What output is produced by the following program”

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  30
  • D.  31
  • E.  0
  • F.  1
class Q004_06{
  public static void main(
                        String args[]){
    char[] a1 = {‘u0030′,’u0031’};
    System.out.println(a1[1]);    
  }//end main()
}//end class definition

Answer and Explanation

7.  What output is produced by the following program?  (Note the placeholder comma in the boldface portion.)

  • A.  A compiler error.
  • B.  A runtime error.
  • C.  0
class Q004_07{
  public static void main(
                        String args[]){
    char[] a1 = {‘u0030′,,’u0031’};
    System.out.println(a1[0]);    
  }//end main()
}//end class definition

Answer and Explanation

8.  What is the name of the property of an array object that always contains the size of the array and how may it be used?

Answer and Explanation

9.  True or false?  All Java applications and applets require a main() method.

Answer and Explanation

Bonus question.  The following question is considerably more difficult than the previous nine questions, and is included here to challenge you if the previous nine questions have been too easy.

10.  What output is produced by the following program?

  • A.  A compiler error
  • B.  A runtime error
  • C.  15
class Q004_10{
   public static void main(
                        String args[]){
     SubClass ref1 = new SubClass(5);
     SubClass ref2 = new SubClass(10);
     System.out.println(
                       ref1.add(ref2));
   }//end main()
 }//end class definition

 class AClass{
   private int x;
   
   AClass(int x){//constructor
     this.x = x;
   }// end constructor

 }//end class AClass

 class SubClass extends AClass{
   SubClass(int x){
     super(x);
   }//end constructor
   
   int add(AClass ref){
     return x + ref.x;
   }//end add()
   
 }//end class SubClass

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

A.  A compiler error

Back to Question 10

Explanation 10

The answer is A, the compiler error “Undefined variable: x”.

Code in a method belonging to an object of a subclass does not have direct access to private instance variables declared in the superclass, even though those variable are inherited into and belong to the object of the subclass.  Private members can only be accessed directly by an instance of the class in which they are declared.
 

Answer 9

False.

Back to Question 9

Explanation 9

The main() method is required only in Java applications.  A Java application is started when the virtual machine invokes the main() method, which is a class or static method of the controlling class.  Applets do not require a main() method because they are started in other ways by the browser that owns them.

Answer 8

The length property is always available for an array, and it always contains the size (number of elements) in the array.

Back to Question 8

Explanation 8

The following program illustrates how the length property may be used to obtain the size of an array.
 

class Q004_08{
  public static void main(
                        String args[]){
    char[] a1 = {‘a’,’b’,’c’,’d’};
    System.out.println(a1[3] + ” ” +
                            a1.length);
  }//end main()
}//end class definition

This program produces the following output, showing that the array contains four elements.

d 4

Note that although length is commonly referred to as a property of the array object, it is not a property in the sense of a JavaBean design-pattern property.  If it were, it would not be directly accessible as shown in the above program.  Rather, it would be accessible by invoking a method named getLength().  (I will have a lot more to say about JavaBean design patterns in a subsequent lesson.)

Answer 7

A.  A compiler error.

Back to Question 7

Explanation 7

The point of this question is to illustrate that if you use the initialization syntax for a Java array, you must provide all of the initial values.  In particular, you cannot simply use a comma as a placeholder in the initialization sequence and expect the array element corresponding to the location of the comma to be automatically initialized to the default value.  The compiler error in this case is simply “Missing term.”

Answer 6

F.  1

Back to Question 6

Explanation 6

This program illustrates the syntax for overriding the default initialization of array elements in order to specify the initial values for the elements in the array.  The syntax is as follows:

char[] a1 = {‘u0030′,’u0031’};

This syntax

  • Declares a reference variable to refer to an array object.
  • Instantiates the array object for a specified size (the size matches the number of initial values provided).
  • Initializes the values of each of the array elements to the specified values.

Just to make things interesting, this program also uses the unicode hexadecimal notation to initialize the two array elements to values corresponding to the characters ‘0’ and ‘1’.  This is how you can specify the values for unicode characters for which there are no corresponding character keys on your keyboard.

Answer 5

B.  ‘u0000’.

Back to Question 5

Explanation 5

The type char is an unsigned integer type, and its value is initialized to numeric zero (sixteen bits, all with zero value) rather than the value for the character zero.

This is easily demonstrated by the following simple program.
 

class Q004_05{
  public static void main(
                        String args[]){
    char[] a1 = new char[1];
    System.out.println((int)a1[0] + ” ”
                       + (int)’0′ + ” ”
                       + (int)’1′);
  }//end main()
}//end class definition

This program produced the following output:

0 48 49

This output resulted from casting three values to type int and displaying the three values.

The first value displayed was the value that was placed in the array element of type char through array initialization.  As you can see, the value was 0.  It was necessary to cast this to type int in order to display it because there is no displayable character associated with the unicode character with a value of 0.

The next two values displayed were the unicode values for the characters ‘0’ and ‘1’.  These values were displayed simply to demonstrate that the unicode value for the character ‘0’ is not numeric zero, but instead is numeric 48.

Answer 4

True.

Back to Question 4

Explanation 4

Instance variables in an ordinary object and element values in an array object are automatically initialized to default values when the object is instantiated.  (Of course, in an ordinary object, the default initialization can be can be overridden in a couple of different ways.)

The default values are:

  • false for boolean
  • zero value for numeric
  • null for object reference

This is easily demonstrated by the following program.
 

class Q004_04{
  public static void main(
                        String args[]){
    int[] a1 = new int[1];
    float[] a2 = new float[1];
    boolean[] a3 = new boolean[1];
    String[] a4 = new String[1];

    System.out.print(a1[0] + ” ” +
                     a2[0] + ” ” +
                     a3[0] + ” ” +
                     a4[0] + ‘n’);    
  }//end main()
}//end class definition

This program displays the default value for one element from each of the four arrays and produces the following output:

0 0.0 false null

Answer 3

C. 10

Back to Question 3

Explanation 3

It is allowable to use a variable of type byte, short, or int to specify the size of an array.  It is important to understand, however, that once the value stored in a variable is used to establish the size of the array, changing the value stored in the variable does not cause the size of the array to change.

Answer 2

A.  A compiler error.

Back to Question 2

Explanation 2

The compiler error is as follows:

Incompatible type for new. Explicit cast needed to convert long to int.

While it is allowable to use a variable of type byte, short, or int to specify the size of an array, you cannot specify the size of an array using a variable of type long.

Answer 1

String[] args = new String[15];
 

Back to Question 1

Explanation 1

The syntax for specifying the size of an array in Java consists of applying the new operator to the name of the type of data to be stored in the array and providing the size as an integer in square brackets.

Note that an array is a special kind of object in Java, and instantiation of an array object is similar to, but different from the instantiation of an ordinary object.  For example, the code to instantiate an ordinary String object might be as follows:

String myVar = new String(“Data”);

Note the differences:

  • The array object is instantiated using square brackets whereas the ordinary object is instantiated using parentheses.
  • For an array object, the new operator is applied to the type of the array whereas for an ordinary object, the new operator is applied to the constructor for the class from which the object is being instantiated.

When instantiating an array object, you can specify the size using either a literal integer value, or a variable.  


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