Unit 3
Unit 3
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).
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
Types –
1. Syntax error
2. Runtime error
3. Logical error
4. Semantic error
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.
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
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.
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
}
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.
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.
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.
1. By string literal
2. By new keyword
1) String Literal
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".
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
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).
StringExample.java
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.
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
Method Description
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.
String replace(char old, char new) It replaces all occurrences of the specified char value.
int indexOf(int ch) ,lastIndexOf() It returns the specified char value index.
static String valueOf(int value) It converts given type into string. It is an overloaded
method.
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.
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.
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)
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.
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
Output:
33
3
4
5
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.
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.
Output:
33
3
4
5
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.
System.out.println(min);
}
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.
Output:
10
22
44
66
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.
Output:
In such case, data is stored in row and column based index (also known as matrix form).
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;
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
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.
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.
}}
Output:
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.
}}
Output:
}}
Output:
2 6 8
6 8 10
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 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.
Vector is synchronized.
Java Vector contains many legacy methods that are not the part of a collections framework.
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.
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.