Skip to content Skip to navigation Skip to collection information

OpenStax_CNX

You are here: Home » Content » Object-Oriented Programming (OOP) with Java » Ap0050: Self-assessment, Escape Character Sequences and Arrays

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Ap0050: Self-assessment, Escape Character Sequences and Arrays

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Part of a self-assessment test designed to help you determine how much you know about escape character sequences and arrays in Java.

Preface

This module is part of a self-assessment test designed to help you determine how much you know about object-oriented programming using Java.

The test consists of a series of questions with answers and explanations of the answers.

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.

I recommend that you open another copy of this document in a separate browser window and use the links to under Listings to easily find and view the listings while you are reading about them.

Questions

Question 1 .

What output is produced by the program shown in Listing 1 ?

Note:

A. Compiler Error
B. Runtime Error
C. \"Backslash\"->\\\nUnderstand
D. "Backslash"->\ 
   Understand
1
Listing 1: Listing for Question 1.
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

Question 2

What output is produced by the program shown in Listing 2 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. St@273d3c St@256a7c St@720eeb
  • D. Tom Dick Harry
  • E. None of the above
2
Listing 2: Listing for Question 2.
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

Question 3

What output is produced by the program shown in Listing 3 ?

Note:

A.  Compiler Error
B.  Runtime Error
C.  0 0 0 0 0
    0 1 2 3 4
    0 2 4 6 8
D.  None of the above
3
Listing 3: Listing for Question 3.
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

Question 4

What output is produced by the program shown in Listing 4 ?

Note:

A.  Compiler Error
B.  Runtime Error
C.  1 1 1 1 1
    1 2 3 4 5
    1 3 5 7 9
D.  None of the above
4
Listing 4: Listing for Question 4.
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

Question 5

What output is produced by program shown in Listing 5 ?

Note:

A.  Compiler Error
B.  Runtime Error
C.  -1 -1 -1 -1 -1
    -1 -2 -3 -4 -5
    -1 -3 -5 -7 -9
D.  None of the above
5
Listing 5: Listing for Question 5.
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

Question 6

What output is produced by program shown in Listing 6 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. 3
  • D. None of the above
6
Listing 6: Listing for Question 6.
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

Question 7

What output is produced by program shown in Listing 7 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. OK
  • D. None of the above
7
Listing 7: Listing for Question 7.
import java.awt.Label;
public class Ap055{
  public static void main(
                        String args[]){
    new Worker().doArrays();
  }//end main()
}//end class definition

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

Answer and Explanation

Question 8

What output is produced by program shown in Listing 8 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. OK
  • D. None of the above
8
Listing 8: Listing for Question 8.

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

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

Answer and Explanation

Question 9

What output is produced by program shown in Listing 9 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. 1
  • D. None of the above
9
Listing 9: Listing for Question 9.
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

Question 10

What output is produced by program shown in Listing 10 ?

Note:

A.  Compiler Error
B.  Runtime Error
C.  0
    0 1
    0 2 4
D.  None of the above
10
Listing 10: Listing for Question 10.
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

Question 11

What output is produced by the program shown in Listing 11 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. Zero One Two
  • D. None of the above
11
Listing 11: Listing for Question 11.
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

Question 12

What output is produced by program shown in Listing 12 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. Zero 1 2.0
  • D. None of the above.
12
Listing 12: Listing for Question 12.
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

Question 13

What output is produced by program shown in Listing 13 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. Zero 1 2.0
  • D. None of the above.
13
Listing 13: Listing for Question 13.
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

Question 14

What output is produced by program shown in Listing 14 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. 1.0 2.0
  • D. None of the above.
14
Listing 14: Listing for Question 14.
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

Question 15

What output is produced by program shown in Listing 15 ?

  • A. Compiler Error
  • B. Runtime Error
  • C. 1.0 2.0
  • D. None of the above.
15
Listing 15: Listing for Question 15.
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

Listings

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the listings while you are reading about them.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Ap0050: Self-assessment, Escape Character Sequences and Arrays
  • File: Ap0050.htm
  • Originally published: 2002
  • Published at cnx.org: 12/03/12
  • Revised: 01/02/13

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Answers

Answer 15

C. 1.0 2.0

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

Back to Question 15

Answer 14

A. Compiler Error

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.

Calling a method on the references

Then the program extracts the references to the two objects and attempts to call 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 call 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:

Note:
Ap062.java:15: error: cannot find symbol
      A[0].getData() + "  " +
          ^
  symbol:   method getData()
  location: class Object

Back to Question 14

Answer 13

D. None of the above.

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

Back to Question 13

Answer 12

C. Zero 1 2.0

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 those object's references 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.

Back to Question 12

Answer 11

C. Zero One Two

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 those object's references 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 and references to other array objects) , 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, however, 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.

Back to Question 11

Answer 10

Note:

C.  0
    0 1
    0 2 4

Explanation 10

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.

Back to Question 10

Answer 9

B. Runtime Error

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.

Note:
    Integer[] A = new Integer[2];   
    A[0] = new Integer(1);
    System.out.println(
                      A[1].intValue());

You can't call 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 call the intValue method on that reference value, the following runtime error occurred

Note:
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.

Back to Question 9

Answer 8

C. OK

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.

Call methods on the object's references

In this case, the code calls one of the public methods belonging to the objects referred to by the reference values stored in the array elements.

Note:
System.out.println(A[0].getText() + A[1].getText());

The getText method that is called, returns the contents of the Label object as type String . This makes it possible to perform String concatenation on the values returned by the method, so the program compiles and executes properly.

Back to Question 8

Answer 7

A. Compiler Error

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.

The default values

You need to know that:

  • The default for numeric primitive types is the zero value for that type
  • The default for the boolean type is false
  • The default for the char type is a 16-bit unsigned integer, all of whose bits have a zero value (sometimes called a null character)
  • The default value for reference types is null , not to be confused with the null character above. (An array element that contains null doesn't refer to an object.)

Arrays of references

If the declared type for the array is not one of the primitive types, the elements in the array are actually 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 Label , as indicated in the following fragment.

Note:
    Label[] A = new Label[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 values stored in each of the two elements don't initially refer to any object.

Populate the array elements

The next fragment creates two instances (objects) of the Label class and assigns those object's references to the two elements in the array object. This is perfectly valid.

Note:
    A[0] = new Label("O");
    A[1] = new Label("K");

You cannot add reference values

The problem arises in the next fragment. Rather than dealing with the object's references in an appropriate manner, this fragment attempts to access the text values of the two reference variables and concatenate those values.

Note:
    System.out.println(A[0] + A[1]);

The compiler produces the following error message:

Note:

Ap055.java:14: error: bad operand types for binary operator '+'
    System.out.println(A[0] + A[1]);
                            ^
  first type:  Label
  second type: Label
1 error

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 good. The problem arises when we attempt to do something illegal with those values after we access them.

Usually two steps are required

Therefore, except in some special cases such as certain operations involving the wrapper classes, 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.

Back to Question 7

Answer 6

C. 3

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 .

Note:
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.

Note:
System.out.println(A[0] + A[1]);

For all Java arrays, you must remember to create the new array object 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.

Back to Question 6

Answer 5

B. Runtime Error

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. That index value is out of bounds of the array.

Note:
      for(int j = 0;j < 6;j++){
        System.out.print(
                  myArray[i][j] + " ");
      }//end inner for loop

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

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.

Back to Question 5

Answer 4

Note:

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

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

The following code fragment creates the array, using one of the acceptable formats discussed in Question 3 .

Note:
    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 .

Note:
    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

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

Using the length property

Pay special attention to the two chunks of code that use the length properties of the arrays to determine the number of iterations for each of the for loops.

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

The second 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. (Think carefully about what I just said.)

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.

Note:
[->]  [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 another pair of nested for loops.

Note:
    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

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.

Back to Question 4

Answer 3

A. Compiler Error

Explanation 3

An incorrect statement

The following statement is not the proper way to create an array object in Java.

Note:
     int myArray[3][5];

This statement caused the program to fail to compile, producing several error messages.

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.

Note:
    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 the array object's reference. The reference is assigned to the new reference variable declared on the left.

A two-dimensional array object

In the code fragments shown above, 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. 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 in Java. The concept of a multi-dimensional array in Java is achieved by creating a tree structure of 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.

Back to Question 3

Answer 2

D. Tom Dick Harry

Explanation 2

An array is an object in Java

An array is a special kind of object in Java. Stated differently, all array structures are encapsulated in objects in Java. Further. all array structures are one-dimensional. I often refer to this special kind of object as an array object .

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().

Note:
    St[] myArray = {new St("Tom"),
                    new St("Dick"),
                    new St ("Harry")};

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

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.

Note:
  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.

Note:
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 reference named this . 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 .

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.

Note:
  public String toString(){
    return name;
  }//end toString()

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.

Back to Question 2

Answer 1

The answer is item D, which reads as follows:

Note:

"Backslash"->\ 
Understand

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. You would do well to learn how to use them before going to an interview for a job as a Java programmer.

Back to Question 1

-end-

Collection Navigation

Content actions

Download:

Collection as:

EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add:

Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks