0% found this document useful (0 votes)
5 views23 pages

Unit 3

The document explains the concept of abstract classes and interfaces in Java, highlighting their roles in achieving abstraction. It covers exception handling, types of exceptions, and the use of keywords like try, catch, and finally. Additionally, it discusses Java strings, their immutability, the StringBuffer class for mutable strings, and the structure and usage of arrays in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

Unit 3

The document explains the concept of abstract classes and interfaces in Java, highlighting their roles in achieving abstraction. It covers exception handling, types of exceptions, and the use of keywords like try, catch, and finally. Additionally, it discusses Java strings, their immutability, the StringBuffer class for mutable strings, and the structure and usage of arrays in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated(we canot create
object).

Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
abstract class Bike{
abstract void run();
}

class Honda4 extends Bike{


void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.

Multiple Inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritances.
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
Error : It is type bug in a program. The process of removing error in a program is known as
debugging.

Types –
1. Syntax error
2. Runtime error
3. Logical error
4. Semantic error

a+b =c; //no meaning

Exception Handling
Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular
flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors
such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run
time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by
the program. When an exception occurs within a method, it creates an object. This object is called the
exception object. It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.

Major reasons why an exception Occurs

 Invalid user input


 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory,
memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually
beyond the control of the programmer, and we should not try to handle errors.

 Error: An Error indicates a serious problem that a reasonable application should not try to catch.
 Exception: Exception indicates conditions that a reasonable application might try to catch.

Types of Exceptions

Java defines several types of exceptions that relate to its various class libraries. Java also allows users to
define their own exceptions.
Difference between Checked and Unchecked Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes that inherit the Runtime Exception are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.

format -
try{
code
}
catch(Exception-type e){
statement;
}
catch(Exception-type ae){
statement;
}
finally{
this block gurantee to execute
}

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Java String

In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and
StringBuilder classes implement it. It means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string
constant pool).

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).

Java String Example

StringExample.java

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on
console using println() method.

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

Method Description

charAt(int index) It returns char value for the particular index

int length() It returns string length

String substring(int beginIndex) It returns substring for given begin index.

String substring(int beginIndex, int It returns substring for given begin index and end
endIndex) index.

boolean equals(Object another) It checks the equality of string with the given object.

boolean isEmpty() It checks if string is empty.

String concat(String str) It concatenates the specified string.

String replace(char old, char new) It replaces all occurrences of the specified char value.

static String It compares another string. It doesn't check case.


equalsIgnoreCase(String another)

int indexOf(int ch) ,lastIndexOf() It returns the specified char value index.

String toLowerCase() It returns a string in lowercase.

String toUpperCase() It returns a string in uppercase.

String trim() It removes beginning and ending spaces of this string.

static String valueOf(int value) It converts given type into string. It is an overloaded
method.

int compareTo()- Checks two Strings lexicographically


-ve – first string < second string

0 - both are equal

+ve – first string > second string

Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java
is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.

Important Constructors of StringBuffer Class

Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Method Description
append(String s) It is used to append the specified string with this string. The append() method is
overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.
insert(int offset, String It is used to insert the specified string with this string at the specified position.
s) The insert() method is overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
replace(int startIndex, It is used to replace the string from specified startIndex and endIndex.
int endIndex, String str)
delete(int startIndex, int It is used to delete the string from specified startIndex and endIndex.
endIndex)
reverse() is used to reverse the string.
capacity() It is used to return the current capacity.
charAt(int index) It is used to return the character at the specified position.
length() It is used to return the length of the string i.e. total number of characters.
substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
substring(int It is used to return the substring from the specified beginIndex and endIndex.
beginIndex, int
endIndex)

ASCII Value (UNICODE)


A-Z = 65-90

a-z =97-122

0-9=48-57
Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on
1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.

//Java Program to illustrate how to declare, instantiate, initialize

//and traverse the Java array.


class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

Let us see the example of print the elements of Java array using the for-each loop.

//Java Program to print the array elements using for-each loop


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:

Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.

//Java Program to demonstrate the way of passing an anonymous array


//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}

Output:

10
22
44
66

Returning Array from the Method

We can also return an array from the method in Java.

//Java Program to return an array from the method


class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}

Output:

10
30
50
90
60
ArrayIndexOutOfBoundsException

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.

//Java Program to demonstrate the case of


//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Output:

1 2 3
2 4 5
4 4 5

Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is
an array of arrays with different number of columns.

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

Output:

0 1 2
3 4 5 6
7 8
What is the class name of Java array?

In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by
getClass().getName() method on the object.

//Java Program to get the class name of array in Java


class Testarray4{
public static void main(String args[]){
//declaration and initialization of array
int arr[]={4,4,5};
//getting the class name of Java array
Class c=arr.getClass();
String name=c.getName();
//printing the class name of Java array
System.out.println(name);

}}

Output:

Copying a Java Array

We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method

1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of Copying an Array in Java

//Java Program to copy a source array into a destination array in Java


class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}

Output:

caffein
Cloning an Array in Java

Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create
the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the
actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java
array which means it copies the references.

//Java Program to clone the array


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);

System.out.println("Printing clone of the array:");


int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);

System.out.println("Are both equal?");


System.out.println(arr==carr);

}}

Output:

Printing original array:


33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false

Addition of 2 Matrices in Java

Let's see a simple example that adds two matrices.

//Java Program to demonstrate the addition of two matrices in Java


class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}

Output:

2 6 8
6 8 10

Multiplication of 2 Matrices in Java

In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of
the second matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

//Java Program to multiply two matrices


public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
Output:
6 6 6
12 12 12
18 18 18

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of
elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in
the java.util package and implements the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use
the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws
the ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

 Vector is synchronized.
 Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector class Declaration

1. public class Vector<E>


2. extends Object<E>
3. implements List<E>, Cloneable, Serializable

Java Vector Constructors

Vector class supports four types of constructors. These are given below:

SN Constructor Description
1) vector() It constructs an empty vector with the default size as 10.
2) vector(int initialCapacity) It constructs an empty vector with the specified initial capacity and
with its capacity increment equal to zero.
3) vector(int initialCapacity, int It constructs an empty vector with the specified initial capacity and
capacityIncrement) capacity increment.
4) Vector( Collection<? extends E> c) It constructs a vector that contains the elements of a collection c.

Java Vector Methods

The following are the list of Vector class methods:

SN Method Description
1) add() It is used to append the specified element in the given vector.
2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It increases
the vector size by one.
4) capacity() It is used to get the current capacity of this vector.
5) clear() It is used to delete all of the elements from this vector.
6) clone() It returns a clone of this vector.
7) contains() It returns true if the vector contains the specified element.
8) containsAll() It returns true if the vector contains all of the elements in the specified collection.
9) copyInto() It is used to copy the components of the vector into the specified array.
10) elementAt() It is used to get the component at the specified index.
11) elements() It returns an enumeration of the components of a vector.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for equality.
14) firstElement() It is used to get the first component of the vector.
15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
17) hashCode() It is used to get the hash code value of a vector.
18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the given vector at the
specified index.
20) isEmpty() It is used to check if this vector has no components.
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
22) lastElement() It is used to get the last component of the vector.
23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.
25) remove() It is used to remove the specified element from the vector. If the vector does not
contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
27) removeAllElements() It is used to remove all elements from the vector and set the size of the vector to
zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.
29) removeElementAt() It is used to delete the component at the specified index.
30) removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.
31) removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.
33) retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.
34) set() It is used to replace the element at the specified position in the vector with the
specified element.
35) setElementAt() It is used to set the component at the specified index of the vector to the
specified object.
36) setSize() It is used to set the size of the given vector.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the specified
Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the
list.
40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive, and
toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.
42) toString() It is used to get a string representation of the vector.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.

Java Vector Example


import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Java Vector Example 2


import java.util.*;
public class VectorExample1 {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

You might also like