A good answer might be:

The compete program is below.

Completed Program

The counting loop uses the size() method to ensure that every element is accessed. A Vector has data in slots 0 to size()-1.

import java.util.* ;

class VectorEg
{

  public static void main ( String[] args)
  {
    Vector names = new Vector( 10 );

    names.addElement( "Amy" );
    names.addElement( "Bob" );
    names.addElement( "Chris" );
    names.addElement( "Dan" );
    names.addElement( "Elaine" );
    names.addElement( "Fred" );

    for ( int j=0; j < names.size(); j++ )
      System.out.println( j + ": " + names.elementAt(j) ); 

  }
}

In most programs, the size of the Vector changes as the program executes. For bug-free code, use size() so that the loop always works.

QUESTION 10:

Examine the following program. What will it print?


import java.util.* ;
class VectorEg
{
  public static void main ( String[] args)
  {
    Vector names = new Vector( 10 );

    names.addElement( "Amy" );
    names.addElement( "Bob" );
    names.addElement( "Chris" );

    names.setElementAt( "Zoe", 0 );
    names.setElementAt( "Bart", 1 );

    for ( int j=0; j < names.size(); j++ )
      System.out.println( j + ": " + names.elementAt(j) ); 

  }
}