Java Vector add() MethodThe add() is a Java Vector class method which is used to insert the specified element in the given Vector. There are two different types of Java add() method which can be differentiated depending on its parameter. These are:
Java Vector add(int index, E element)This method is used to insert the specified element at the specified position in the given Vector. Java Vector add(E e)This method appends the specified element to the end of this vector. SyntaxFollowing is the declaration of add() method: Parameter
ReturnThe add(int index, E element) method does not return anything because its return type is void. The add(E e) method returns true if the specified element added successfully, otherwise returns false. ExceptionsArrayIndexOutOfBoundsException- This method has thrown an exception if the index is out of range. Compatibility VersionJava 1.2 and above Example 1Test it NowOutput: --Elements of Vector are-- Alphabet= A Alphabet= B Alphabet= C Alphabet= D Alphabet= E Example 2Test it NowOutput: Vector is: [Java, Android, Python, JavaTpoint, Hindi100] Example 3Test it NowOutput: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 > 3 at java.base/java.util.Vector.insertElementAt(Vector.java:619) at java.base/java.util.Vector.add(Vector.java:857) at myPackage.VectorAddExample3.main(VectorAddExample3.java:11) Example 4Test it NowOutput: Element at index: 0 Color: White Element at index: 1 Color: Green Element at index: 2 Color: Black Element at index: 3 Color: Pink New color Yellow added at first position. Element at index: 0 Color: White Element at index: 1 Color: Yellow Element at index: 2 Color: Green Element at index: 3 Color: Black Element at index: 4 Color: Pink Next TopicJava Vector |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India