Java Advanced Placement Study Guide:  Escape Character Sequences and Arrays

Sample question:  What happens if you attempt to access a Java array element outside of the array boundaries?

Published: February 18, 2002
By Richard G. Baldwin

Questions

File JavaAP010.htm


Welcome

This is one in a miniseries of tutorial lessons designed to help you learn the essential features of Java object-oriented programming as identified by The College Board.

Purpose

The purpose of this miniseries is to help you study for, and successfully complete, the Advanced Placement Examinations designed by the College Board.

Once you understand everything in this miniseries, plus the material in the lessons that I published earlier on Java Data Structures, you should understand the Java programming features that the College Board considers essential for the first two semesters of object-oriented programming education at the university level.

Hopefully, that will help you to take and successfully complete the Advanced Placement Examinations.

Approach

These lessons provide questions, answers, and explanations designed to help you to understand the subset of Java features covered by the Java Advanced Placement Examinations (as of October, 2001).

Please see the first lesson in the miniseries entitled Java Advanced Placement Study Guide: Introduction to the Lessons, Primitive Types, for additional background information.  The lesson immediately prior to this one was entitled Java Advanced Placement Study Guide:  Logical Operations, Numeric Cast, String Concatenation, and the toString() Method.

Supplementary material

In addition to the material in these lessons, I recommend that you also study the other lessons in my extensive collection of online Java tutorials, which are designed from a more conventional textbook approach.  You will find those lessons published at Gamelan.com.  However, as of the date of this writing, Gamelan doesn't maintain a consolidated index of my Java tutorial lessons, and sometimes they are difficult to locate there.  You will find a consolidated index at Baldwin's Java Programming Tutorials.

What is Included?

Click here for a preview of the Java programming features covered by this lesson.



1.  What output is produced by the following program?
public class Ap049{
  public static void main(
                        String args[]){
    new Worker().doEscape();
  }//end main()
}//end class definition

class Worker{
  public void doEscape(){
    System.out.println(
      "\"Backslash\"->\\\nUnderstand");
  }//end doEscape()
}// end class

Answer and Explanation

2.  What output is produced by the following program?

public class Ap050{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    St[] myArray = {new St("Tom"),
                    new St("Dick"),
                    new St ("Harry")};
  for(int cnt = 0; 
           cnt < myArray.length;cnt++){
    System.out.print(
                   myArray[cnt] + " ");
    
  }//end for loop
  System.out.println("");
  }//end doArrays()
}// end class

class St{
  private String name;
  
  public St(String name){
    this.name = name;
  }//end constructor
  
  public String toString(){
    return name;
  }//end toString()
}//end class

Answer and Explanation

3.  What output is produced by the following program?

public class Ap051{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    int myArray[3][5];
    
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        myArray[i][j] = i*j;
      }//end inner for loop
    }//end outer for loop
 
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop
      System.out.println("");
    }//end outer for loop   
    
  }//end doArrays()
}// end class

Answer and Explanation

4.  What output is produced by the following program?

public class Ap052{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    int myArray[][];
    myArray = new int[3][5];
    
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        myArray[i][j] = i*j + 1;
      }//end inner for loop
    }//end outer for loop
 
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop
      System.out.println("");
    }//end outer for loop   
    
  }//end doArrays()
}// end class

Answer and Explanation

5.  What output is produced by the following program?

public class Ap053{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    int myArray[][];
    myArray = new int[3][5];
    
    for(int i = 0;i < 3;i++){
      for(int j = 0;j < 5;j++){
        myArray[i][j] = (i*j+1)*(-1);
      }//end inner for loop
    }//end outer for loop
 
    for(int i = 0;i < 3;i++){
      for(int j = 0;j < 6;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop
      System.out.println("");
    }//end outer for loop   
    
  }//end doArrays()
}// end class

Answer and Explanation

6.  What output is produced by the following program?

public class Ap054{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    int[] A = new int[2];   
    A[0] = 1;
    A[1] = 2;
    System.out.println(A[0] + A[1]);

  }//end doArrays()
}// end class

Answer and Explanation

7.  What output is produced by the following program?

public class Ap055{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Integer[] A = new Integer[2];   
    A[0] = new Integer(1);
    A[1] = new Integer(2);
    System.out.println(A[0] + A[1]);
  }//end doArrays()
}// end class

Answer and Explanation

8.  What output is produced by the following program?

public class Ap056{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Integer[] A = new Integer[2];   
    A[0] = new Integer(1);
    A[1] = new Integer(2);
    System.out.println(A[0].intValue()
                    + A[1].intValue());
  }//end doArrays()
}// end class

Answer and Explanation

9.  What output is produced by the following program?

public class Ap057{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Integer[] A = new Integer[2];   
    A[0] = new Integer(1);
    System.out.println(
                      A[1].intValue());
  }//end doArrays()
}// end class

Answer and Explanation

10.  Bonus Question:  What output is produced by the following program?

public class Ap058{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    int A[][] = new int[3][];
    A[0] = new int[1];
    A[1] = new int[2];
    A[2] = new int[3];
    
    for(int i = 0;i < A.length;i++){
      for(int j=0;j < A[i].length;j++){
        A[i][j] = i*j;
      }//end inner for loop
    }//end outer for loop

    for(int i=0;i<A.length;i++){
      for(int j=0;j < A[i].length;j++){
        System.out.print(
                        A[i][j] + " ");
      }//end inner for loop
      System.out.println("");
    }//end outer for loop

  }//end doArrays()
}// end class

Answer and Explanation

11.  What output is produced by the following program?

public class Ap059{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Object[] A = new Object[3];
    //Note that there is a simpler and
    // better way to do the following
    // but it won't illustrate my point
    // as well as doing it this way.
    A[0] = new String("Zero");
    A[1] = new String("One");
    A[2] = new String("Two");
    
    System.out.println(A[0] + " " +
                       A[1] + " " +
                       A[2]);
  }//end doArrays()
}// end class

Answer and Explanation

12.  What output is produced by the following program?

public class Ap060{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Object[] A = new Object[3];
    //Note that there is a simpler and
    // better way to do the following
    // but it won't illustrate my point
    // as well as doing it this way.
    A[0] = new String("Zero");
    A[1] = new Integer(1);
    A[2] = new Double(2.0);
    
    System.out.println(A[0] + "  " +
                       A[1] + "  " +
                       A[2]);
  }//end doArrays()
}// end class

Answer and Explanation

13.  What output is produced by the following program?

public class Ap061{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Object[] A = new Object[3];
    //Note that there is a simpler and
    // better way to do the following
    // but it won't illustrate my point
    // as well as doing it this way.
    A[0] = new String("Zero");
    A[1] = new Integer(1);
    A[2] = new MyClass(2.0);
    
    System.out.println(A[0] + "  " +
                       A[1] + "  " +
                       A[2]);
  }//end doArrays()
}// end class

class MyClass{
  private double data;
  
  public MyClass(double data){
    this.data = data;
  }//end constructor
}// end MyClass

Answer and Explanation

14.  What output is produced by the following program?

public class Ap062{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Object[] A = new Object[2];
    A[0] = new MyClass(1.0);
    A[1] = new MyClass(2.0);
    
    System.out.println(
      A[0].getData() + "  " +
      A[1].getData());
  }//end doArrays()
}// end class

class MyClass{
  private double data;
  
  public MyClass(double data){
    this.data = data;
  }//end constructor
  
  public double getData(){
    return data;
  }//end getData()
}// end MyClass

Answer and Explanation

15.  What output is produced by the following program?

public class Ap063{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

class Worker{
  public void doArrays(){
    Object[] A = new Object[2];
    A[0] = new MyClass(1.0);
    A[1] = new MyClass(2.0);
    
    System.out.println(
      ((MyClass)A[0]).getData() + "  "
      + ((MyClass)A[1]).getData());
  }//end doArrays()
}// end class

class MyClass{
  private double data;
  
  public MyClass(double data){
    this.data = data;
  }//end constructor
  
  public double getData(){
    return data;
  }//end getData()
}// end MyClass

Answer and Explanation



Copyright 2002, 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 (at Austin Community College in Austin, TX) 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


What is Included?

According to the subset document,

Answers and Explanations

Answer 15

C.  1.0  2.0

Back to Question 15

Explanation 15

This is an upgrade of the program from Question 14.  This program applies the proper downcast operator to the references extracted from the array of type Object before attempting to invoke the method named getData() on those references.  (For more information, see the discussion of Question 14.)

As a result of applying a proper downcast, the program compiles and runs successfully.

Answer 14

A.  Compiler Error

Back to Question 14

Explanation 14

Storing references in a generic array of type Object

This program stores references to two objects instantiated from a new class named MyClass in the elements of an array object of declared type Object.  That is OK.

Invoking a method on the references

Then the program extracts the references to the two objects and attempts to invoke the method named getData() on each of the references.  That is not OK.

Downcast is required

Because the method named getData() is not defined in the class named Object, in order to invoke this method on references extracted from an array of type Object, it is necessary to downcast the references to the class in which the method is defined.  In this case, the method is defined in the new class named MyClass (but it could be defined in an intermediate class in the class hierarchy if the new class extended some class further down the hierarchy).

Here is a partial listing of the compiler error produced by this program:

Ap062.java:17: cannot resolve symbol
symbol  : method getData  ()
location: class java.lang.Object
      A[0].getData() + "  " +
 

Answer 13

D.  None of the above.

Back to Question 13

Explanation 13

The array object of type Object in this program is capable of storing a reference to a new object instantiated from the new class named MyClass.  However, because the new class does not override the toString() method, when a string representation of the new object is displayed, the string representation is created using the version of the toString() method that is inherited from the Object class.  That causes this program to produce an output similar to the following:

Zero  1  MyClass@273d3c

Answer 12

C.  Zero  1  2.0

Back to Question 12

Explanation 12

A type-generic array object

As explained in Question 11, an array object of the type Object is a generic array that can be used to store references to objects instantiated from any class.

Storing mixed reference types

This program instantiates objects from the classes String, Integer, and Double, and stores references to those objects in the elements of an array of type Object.  Then the program accesses the references and uses them to display string representations of each of the objects.

Polymorphic behavior applies

Once again, polymorphic behavior involving overridden versions of the toString() method were involved and it was not necessary to downcast the references to their true type to display string representations of the objects.

Answer 11

C.  Zero One Two

Back to Question 11

Explanation 11

Storing references to subclass types

When you create an array object for a type defined by a class definition, the elements of the array can be used to store references to objects of that class or any subclass of that class.

A type-generic array object

All classes in Java are subclasses of the class named Object.  This program creates an array object with the declared type being type Object.  An array of type Object can be used to store references to objects instantiated from any class.

After creating the array object, this program instantiates three objects of the class String and stores references to those objects in the elements of the array.  (As I pointed out in the comments, there is a simpler and better way to instantiate String objects, but it wouldn't illustrate my point as well as doing the way that I did.)

Sometimes you need to downcast

Although an array of type Object can be used to store references to objects of any type (including mixed types), you will sometimes need to downcast those references back to their true type once you extract them from the array and attempt to use them for some purpose.

Polymorphic behavior applies here

For this case, because the toString() method is defined in the Object class and overridden in the String class, polymorphic behavior applies and it is not necessary to downcast the references to type String in order to be able to convert them to strings and display them.

Answer 10

C.  0
    0 1
    0 2 4

Back to Question 10

Explanation 10

Apparently, the concepts illustrated by this program are not included in the AP CS exam.  Therefore, it is identified as a Bonus Question.

Defer size specification for secondary arrays

It is not necessary to specify the sizes of the secondary arrays when you create a multi-dimensional array in Java.  Rather, since the elements in the primary array simply contain references to other array objects (or null by default), you can defer the creation of those secondary array objects until later.

Independent array objects

When you do finally create the secondary arrays, they are essentially independent array objects (except for the requirement for type commonality among them).

Ragged arrays

Each individual secondary array can be of any size, and this leads to the concept of a ragged array. (On a two-dimensional basis, a ragged array might be thought of as a two-dimensional array where each row can have a different number of columns.)

This program creates, populates, and displays the contents of such a two-dimensional ragged array.  Although this program creates a two-dimensional array that is triangular in shape, even that is not a requirement.  The number of elements in each of the secondary arrays need have no relationship to the number of elements in any of the other secondary arrays.

Answer 9

B.  Runtime Error

Back to Question 9

Explanation 9

NullPointerException

The following code fragment shows that this program attempts to perform an illegal operation on the value accessed from the array object at index 1.
 
    Integer[] A = new Integer[2];   
    A[0] = new Integer(1);
    System.out.println(
                      A[1].intValue());

You can't invoke methods on null references

The reference value that was returned by accessing A[1] is the default value of null.  This is the value that was deposited in the element when the array object was created (no other value was ever stored there).  When an attempt was made to invoke the intValue() method on that reference value, the following runtime error occurred

java.lang.NullPointerException
 at Worker.doArrays(Ap057.java:14)
 at Ap057.main(Ap057.java:6)

This is a common programming error, and most Java programmers have seen an error message involving a NullPointerException several (perhaps many) times during their programming careers.

Answer 8

C.  3

Back to Question 8

Explanation 8

Success at last

This program finally gets it all together and works properly.  In particular, after accessing the reference values stored in each of the elements, the program does something legal with those values.

Invoke methods on the object's references

In this case, the code invokes one of the public methods belonging to the objects referred to by the reference values stored in the array elements.
 
    System.out.println(A[0].intValue()
                    + A[1].intValue());

The intValue() method that is invoked, "Returns the value of this Integer as an int."  This makes it possible to perform numeric addition on the values returned by the method, so the program compiles and executes properly.

Answer 7

A.  Compiler Error

Back to Question 7

Explanation 7

Java arrays may seem different to you

For all types other than the primitive types, you may find the use of arrays in Java to be considerably different from what you are accustomed to in other programming languages.  There are a few things that you should remember.

Array elements may contain default values

If the declared type of an array is one of the primitive types, the elements of the array contain values of the declared type.  If you have not initialized those elements or have not assigned specific values to the elements, they will contain default values.

What are the default values?

Although the AP CS exam apparently doesn't test for the default values, it won't hurt you to know that:

Arrays of references

If the declared type for the array is not one of the primitive types, the elements in the array actually consist of reference variables.  Objects are never stored directly in a Java array.  Only references to objects are stored in a Java array.

If the array type is the name of a class ...

If the declared type is the name of a class, references to objects of that class or any subclass of that class can be stored in the elements of the array.

If the array type is the name of an interface ...

If the declared type is the name of an interface, references to objects of any class that implements the interface, or references to objects of any subclass of a class that implements the interface can be stored in the elements of the array.

Why did this program fail to compile?

Now back to the program at hand.  Why did this program fail to compile?  To begin with, this array was not designed to store any of the primitive types.  Rather, this array was designed to store references to objects instantiated from the class named Integer, as indicated in the following fragment.
 
    Integer[] A = new Integer[2];   

Elements initialized to null

This is a two-element array.  When first created, it contains two elements, each having a default value of null.  What this really means is that the reference variables stored in each of the two elements don't initially contain a reference to an object.

Populate the array elements

The next fragment creates two instances (objects) of the Integer class and assigns those object's references to the two elements in the array object.  This is perfectly valid.
 
    A[0] = new Integer(1);
    A[1] = new Integer(2);

You cannot add reference values

The problem arises in the next fragment.  Rather than dealing with the references to the object in an appropriate manner, this fragment attempts to access the values of the two reference variables and add those values.
 
    System.out.println(A[0] + A[1]);

The compiler produces the following error message:

Ap055.java:15: operator + cannot be applied to java.lang.Integer,java.lang.Integer
    System.out.println(A[0] + A[1]);

This error message is simply telling us that it is not legal to add the values of reference variables.

Not peculiar to arrays

This problem is not peculiar to arrays.  You would get a similar error if you attempted to add two reference variables even when they aren't stored in an array.  In this case, the code to access the values of the elements is OK.  The problem arises when we attempt to do something illegal with those values after we access them.

Usually two steps are required

Therefore, to use Java arrays with types other than the primitive types, when you access the value stored in an element of the array (a reference variable) you must perform only those operations on that reference variable that are legal for an object of that type.  That usually involves two steps.  The first step accesses the reference to an object.  The second step performs some operation on the object.

Answer 6

C.  3

Back to Question 6

Explanation 6

Once you create an array object for a primitive type in Java, you can treat the elements of the array pretty much as you would treat the elements of an array in other programming languages.  In particular, a statement such the following can be used to assign a value to an indexed element in an array referred to by a reference variable named A.
 
A[1] = 2;

Similarly, when you reference an indexed element in an expression such as the following, the value stored in the element is used to evaluate the expression.
 
System.out.println(A[0] + A[1]);

For all Java arrays, you must remember to create the new array object first and to store the array object's reference in a reference variable of the correct type.  Then you can use the reference variable to gain access to the elements in the array.

Answer 5

B.  Runtime Error

Back to Question 5

Explanation 5

Good fences make good neighbors

One of the great things about an array object in Java is that it knows how to protect its boundaries.

Unlike some other currently popular programming languages, if your program code attempts to access a Java array element outside its boundaries, an exception will be thrown.  If your program doesn't catch and handle the exception, the program will be terminated.

Abnormal termination

While experiencing abnormal program termination isn't all that great, it is better than the alternative of using arrays whose boundaries aren't protected.  Programming languages that don't protect the array boundaries simply overwrite other data in memory whenever the array boundaries are exceeded.

Attempt to access out of bounds element

The code in the for loop in the following fragment attempts to access the array element at the index value 5.  Since that index value is outside the boundaries of the array, an ArrayIndexOutOfBoundsException is thrown.  The exception isn't caught and handled by program code, so the program terminates abnormally at runtime.
 
      for(int j = 0;j < 6;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop

This program also illustrates that it is usually better to use the length property of an array to control iterative loops than to use hard-coded limit values, which may be coded erroneously.

Answer 4

C.  1 1 1 1 1
    1 2 3 4 5
    1 3 5 7 9

Back to Question 4

Explanation 4

A two-dimensional array

This program illustrates how to create, populate, and process a two-dimensional array with three rows and five columns.

(As mentioned earlier, a Java programmer who understands the fine points of the language probably wouldn't call this a two-dimensional array.  Rather, this is a one-dimensional array containing three elements.  Each of those elements is a reference to a one-dimensional array containing five elements.  That is the more general way to think of Java arrays, but the AP CS exam doesn't test for those more general concepts.)
The following code fragment creates the array, using one of the acceptable formats discussed in Question 3.
 
    int myArray[][];
    myArray = new int[3][5];

Populating the array

The next code fragment uses a pair of nested for loops to populate the elements in the array with values of type int.  This is where the analogy of a two-dimensional array falls apart.  It is much easier at this point to think in terms of a three-element primary array, each of whose elements contains a reference to a secondary array containing five elements.  (Note that in Java, the secondary arrays don't all have to be of the same size.  Hence, it is possible to create odd-shaped multi-dimensional arrays in Java.)
 
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        myArray[i][j] = i*j + 1;
      }//end inner for loop
    }//end outer for loop

Using the length property

Pay special attention to the two chunks of code highlighted in boldface, which use the length properties of the arrays to determine the number of iterations for each of the for loops.

The first boldface chunk determines the number of elements in the primary array.  In this case, the length property contains the value 3.

The second boldface chunk determines the number of elements in the secondary array that is referred to by the contents of the element at index 0 in the primary array.  In this case, the length property of the secondary array contains the value 5.

Putting data into the secondary array elements

The code interior to the inner loop simply calculates some numeric values and stores those values in the elements of the three secondary array objects.

Let's look at a picture

Here is a picture that attempts to illustrate what is really going on here.  I don't know if it will make sense to you or not, but hopefully, it won't make the situation any more confusing than it might already be.

[->]  [1][1][1][1][1]
[->]  [1][2][3][4][5]
[->]  [1][3][5][7][9]

The primary array

The three large boxes on the left represent the individual elements of the three-element primary array.  The length property for this array has a value of 3.  The arrows in the boxes indicate that the content of each of these three elements is a reference to one of the five-element arrays on the right.

The secondary arrays

Each of the three rows of five boxes on the right represents a separate five-element array object.  Each element in each of those array objects contains the int value shown.  The length property for each of those arrays has a value of 5.

Access and display the array data

The code in the following fragment is a set of two nested for loops.  In this case, the code in the inner loop accesses the contents of the individual elements in the three five-element arrays and displays those contents.  If you understand the earlier code in this program, you shouldn't have any difficulty understanding the code in this fragment.
 
    for(int i=0;i<myArray.length;i++){
      for(int j=0;
              j<myArray[0].length;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop
      System.out.println("");
    }//end outer for loop   

Answer 3

A.  Compiler Error

Back to Question 3

Explanation 3

An incorrect statement

The following statement is not the proper way to create an array object in Java.  This statement caused the program to fail to compile, producing several error messages.
 
    int myArray[3][5];

What is the correct syntax?

There are several different formats that can be used to create an array object in Java.  One of the acceptable ways was illustrated by the code used in Question 2.  Three more acceptable formats are shown below
 
    int[][] myArrayA = new int[3][5];

    int myArrayB[][] = new int[3][5];

    int myArrayC[][];
    myArrayC = new int[3][5];

Two steps are required

The key thing to remember is that an array is an object in Java.  Just like all other (non-anonymous) objects in Java, there are two steps involved in creating and preparing an object for use.

Declare a reference variable

The first step is to declare a reference variable capable of holding a reference to the object.

The second step

The second step is to create the object and to assign the object's reference to the reference variable.  From that point on, the reference variable can be used to gain access to the object.

Two steps can often be combined

Although there are two steps involved, they can often be combined into a single statement, as indicated by the first two acceptable formats shown above.

In both of these formats, the code on the left of the assignment operator declares a reference variable.  The code on the right of the assignment operator creates a new array object and returns a reference to the array object.  The reference is assigned to the new reference variable declared on the left.

A two-dimensional array object

In these two cases, the array object is a two-dimensional array object that can be thought of as consisting of three rows and five columns.

(Actually, multi-dimensional array objects in Java can be much more complex than this, but the AP CS exam does not test for the more complex forms.  In fact, although I have referred to this as a two-dimensional array object, there is no such thing as a multi-dimensional array object.  The concept of a multi-dimensional array in Java is achieved by creating single-dimensional array objects that contain references to other single-dimensional array objects.)
The square brackets in the declaration

What about the placement and the number of matching pairs of empty square brackets?  As indicated in the first two acceptable formats shown above, the empty square brackets can be next to the name of the type or next to the name of the reference variable.  The end result is the same, so you can use whichever format you prefer.

How many pairs of square brackets are required?

Also, as implied by the acceptable formats shown above, the number of matching pairs of empty square brackets must match the number of so-called dimensions of the array.  (This tells the compiler to create a reference variable capable of holding a reference to a one-dimensional array object, whose elements are capable of holding references to other array objects.)

Making the two steps obvious

A third acceptable format, also shown above, separates the process into two steps.

One statement in the third format declares a reference variable capable of holding a reference to a two-dimensional array object containing data of type int.  When that statement finishes executing, the reference variable exists, but it doesn't refer to an actual array object.  The next statement creates an array object and assigns that object's reference to the reference variable.

Answer 2

D.  Tom Dick Harry

Back to Question 2

Explanation 2

An array is an object in Java

An array is a special kind of object in Java.  An array object always has a property named length.  The value of the length property is always equal to the number of elements in the array.  Thus, a program can always determine the size of an array be examining its length property.

Instantiating an array object

An array object can be instantiated in at least two different ways:

  1. By using the new operator in conjunction with the type of data to be stored in the array.
  2. By specifying an initial value for every element in the array, in which case the new operator is not used.
This program uses the second of the two ways listed above.

Declaring a reference variable for an array object

The following code fragment was extracted from the method named doArrays().  The code to the left of the assignment operator declares a reference variable named myArray.  This reference variable is capable of holding a reference to an array object that contains an unspecified number of references to objects instantiated from the class named St (or any subclass of the class named St).
 
    St[] myArray = {new St("Tom"),
                    new St("Dick"),
                    new St ("Harry")};

Note the square brackets

You should note the square brackets in the declaration of the reference variable in the above code (the declaration of a reference variable to hold a reference to an ordinary object doesn't include square brackets).

Create the array object

The code to the right of the assignment operator in the above fragment causes the new array object to come into being.  Note that the new operator is not used to create the array object in this case.  (This is one of the few cases in Java, along with a literal String object, where it is possible to create a new object without using either the new operator or the newInstance() method of the class whose name is Class.)

Populate the array object

This syntax not only creates the new array object, it also populates it.  The new array object created by the above code contains three elements, because three initial values were provided.  The initial values are separated by commas in the initialization syntax.

Also instantiates three objects of the St class

The code in the above fragment also instantiates three objects of the class named St.  Once the array object has come into being, each of the three elements in the array contains a reference to a new object of the class St.  Each of those objects is initialized to contain the name of a student by using a parameterized constructor that is defined in the class.

The length property value is 3

Following execution of the above code, the length property of the array object will contain a value of 3, because the array contains three elements, one for each initial value that was provided.

Using the length property

The code in the following fragment uses the length property of the array object in the conditional clause of a for loop to display a String representation of each of the objects.
 
  for(int cnt = 0; 
           cnt < myArray.length;cnt++){
    System.out.print(
                   myArray[cnt] + " ");

Overridden toString method

The class named St, from which each of the objects was instantiated, defines an overridden toString() method that causes the string representation of an object of that class to consist of the String stored in an instance variable of the object.

Thus, the for loop shown above displays the student names that were originally encapsulated in the objects when they were instantiated.

The class named St

The code in the following fragment shows the beginning of the class named St including one instance variable and a parameterized constructor.
 
class St{
  private String name;
  
  public St(String name){
    this.name = name;
  }//end constructor

A very common syntax

This constructor makes use of a very common syntax involving the this reference (this syntax is not included in the AP CS exam).  Basically, this syntax says to get the value of the incoming parameter whose name is name and to assign that value to the instance variable belonging to this object whose name is also name.  Even though this syntax is not included on the exam, it is so important that I have chosen to include it here to make certain that you are exposed to it.

Initializing the object of type St

Each time a new object of the St class is instantiated, that object contains an instance variable of type String whose value matches the String value passed as a parameter to the constructor.

Overridden toString method

The overridden toString() method for the class named St is shown in the following code fragment.  This version causes the value in the String object, referred to by the instance variable named name, to be returned when it is necessary to produce a String representation of the object.
 
  public String toString(){
    return name;
  }//end toString()

Answer 1

The answer is item D, which reads as follows:

"Backslash"->\
Understand

Back to Question 1

Explanation 1

Don't confuse the compiler

If you include certain characters inside a literal String, you will confuse the compiler.  For example, if you simply include a quotation mark (") inside a literal String, the compiler will interpret that as the end of the string.  From that point on, everything will be out of synchronization.  Therefore, in order to include a quotation mark inside a literal string, you must precede it with a backslash character like this:  \"

Multiple lines

If you want your string to comprise two or more physical lines, you can include a newline code inside a String by including the following in the string:  \n

Escape character sequences

These character sequences are often referred to as escape character sequences.  Since the backslash is used as the first character in such a sequence, if you want to include a backslash in a literal string, you must do it like this:  \\

There are some other escape sequences used in Java as well.  However, they aren't included on the AP CS exam, so they won't be discussed here.



Copyright 2002, 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 (at Austin Community College in Austin, TX) 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-