What is the Vector.toString() method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed with an integer index, and the size of a Vector can be increased or decreased. Read more about Vector here.

The toString() method returns the String representation of the Vector object with the String representation of each element in the vector.

Syntax

public String toString()

Parameters

This method doesn’t take any parameters.

Return value

The toString() method returns a String as the result. The returned string contains the elements of the vector in the insertion order enclosed between [] and separated by comma(,). Internally, the elements are converted to string with the String.valueOf(Object) method.

Code

import java.util.Vector;
class ToString {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
System.out.println(vector.toString());
}
}

Explanation

  • In line number 1, we import the Vector class.

  • In line number 4, we create a new Vector object with the name vector.

  • From line numbers 5 to 7, we use the add() method to add three elements (1,2,3) to the vector object.

  • In line number 8, we use the toString() method to get the string representation of the vector object.