Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to calculate time difference in Java How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java

Vector in Java

Java Vector Class

The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of a Vector can grow or shrink as required to add and remove items after the Vector created.

Vectors are similar to ArrayList, but Vector is synchronized. It implements the List interface and extends AbstractList.

Vector tries to optimize storage by maintaining a capacity and capacityIncrement. Always, the capacity at least as large as the size of the vector. To reduce the amount of incremental reallocation, the methods usually increases the capacity of a vector before inserting a large number of elements.

Java Vector Fields:

capacityIncrement It increases the capacity of the vector automatically when its size becomes greater than its capacity.
elementCount It returns the valid components in this vector object.
elementData The components of the vector are stored in this array buffer.

Constructors of Vector and its usages:

Vector() It constructs an empty vector with size 10 and with zero standard capacity increment.
Vector(Collection c) It creates a vector with elements of the specified collection in the arguments; in the order, they are returned by the collection’s iterator.
Vector(int initialCapacity) It constructs an empty vector with specified initial capacity in the argument, with capacity increment equals to zero.
Vector(int initialCapacity, int capacityIncrement) It constructs an empty vector with specified initial capacity and capacity increment.

Methods of Java Vector and their usages:

Modifier and Data type Methods Description
Boolean add(E e) It adds the specific element to the end of the Vector
addAll(Collection c) It will add all the elements in the specified collection to the end of the Vector, in the same order as it is in the specified collection.
addAll(int index, Collection c) It adds all the elements in the vector from the specified collection at the specified index position in the arguments.
contains (Object o) It will return true if the specified element present in the vector
containsAll(Collection c) Will return true if all the elements in the specified collection are present in the vector.
equals(Object o) It will compare the specified object with the vector for equality.
isEmpty() Used to test if the vector has no components.
remove(Object o) It will delete the first occurrence of the specified element in the vector. In case the element is not present, then status will be unchanged.
removeAll(Collection c) Removes all the Vector elements that are present in the specified collection.
removeElement(Object obj) It will remove the first occurrence (from lowest index) of the argument from the vector
retainAll(Collection c) It will keep only the elements in the vector that are contained in the specified Collection.
int capacity() It will return the current capacity of the vector.
hashCode() It returns the hash value of the vector.
indexOf(Object o) It will return the index of the first occurrence of the element specified in the argument or returns –ve one if the element is not present in the vector.
indexOf(Object o, int index) It will return the index of the first occurrence of the element specified in the argument, searching forward from index or return -1 if the element is not present in the vector.
lastIndexOf(Object o) It will return the index of the last occurrence of the element specified in the argument or -1 if the element is not in the vector.
lastIndexOf(Object o, int index) It also returns the last occurrence of the element specified in the argument but searching backward from the index or it returns -1 if the vector does not contain the specified element.
Size( ) Used to get the number of elements present in the vector.
void add(int index, E element) It will insert the specified element at the specified position in the vector.
addElement(E obj) It appends the specified component at the end of the vector, increasing its size by 1.
clear() Used to remove the elements from the vector.
copyInto(object[] anArray) It will copy the elements of the vector to the specified array.
ensureCapacity(int minCapacity) Used to increase the capacity of the vector if necessary, to ensure that it holds the number of elements specified by the minCapacity argument.
insertElementAt(E obj, int index) Used to insert the specified object as an element in the vector at the specified index position.
removeAllElements() Removes all elements from the vector and set the size to zero.
removeElementAt(int index) It deletes the element at the specified index location.
removeRange(int fromIndex, int toIndex) Used to remove all the element from the list whose index is between fromIndex(inclusive) and toIndex(exclusive).
setElementAt(E obj, int index) Used to set the element at the specified index of this vector to be the specified object.
setSize(int newSize) It sets the size of the vector to the specified argument.
trimToSize() It will trim the capacity of the vector to be the vectors current size.
Object clone() Used to clone the vector/exact copy of the vector
toArray() It always returns an array containing all the values in the vector in the sequence.
String toString() It returns an array that contains all the elements in the vector in the correct order.
E elementAt(int index) It returns the elements at the specified index.
firstElement() It returns the first element of the vector (item at index 0).
get(int index) It will return the values at the specified position in the vector.
lastElement() It will return the last element of the vector.
remove(int index) It is used to remove the element from the specified position in the vector.
set(int index, E element) It will replace the element at the specified position in the vector with specified elements in the argument.
Enumeration elements() It will return an enumeration of the elements of this vector.
Iterator iterator() Always returns an iterator over the elements in the list in proper sequence.
ListIterator listIterator() It always returns a ListIterator over the values in the list (in sequence).
ListIterator listIterator(int index) It always returns a list iterator over the elements in the list, starting at the specified position
List sublist(int fromIndex, int toIndex) It will return a view of the area of the list between the starting and ending specified index position.
T[] toArray(T[] a) It returns an array that contains all the elements of the vector in the sequential order, and the runtime type of the returned array is that of the specified array.

Example to illustrate add() method.

import java.util.*;
 class Add_demo {
  public static void main(String[] arg)
  {
   // creating default vector 
   Vector a = new Vector();
  //adding element to the vector using add()
   a.add("Learn");
   a.add("Tutorials");
   a.add("And");
   a.add("Examples");
   System.out.println("Vector is: " + a);
  }
 } 

Output:

Vector is:  [Learn, Tutorials, And, Examples]

Example to illustrate addAll(Collection c) method.

 import java.util.*;
 class add_demo {
  public static void main(String[] arg)
  {
   ArrayList ar = new ArrayList();
   ar.add("Tutorials");
   ar.add("And");
   ar.add("Examples");
   // creating default vector
   Vector v = new Vector();
   // copying all elements of array list into vector
   v.addAll(ar);
   // checking vector v
   System.out.println("vector v:" + v);
  }
 } 

Output:

vector v:[Tutorials, And, Examples]

Example to Demonstrate addAll(int index, Collection c) method.

 import java.util.*;
 class add_demo2 {
  public static void main(String[] arg)
  {
   ArrayList ar = new ArrayList();
   ar.add("Learn");
   ar.add("Tutorials");
   ar.add("And");
   ar.add("Examples");
   // creating default vector
   Vector v = new Vector();
   v.add("Java Vector");
   // copying all element of arraylist into vector
   v.addAll(1, ar);
   // printing vector
   System.out.println("vector v:" + v);
  }
 } 

Output:

vector v:[Java Vector, Learn, Tutorials, And, Examples]

Example to illustrate contains() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  // creating default vector 
  Vector v = new Vector();  
  v.add("Java"); 
  v.add("OOPS"); 
  v.add("Hibernate"); 
  v.add("Spring"); 
  v.add("Servlet"); 
  // checking whether vector contains "HIbernate" or not  
  if (v.contains("Hibernate")) 
  System.out.println("Hibernate exists in the List"); 
  } 
 } 

Output:

Hibernate exists in the List

Example to illustrate containsAll() method.

import java.util.*; 
 public class Demo { 
  public static void main(String arg[]) { 
  //Creating an empty Vector  
  Vector vc = new Vector(); 
  //Adding elements in the vector 
  vc.add("Java"); 
  vc.add("Spring");  
  vc.add("boot"); 
  vc.add("hibernate"); 
  //Creating an empty list 
  List list = new ArrayList();  
  //Adding elements in the ArrayList 
  list.add("Java"); 
  list.add("hibernate"); 
  //checking if the vector contain the item present in the arraylist 
  System.out.println("Vector contains all the list item.- "+vc.containsAll(list));
  //adding one more unique element to the list
  list.add("Ajax"); 
  //checking again for the presence of element
  System.out.println("Vector contains all the list item.- "+vc.containsAll(list)); 
  } 
 } 

Output:

Vector contains all the list item.- true
Vector contains all the list item.- false 

Example to illustrate equals() method

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  // creating default vector  
  Vector v = new Vector(); 
  v.add("Java"); 
  v.add("Spring"); 
  v.add("Hibernate"); 
  v.add("Jquery");  
  v.add("Servlet"); 
  // creating second vector 
  Vector v_second = new Vector(); 
  v_second.add("Java"); 
  v_second.add("Spring"); 
  v_second.add("Hibernate");  
  v_second.add("Servlet"); 
  v_second.add("Jquery"); 
  //checking if both the vectors have same elements
  if (v.equals(v_second)) 
  System.out.println("both vectors are equal"); 
  else 
   System.out.println("Vectors are not equal"); 
  } 
 } 

Output:

Vectors are not equal

Example to illustrate isEmpty() method.

import java.util.*; 
 class IsEmptyDemo { 
  public static void main(String[] arg) 
  { 
  // creating default vector 
  Vector v = new Vector();  
  v.add(1); 
  v.add(2); 
  v.add(3); 
  v.add(4); 
  v.add(5); 
  v.clear();  
  // checking whether vector is empty or not 
  if (v.isEmpty()) 
  System.out.println("Vector is empty"); 
  } 
 } 

Output:

Vector is empty

Example to illustrate remove() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  // create default vector of capacity 10 
  Vector v = new Vector();  
  v.add("A"); 
  v.add("B"); 
  v.add("C"); 
  v.add("D"); 
  v.add("E");  
  // removing element from 1st index position 
  v.remove(1); 
  // checking vector 
  System.out.println("after removal: " + v); 
  } 
 } 

Output:

after removal: [A, C, D, E]

Example to illustrate removeElement() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  Vector v = new Vector(5);
  //using add() method to add elements 
  v.add("Java"); 
  v.add("Android"); 
  v.add("Spring"); 
  v.add("Pyhton"); 
  v.add("MongoDB"); 
  // removing an element from vector  
  v.removeElement("Java"); 
  // checking vector 
  System.out.println("Vector after removal: " + v); 
  } 
 } 

Output:

Vector after removal: [Android, Spring, Pyhton, MongoDB]

Example to illustrate retainAll() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  Vector v = new Vector(5); 
  Vector vretain = new Vector();  
  // using add() method to add elements
  v.add("Java"); 
  v.add("Spring"); 
  v.add("AI"); 
  v.add("MongoDB"); 
  v.add("Oracle");  
  // these elements will be retained 
  vretain.add("Java"); 
  vretain.add("Oracle"); 
  vretain.add("Spring"); 
  System.out.println("Calling retainAll()");  
  v.retainAll(vretain); 
  //printing all the elements available in vector 
  System.out.println("Elements after removal :- "); 
  //using iterator to return the elements in the sequence they are present int the vector v 
  Iterator itr = v.iterator(); 
  while (itr.hasNext()) { 
  System.out.println(itr.next()); 
  } 
  } 
 } 

Output:

Calling retainAll()
 Elements after removal :- 
 Java
 Spring
 Oracle 

Example to illustrate capacity() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  Vector v = new Vector(); 
  // using add() to add elements in the vector 
  v.add("A");  
  v.add("B"); 
  v.add("C"); 
  v.add("D"); 
  v.add("E");  
  // printing the capacity of vector v 
  System.out.println("Capacity of vector is: " + v.capacity()); 
  } 
 } 

Output:

Capacity of vector is: 10
//The output is 10 because the default capacity of a vector is 10. 

Example to illustrate hashCode() method.

import java.util.*; 
 class Demo { 
  public static void main(String[] arg) 
  { 
  Vector v = new Vector(5); 
  // using add() to add elements in the vector 
  v.add(1);  
  v.add(2); 
  v.add(3); 
  v.add(4); 
  v.add(5);  
  // checking hash code 
  System.out.println("Hash code: " + v.hashCode()); 
  } 
 } 

Output:

Hash code: 29615266

Example to illustrate indexOf() method.

import java.util.*; 
 class Demo {  
  public static void main(String[] arg)  
  {  
  // create default vector of capacity 10  
  Vector v = new Vector();  
  v.add("PL/Sql");  
  v.add("Sql");  
  v.add("MongoDB");  
  v.add("Oracle");  
  v.add("MySql");  
  // get the element at index of Geeks  
  System.out.println("Index of Oracle is: " + v.indexOf("Oracle"));  
  }  
 } 

Output:

Index of Oracle is: 3

Example to illustrate lastIndexof() method.

import java.util.*; 
 class Demo {  
  public static void main(String[] arg)  
  {  
  // create default vector of capacity 10  
  Vector v = new Vector();  
  v.add(1);  
  v.add(2);  
  v.add(5);  
  v.add(5);  
  v.add(2);  
  // checking last occurance of 5  
  System.out.println("Last occurrence of 5 is: " + v.lastIndexOf(5));  
  }  
 } 

Output:

Last occurrence of 5 is: 3

Example to illustrate size() method.

import java.util.*; 
 class Demo {  
  public static void main(String[] arg)  
  {  
  // creating default vector  
  Vector v = new Vector();  
  v.add("Java"); 
  v.add("Python"); 
  v.add("MongoDB"); 
  v.add("Oracle"); 
  v.add("Ruby");  
  // Printing size of vector 
  System.out.println(" Size of vector: " + v.size()); 
  } 
 } 

Output:

Size of vector: 5

Example to illustrate add(int index, Object obj) method.

import java.util.*; 
 class Demo {  
  public static void main(String[] arg)  
  {  
  // create default vector  
  Vector v = new Vector(); 
  v.add(0, "India"); 
  v.add(1, "Australia");  
  v.add(2, "England"); 
  v.add(3, "South Africa"); 
  v.add(4, "Pakistan"); 
  System.out.println("Vector is " + v); 
  } 
 } 

Output:

Vector is [India, Australia, England, South Africa, Pakistan]

Example to illustrate addElement(E obj)

import java.util.*; 
 class Demo {  
  public static void main(String args[]) 
  {   
  // Creating an empty Vector  
  Vector v = new Vector();  
  // Using add() to add elements in the vector  
  v.add("Tutorials");  
  v.add("And");  
  v.add("Example");  
  v.add("Java");  
  v.add("Python");  
  // Printing the present vector  
  System.out.println("The vector is: " + v);  
  // Adding more elements to the end of the vector  
  v.addElement("Machine Learning");  
  v.addElement("AI");  
  // Printing the modified vector 
  System.out.println("The new Vector is: " + v); 
  }    
 } 

Output:

The vector is: [Tutorials, And, Example, Java, Python]
The new Vector is: [Tutorials, And, Example, Java, Python, Machine Learning, AI] 

Example to Illustrate void clear() method.

import java.util.*; 
 class Demo {  
 public static void main(String[] arg)  
 {  
 // creating default vector  
   Vector v = new Vector(); 
   v.add(0, "Java"); 
   v.add(1, "Spring");
   v.add(2, "Hibernate"); 
   v.add(3, "MongoDB"); 
   v.add(4, "Oracle");  
   System.out.println("Vector is: " + v); 
   // clearing the vector using clear() method
   v.clear(); 
   // checking vector  
   System.out.println("After clearing: " + v); 
    } 
   } 

Output:

Vector is: [Java, Spring, Hibernate, MongoDB, Oracle]
After clearing: [] 

Example to illustrate copyInto() method.

import java.util.*; 
 class Demo {  
     public static void main(String[] arg)  
     {  
         Vector v = new Vector(5); 
         // using add() to add elements in the vector  
         v.add(1);  
         v.add(2);  
         v.add(3);  
         v.add(4);  
         v.add(5); 
         Integer[] ar = new Integer[5];  
         // copying componnents of vector in array  
         v.copyInto(ar); 
         System.out.println("elements in array ar: ");   
         for (Integer num : ar) { 
             System.out.println(num);   
         }   
     }  
 } 

Output:

1
2 
3 
4 
5 

Example to illustrate ensureCapacity() method.

import java.util.*; 
 class Demo {  
     public static void main(String[] arg)
     {    
         // creating default vector 
         Vector v = new Vector(); 
         // ensuring the capacity    
         v.ensureCapacity(20);  
         // cheking capacity  
         System.out.println("Minimum capacity: " + v.capacity());  
     }  
 } 

Output:

Minimum capacity: 20

Example to illustrate insertElementAt() method.

import java.util.*; 
 class Demo {  
     public static void main(String[] arg)  
     {  
         Vector v = new Vector(5); 
  //using add() to add elements in the vector  
         v.add(1); 
         v.add(2); 
         v.add(3); 
         v.add(4); 
         v.add(5);  
         // inserting 20 at the index 5 
         v.insertElementAt(10, 5);  
         // printing vector   
         System.out.println(" Vector: " + v);  
     } 
 } 

Output:

Vector: [1, 2, 3, 4, 5, 10]

Example to illustrate removeAllElements() method.

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         Vector v = new Vector(5); 
         // using add() method to add elements 
         v.add("A"); 
         v.add("B"); 
         v.add("C"); 
         v.add("D"); 
         v.add("E");  
         // removing all elements 
         v.removeAllElements(); 
         // checking size of vector
         System.out.println("Size: " + v.size());  
         // checking components of vector 
         System.out.println("Elements in Vector " + v); 
     } 
 } 

Output:

Size: 0
Elements in vector: [] 

Example to illustrate setElementAt() method

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         // creating default vector 
         Vector v = new Vector();  
         v.add("Java"); 
         v.add("Python"); 
         v.add("Android"); 
         v.add("Ruby"); 
         v.add("Django"); 
         // setting MongoDB at the place of Ruby 
         v.setElementAt("MongoDB", 3);  
         System.out.println("vector: " + v); 
     } 
 } 

Output:

vector: [Java, Python, Android, MongoDB, Django]

Example to illustrate setSize() method.

import java.util.*; 
 class Demo {  
     public static void main(String[] arg)  
     {  
         // creating default vector 
         Vector v = new Vector();  
         v.add("Java");  
         v.add("Python"); 
         v.add("Android"); 
         v.add("Ruby"); 
         v.add("Django");  
         // setting the new size of vector 
         v.setSize(13); 
         // printing the size of vector 
         System.out.println("size of vector: " + v.size()); 
     } 
 } 

Output:

size of vector: 13

Example to illustrate trimToSize() method.

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         // creating default vector of capacity 10  
         Vector v = new Vector(); 
         v.add("Ankit"); 
         v.add("Aman"); 
         v.add("Deepanshu"); 
         v.add("Priyanshu");  
         v.add("Himanshu");  
         //initial capacity 
         System.out.println("Initial capacity of Vector: " + v.capacity()); 
         // trimming the capacity to size 
         v.trimToSize(); 
         // Printing capacity after trimming 
         System.out.println("Capacity of vector after trimming: " + v.capacity()); 
     } 
 } 

Output:

Initial capacity of Vector: 10
Capacity of vector after trimming: 5 

Example to illustrate clone() method.

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         // create default vector 
         Vector vector = new Vector();  
         Vector vector_clone = new Vector();  
         vector.add("Java");
         vector.add("Python"); 
         vector.add("Android"); 
         vector.add("Ruby"); 
         vector.add("Django");
         vector_clone = (Vector)vector.clone(); 
         // printing cloned vector 
         System.out.println("Clone of vector: " + vector_clone); 
     } 
 }     

Output:

Clone of vector: [Java, Python, Android, Ruby, Django]

Example to illustrate toArray() method.

import java.util.*;
 public class Demo { 
    public static void main(String[] args) { 
       // creating an empty Vector with initial capacity 5   
       Vector v = new Vector(5);     
       // creating an array with capacity 5
       String[] vArray = new String[5];
       // using add() to add elements in the vector
       v.add("A"); 
       v.add("B");
       v.add("C");
       v.add("D");
       v.add("E"); 
       // filling array from the vector
       v.toArray(vArray); 
       // checking the content of the array
       System.out.println("Elements are: ");   
       for (int i = 0; i < vArray.length; i++) {
          System.out.println(vArray[i]);
       }
    }    
 } 

Output:

Elements are: 
 A
 B
 C
 D
 E 

Example to illustrate toString() method.

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         // creating default vecto  
         Vector v = new Vector(); 
         v.add(1); 
         v.add(2); 
         v.add(3);  
         v.add(4); 
         v.add(5); 
         // priting equivalent string value for the vector  
         System.out.println(" String equivalent of vector are: " + v.toString());  
     } 
 } 

Output:

String equivalent of vector are: [1, 2, 3, 4, 5]

Example to illustrate elementAt(int Index) method.

import java.util.Vector;
  class Demo {
    public static void main(String[] args) {
       // creating an empty Vector v with an initial capacity of 4      
       Vector<Integer> v = new Vector<Integer>(4); 
       //using add() to add elements in the vector
       v.add(20);
       v.add(100);
       v.add(120);
       v.add(50); 
       //printing the element at 3rd index position in the vector
       System.out.println("Element at 3rd index position :- "+v.elementAt(3));
    }    
 } 

Output:

Element at 3rd index position :- 50

Example to illustrate firstElement() method.

import java.util.*; 
 class Demo {  
     public static void main(String[] arg)  
     {  
         // create default vector of capacity 10  
         Vector v = new Vector();  
         v.add("Java");  
         v.add("Python");  
         v.add("Android"); 
         v.add("Oracle");   
         v.add("SQL"); 
         // first element of vector 
         System.out.println("1st element of vector is: " + v.firstElement()); 
     } 
 } 

Output:

1st element of vector is: Java

Example to illustrate get() methods

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         // create default vector of capacity 10 
         Vector v = new Vector();  
         v.add("Java"); 
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle");  
         v.add("SQL"); 
         // get the element at index 2 
         System.out.println("Element at index 3 is: " + v.get(3)); 
     } 
 } 

Output:

Element at index 3 is: Oracle

Example to illustrate lastElement() method

import java.util.*; 
 class Demo { 
     public static void main(String[] arg) 
     { 
         Vector v = new Vector(5); 
 // using add() to add elements in the vector 
         v.add("Java"); 
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle");  
         v.add("SQL"); 
         // checking last element of vector 
         System.out.println("vector's last element is: " + v.lastElement()); 
     } 
 } 

Output:

vector's last element is: SQL

Example to illustrate remove(int Index) method. 

import java.util.*; 
 class Demo { 
     public static void main(String args[]) 
     { 
         // creating an empty Vector 
         Vector<String> v = new Vector<String>();
 // Using add() to add elements in the Vector 
         v.add("Java"); 
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle"); 
         v.add("SQL");  
         // Printing the Vector 
         System.out.println("Vector: " + v);  
         // Removing the element using remove() 
         String rmv = v.remove(3); 
         // Printing the removed element 
         System.out.println("Removed element: " + rmv); 
         // Printing the final Vector 
         System.out.println("Final Vector: " + v);  
     } 
 } 

Output:

Vector: [Java, Python, Android, Oracle, SQL]
Removed element: Oracle
Final Vector: [Java, Python, Android, SQL] 

Example to illustrate set() method.

import java.util.*; 
 class Demo { 
     public static void main(String args[]) 
     { 
         // creating an empty Vector 
         Vector<String> v = new Vector<String>();
         // Using add() to add elements in the vector 
         v.add("Java");  
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle"); 
         v.add("SQL");   
         // Displaying the Vector 
         System.out.println("Vector: " + v); 
         // Using set() method to replace elements
         System.out.println("The Object that is replaced is: "
                            + v.set(2, "IOS"));  
         // Using set() method to replace elements
         System.out.println("The Object that is replaced is: "
                            + v.set(4, "PL/Sql")); 
         // Displaying the modified vector 
         System.out.println("The new Vector is:" + v); 
     } 
 } 

Output:

Vector: [Java, Python, Android, Oracle, SQL]
The Object that is replaced is: Android
The Object that is replaced is: SQL
The new Vector is:[Java, Python, IOS, Oracle, PL/Sql] 

Example to illustrate the elements() method .

import java.util.*; 
 class Demo { 
     public static void main(String[] args) 
     { 
         // Creating Vector  
         Vector<String> v = new Vector<String>(5); 
         // Inserting elements into the table 
         v.add("Java"); 
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle");  
         v.add("SQL");  
         // printing the Vector 
         System.out.println("The Vector is: " + v); 
         // Creating an empty enumeration to store 
         Enumeration enu = v.elements(); 
         System.out.println("The enumeration of values are:");  
         // Displaying the Enumeration 
         while (enu.hasMoreElements()) { 
             System.out.println(enu.nextElement()); 
         } 
     } 
 } 

Output:

The enumeration of values are:
 Java
 Python
 Android
 Oracle
 SQL 

Example to illustrate iterator()

import java.util.*; 
 class Demo {  
 public static void main(String args[])  
     {  
         // Creating a Vector 
         Vector<String> v = new Vector<String>();
 // Use add() to add elements into the Vector 
         v.add("Java");  
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle"); 
         v.add("SQL");  
         // Printing the Vector 
         System.out.println("Vector: " + v);  
         // Creating an iterator 
         Iterator val = v.iterator(); 
         // Printing the values after iterating through the vector 
         System.out.println("The iterator values are: "); 
         while (val.hasNext()) { 
             System.out.println(val.next());  
         } 
     } 
 } 

Output:

Vector: [Java, Python, Android, Oracle, SQL]
 The iterator values are: 
 Java
 Python
 Android
 Oracle
 SQL 

Example to illustrate listIterator() method.

import java.util.*;  
 class Demo {  
     public static void main(String[] args)  
     {  
         // Declaring empty vector  
         Vector<String> v = new Vector<String>();  
         v.add("Java");  
         v.add("Python");  
         v.add("Android");  
         v.add("Oracle");  
         v.add("SQL");   
         // Declaring list iterator  
         ListIterator LItr = v.listIterator();  
         // Forward iterations  
         System.out.println("FWD>> Traversal:");  
         while (LItr.hasNext()) { 
             System.out.println(LItr.next()); 
         } 
         // Backward iterations 
         System.out.println("\n BWD<<< Traversal:");  
         while (LItr.hasPrevious()) { 
             System.out.println(LItr.previous()); 
         } 
     } 
 } 

Output:

FWD>> Traversal:
 Java
 Python
 Android
 Oracle
 SQL
  BWD<<< Traversal: 
 SQL
 Oracle
 Android
 Python
 Java 

Example to illustrate listIterator(int index) method.

import java.util.*; 
 class Demo{ 
     public static void main(String[] args) 
     { 
         // Declaring empty vector 
         Vector<String> v = new Vector<String>(); 
         v.add("Java");  
         v.add("Python"); 
         v.add("Android"); 
         v.add("Oracle"); 
         v.add("SQL");  
         // Declaring list iterator  
         ListIterator LItr = v.listIterator(1); 
         // traversing 
         while (LItr.hasNext()) { 
             System.out.println(LItr.next());  
         } 
     } 
 } 

Output:

Python
Android
Oracle
SQL 

Example to illustrate subList(int fromIndex, int toIndex) method

import java.util.*; 
  class Demo { 
     public static void main(String[] args) 
     { 
         // Creating an empty Vector  
         Vector<Integer> v = new Vector<Integer>(); 
         // Adding the elements using add() 
         v.add(50); 
         v.add(10); 
         v.add(50); 
         v.add(100); 
         v.add(200); 
         v.add(60); 
         v.add(200); 
         v.add(180); 
         v.add(90); 
         v.add(300); 
         System.out.println("The Vector is: " + v); 
         // Creating the sublist vector 
         List<Integer> sub_list = new ArrayList<Integer>(); 
         // Setting the limits
         sub_list = v.subList(2, 5); 
         //Printing the SubList data  
         System.out.println("Values within the sub list: " + sub_list); 
     } 
 } 

Output:

The Vector is: [50, 10, 50, 100, 200, 60, 200, 180, 90, 300]
Values within the sub list: [50, 100, 200] 

Example to illustrate toArray() method.

import java.util.*; 
 class Demo { 
     public static void main(String args[]) 
     { 
         // Creating a Vector 
         Vector<String> v = new Vector<String>(); 
 // Using add() to add elements into the Vector 
         v.add("Welcome"); 
         v.add("To"); 
         v.add("Tutorials"); 
         v.add("And"); 
         v.add("Examples");  
         // Printing the Vector 
         System.out.println("The Vector: " + v); 
         // Creating the array and using toArray() method 
         Object[] ar = v.toArray(); 
         System.out.println("The array is:");  
         for (int j = 0; j < ar.length; j++) 
             System.out.println(ar[j]); 
     } 
 } 

Output:

The Vector: [Welcome, To, Tutorials, And, Examples]
The array is:
Welcome
To
Tutorials
And
Examples 



ADVERTISEMENT
ADVERTISEMENT