Java Vector clear( ) Method with Example

In the previous article, we have discussed about Java Vector size( ) Method with Example

In this article, we are going to see the use of Java Vector clear() method along with examples.

Java Vector clear( ) Method with Example

This java.util.Vector.clear() method removes all elements from the vector. Its return type is void.

Syntax:

vectorName.clear( );

Where,

  • vectorName refers to the name of the Vector.

Approach:

  • Create a vector of string data type and add some elements to it.
  • Print the elements.
  • Now using clear( ) method remove all elements from the vector.
  • Print the vector elements after remove all elements.

Program:

import java.util.*;
public class Main
{
   public static void main(String[] args) 
   {
       // Create a Vector of string datatype
       Vector<String> vec = new Vector<String>();
       // Adding some elements to the vector
       vec.add("One");
       vec.add("Two");
       vec.add("Three");
       vec.add("Four");
       vec.add("Five");
       vec.add("Six");
       vec.add("Seven");
       // Prints the vector elements
       System.out.println("The vector elements are "+vec);
       // Clearing all elements from the vector
       vec.clear();
       // Prints the vector elements
       System.out.println("The vector elements after clear() are "+vec);
   }
}
Output:

The vector elements are [One, Two, Three, Four, Five, Six, Seven]
The vector elements after clear() are []

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs: