1. JAVA Programming
Arrays, Strings and
Exception Handling
December 8, 2022
Department of CSE, NCCE , Israna Panipat
By
Naushad Varish
Department of Computer Science &
Engineering
NC College of Engineering, Israna,
Panipat
1
2. JAVA Programming
An array is a collection of variables of the same type,
referred to by a common name.
In Java arrays can have one or more dimensions,
although the one-dimensional array is the most common.
Arrays are used for a variety of purposes because they
offer a convenient means of grouping together related
variables.
The principal advantage of an array is that it organizes
data in such a way that it can be easily manipulated.
In Java arrays are implemented as objects.
• An array is an ordered list of values
Arrays
December 8, 2022
Department of CSE, NCCE , Israna Panipat 2
3. JAVA Programming
Arrays(Cont…)
December 8, 2022
Department of CSE, NCCE , Israna Panipat 3
0 1 2 3 4 5 6 7 8 9
79 87 94 82 67 98 87 81 74 91
scores
The entire array
has a single name
Each value has a numeric index
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
5. JAVA Programming
// file name: Main.java
public class Main{
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
for(int i=0; i < arr.length; i++)
{
System.out.print(" " + arr[i]);
}
}
}
Output:
10 20 30 40 50
Array Example
December 8, 2022
Department of CSE, NCCE, Israna Panipat 5
6. JAVA Programming
If we don’t assign values to array elements, and try to
access them, compiler does not produce error as in case
of simple variables. Instead it assigns values which aren’t
garbage.
Below are the default assigned values.
boolean : false
int : 0
double : 0.0
String : null
User Defined Type : null
Default array values in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 6
7. JAVA Programming
// Java program to demonstrate default values of array
// elements
class ArrayDemo
{
public static void main(String[] args)
{
System.out.println("String array default values:");
String str[] = new String[5];
for (String s : str)
System.out.print(s + " ");
System.out.println("nnInteger array default values:");
int num[] = new int[5];
for (int val : num)
System.out.print(val + " ");
System.out.println("nnDouble array default values:");
double dnum[] = new double[5];
for (double val : dnum)
System.out.print(val + " ");
System.out.println("nnBoolean array default values:");
boolean bnum[] = new boolean[5];
for (boolean val : bnum)
System.out.print(val + " ");
System.out.println("nnReference Array default values:");
ArrayDemo ademo[] = new ArrayDemo[5];
for (ArrayDemo val : ademo)
System.out.print(val + " ");
}
}
Default array values in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 7
O/P:
String array default values: null null null null null
Integer array default values: 0 0 0 0 0
Double array default values: 0.0 0.0 0.0 0.0 0.0
Boolean array default values: false false false
false false
Reference Array default values: null null null null
null
8. JAVA Programming
Predict the output of following Java program.
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1 == arr2) // Same as arr1.equals(arr2)
System.out.println("Same");
else
System.out.println("Not same");
}
}
O/P: Not same
In Java, arrays are first class objects. In the above program, arr1 and arr2 are two
references to two different objects. So when we compare arr1 and arr2, two reference
variables are compared, therefore we get the output as “Not Same” (See this for more
examples).
How to compare two arrays in Java?
December 8, 2022
Department of CSE, NCCE, Israna Panipat 8
9. JAVA Programming
A simple way is to run a loop and compare elements one by one. Java
provides a direct method Arrays.equals() to compare two arrays. Actually,
there is a list of equals() methods in Arrays class for different primitive types
(int, char, ..etc) and one for Object type (which is base of all classes in Java).
// we need to import java.util.Arrays to use Arrays.equals().
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
How to compare array contents?
December 8, 2022
Department of CSE, NCCE, Israna Panipat 9
O/P: Same
10. JAVA Programming
As seen above, the Arrays.equals() works fine and compares arrays contents.
Now the questions, what if the arrays contain arrays inside them or some
other references which refer to different object but have same values. For
example, see the following program..
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
// inarr1 and inarr2 have same values
int inarr1[] = {1, 2, 3};
int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1}; // arr1 contains only one element
Object[] arr2 = {inarr2}; // arr2 also contains only one element
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
How to Deep compare array contents?
December 8, 2022
Department of CSE, NCCE, Israna Panipat 10
O/P: Not same
11. JAVA Programming
So Arrays.equals() is not able to do deep comparison. Java provides another
method for this Arrays.deepEquals() which does deep comparison.
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int inarr1[] = {1, 2, 3};
int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1}; // arr1 contains only one element
Object[] arr2 = {inarr2}; // arr2 also contains only one element
if (Arrays.deepEquals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
How to Deep compare array contents?
December 8, 2022
Department of CSE, NCCE, Israna Panipat 11
O/P: Same
12. JAVA Programming
It compares two objects using any custom equals() methods they may have (if they
have an equals() method implemented other than Object.equals()). If not, this
method will then proceed to compare the objects field by field, recursively. As each
field is encountered, it will attempt to use the derived equals() if it exists, otherwise it
will continue to recurse further..
Exercise: Predict the output of following program
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int inarr1[] = {1, 2, 3};
int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1}; // arr1 contains only one element
Object[] arr2 = {inarr2}; // arr2 also contains only one element
Object[] outarr1 = {arr1}; // outarr1 contains only one element
Object[] outarr2 = {arr2}; // outarr2 also contains only one element
if (Arrays.deepEquals(outarr1, outarr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
}
How does Arrays.deepEquals() work?
December 8, 2022
Department of CSE, NCCE, Israna Panipat 12
O/P: ?
13. JAVA Programming
Predict the output of following Java program.
class Test
{
public static void main(String args[])
{
final int arr[] = {1, 2, 3, 4, 5}; // Note: arr is final
for (int i = 0; i < arr.length; i++)
{
arr[i] = arr[i]*10;
System.out.print(arr[i]);
}
}
}
Output:
10 20 30 40 50
The array arr is declared as final, but the elements of array are changed without any problem.
Arrays are objects and object variables are always references in Java. So, when we declare an object
variable as final, it means that the variable cannot be changed to refer to anything else. For
example, the following program 1 compiles without any error and program fails in compilation.
Final arrays in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 13
14. JAVA Programming
// Program 1
class Test
{
int p = 20;
public static void main(String args[])
{
final Test t = new Test();
t.p = 30;
System.out.println(t.p);
}
}
Output: 30
// Program 2
class Test
{
int p = 20;
public static void main(String args[])
{
final Test t1 = new Test();
Test t2 = new Test();
t1 = t2;
System.out.println(t1.p);
}
}
Output: Compiler Error: cannot assign a value to final variable t1
Final arrays in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 14
15. JAVA Programming
So a final array means that the array variable which is actually a reference to an object,
cannot be changed to refer to anything else, but the members of array can be
modified.
As an exercise, predict the output of following program
class Test
{
public static void main(String args[])
{
final int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {10, 20, 30, 40, 50};
arr2 = arr1;
arr1 = arr2;
for (int i = 0; i < arr2.length; i++)
System.out.println(arr2[i]);
}
}
Output:?
Final arrays in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 15
16. JAVA Programming
Jagged array is array of arrays such that member arrays can be of different sizes, i.e.,
we can create a 2-D arrays but with variable number of columns in each row. These
type of arrays are also known as Jagged arrays.
Following are Java programs to demonstrate the above concept.
// Program to demonstrate 2-D jagged array in Java
class Main
{
public static void main(String[] args)
{
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];
// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];
// Second row has 2 columns
arr[1] = new int[2];
// Initializing 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++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D 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();
}
}
}
Jagged Array in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 16
Output: Contents of 2D
Jagged Array
0 1 2
3 4
17. JAVA Programming
Following is another example where i’th row has i columns, i.e., first row has 1 element, second
row has two elements and so on
// Another Java program to demonstrate 2-D jagged
// array such that first row has 1 element, second
// row has two elements and so on.
class Main
{
public static void main(String[] args)
{
int r = 5;
// Declaring 2-D array with 5 rows
int arr[][] = new int[r][];
// Creating a 2D array such that first row
// has 1 element, second row has two
// elements and so on.
for (int i=0; i<arr.length; i++)
arr[i] = new int[i+1];
// Initializing 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++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D 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();
}
}
}
Jagged Array in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 17
Output: Contents of 2D
Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
18. JAVA Programming
Java supports creation and manipulation of arrays, as a data structure. The index of an array is an
integer value that has value in interval [0, n-1], where n is the size of the array. If a request for a
negative or an index greater than or equal to size of array is made, then the JAVA throws a
ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done.
The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java
Compiler does not check for this error during the compilation of a program.
// A Common cause index out of bound
public class NewClass2
{
public static void main(String[] args)
{
int ar[] = {1, 2, 3, 4, 5};
for (int i=0; i<=ar.length; i++)
System.out.println(ar[i]);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at
NewClass2.main(NewClass2.java:5)
Understanding Array IndexOutofbounds Exception in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 18
Output:
1
2
3
4
5
19. JAVA Programming
Here if you carefully see, the array is of size 5. Therefore while accessing its element using for
loop, the maximum value of index can be 4 but in our program it is going till 5 and thus the
exception.
Let’s see another example using arraylist:
// One more example with index out of bound
import java.util.ArrayList;
public class NewClass2
{
public static void main(String[] args)
{
ArrayList<String> lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
System.out.println(lis.get(2));
}
}
Runtime error here is a bit more informative than the previous time-
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at
java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at NewClass2.main(NewClass2.java:7)
Understanding Array IndexOutofbounds Exception in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 19
20. JAVA Programming
Lets understand it in a bit of detail-
Index here defines the index we are trying to access.
The size gives us information of the size of the list.
Since size is 2, the last index we can access is (2-1)=1, and thus the exception
The correct way to access array is :
for (int i=0; i<ar.length; i++) { }
Handling the Exception:
Use for-each loop: This automatically handles indices while accessing the
elements of an array.
Example-for(int m : ar){ }
Use Try-Catch: Consider enclosing your code inside a try-catch statement and
manipulate the exception accordingly. As mentioned, Java won’t let you
access an invalid index and will definitely throw
an ArrayIndexOutOfBoundsException. However, we should be careful inside
the block of the catch statement, because if we don’t handle the exception
appropriately, we may conceal it and thus, create a bug in your application.
Understanding Array IndexOutofbounds Exception in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 20
21. JAVA Programming
String is a sequence of characters.
The easiest way to represent a sequence of characters in JAVA is by using a character
array.
char Array[ ] = new char [5];
Character arrays are not good enough to support the range of operations we want to
perform on strings.
In java, objects of String are immutable which means a constant and cannot be
changed once created.
In JAVA strings are class objects and implemented using two classes:-
String
StringBuffer
In JAVA strings are not a character array and is not NULL terminated.
String objects are handled specially by the compiler.
String is the only class which has "implicit" instantiation.
The String class is defined in the java.lang package.
Strings are immutable. For mutable Strings, use the StringBuffer class.
The value of a String object can never be changed.
Strings in JAVA
December 8, 2022
Department of CSE, NCCE, Israna Panipat 21
22. JAVA Programming
Normally, objects in Java are created with the new keyword..
Creating a String:
There are two ways to create string in Java:
String literal
String s = “Craig”;
Using new keyword
String s = new String (“Craig”);
OR
String name;
name = new String("Craig");
However, String objects can be created "implicitly":
String name;
name = "Craig";
DECLARING & INITIALISING
December 8, 2022
Department of CSE, NCCE, Israna Panipat 22
23. JAVA Programming
int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
String substring (int i): Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
String substring (int i, int j): Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
int indexOf (String s): Returns the index within the string of the first occurrence of the
specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6.
String Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 23
24. JAVA Programming
int indexOf (String s, int i): Returns the index within the string of the first
occurrence of the specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf(‘a’,3);// returns 8
Int lastindexOf( int ch): Returns the index within the string of the last occurrence
of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastindexOf(‘a’); // returns 14
boolean equals( Object otherObj): Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
boolean equalsIgnoreCase (String anotherString): Compares string to another
string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
String Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 24
25. JAVA Programming
int compareTo( String anotherString): Compares two string lexicographically.
int out = s1.compareTo(s2); // where s1 ans s2 are strings to be compared.
This returns difference s1-s2.
If : out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
int compareToIgnoreCase( String anotherString): Compares two string
lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2); // where s1 ans s2 strings to be
compared.
This returns difference s1-s2.
If : out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
String Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 25
26. JAVA Programming
String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word2 = word1.toLowerCase(); // returns “hello“.
String toUpperCase(): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”.
String trim(): Returns the copy of the String, by removing whitespaces at both
ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”.
String replace (char oldChar, char newChar): Returns new string by replacing all
occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks
String Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 26
27. JAVA Programming
// Java code to illustrate different constructors and methods String class.
import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
// Returns the number of characters in the String.
System.out.println("String length = " + s.length());
// Returns the character at ith index.
System.out.println("Character at 3rd position = "
+ s.charAt(3));
// Return the substring from the ith index character
// to end of string
System.out.println("Substring " + s.substring(3));
// Returns the substring from i to j-1 index.
System.out.println("Substring = " + s.substring(2,5));
Program to illustrate all string methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 27
28. JAVA Programming
// Concatenates string2 to the end of string1.
String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " +
s1.concat(s2));
// Returns the index within the string
// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +
s4.indexOf("Share"));
// Returns the index within the string of the
// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +
s4.indexOf('a',3));
// Checking equality of Strings
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality" + out);
int out1 = s1.compareTo(s2);
System.out.println("If s1 = s2" + out);
Cont…
December 8, 2022
Department of CSE, NCCE, Israna Panipat 28
29. JAVA Programming
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +
word1.toLowerCase());
// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
word1.toUpperCase());
// Trimming the word
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Cont…
December 8, 2022
Department of CSE, NCCE, Israna Panipat 29
30. JAVA Programming
Output :
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equalityfalse
If s1 = s2 false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks
Cont…
December 8, 2022
Department of CSE, NCCE, Israna Panipat 30
31. JAVA Programming
StringBuffer is a peer class of String that provides much of the
functionality of strings. String represents fixed-length, immutable
character sequences
while StringBuffer represents growable and writable character
sequences which means that class creates strings of flexible
length that can be modified in terms of both length and content.
StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
StringBuffer automatically grows to make room for such
additions.
Actually StringBuffer has more characters pre allocated than are
actually needed, to allow room for growth.
StringBuffer class in Java
December 8, 2022
Department of CSE, NCCE, Israna Panipat 31
32. JAVA Programming
StringBuffer( ): It reserves room for 16 characters without
reallocation.
StringBuffer s=new StringBuffer();
StringBuffer(int size): It accepts an integer argument that
explicitly sets the size of the buffer.
StringBuffer s=new StringBuffer(20);
StringBuffer(String str): It accepts a String argument that sets
the initial contents of the StringBuffer object and reserves room
for 16 more characters without reallocation.
StringBuffer s=new StringBuffer("GeeksforGeeks");
StringBuffer Constructors
December 8, 2022
Department of CSE, NCCE, Israna Panipat 32
33. JAVA Programming
Some of the most used methods are:
length( ) and capacity( ): The length of a StringBuffer can be found by the length(
) method, while the total allocated capacity can be found by the capacity( )
method.
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksforGeeks");
int p=s.length();
int q=s.capacity();
System.out.println("Length of string GeeksforGeeks="+p);
System.out.println("Capacity of string GeeksforGeeks="+q);
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 33
34. JAVA Programming
Output:
Length of string GeeksforGeeks=13
Capacity of string GeeksforGeeks=29
append( ): It is used to add text at the end of the existence text. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("Geeksfor");
s.append("Geeks");
System.out.println(s); //returns GeeksforGeeks
s.append(1);
System.out.println(s); //returns GeeksforGeeks1
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 34
35. JAVA Programming
insert( ): It is used to insert text at the specified index position. These are a few of its
forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object.
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksGeeks");
s.insert(5, "for");
System.out.println(s); //returns GeeksforGeeks
s.insert(0,5);
System.out.println(s); //returns 5GeeksforGeeks
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 35
36. JAVA Programming
reverse( ): It can reverse the characters within a
StringBuffer object using reverse( ).This method returns
the reversed object on which it was called.
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksGeeks");
s.reverse();
System.out.println(s); //returns skeeGrofskeeG
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 36
37. JAVA Programming
delete( ) and deleteCharAt( ): It can delete characters within a
StringBuffer by using the methods delete( ) and deleteCharAt( ).
The delete( ) method deletes a sequence of characters from the
invoking object. Here, start Index specifies the index of the first
character to remove, and end Index specifies an index one past
the last character to remove. Thus, the substring deleted runs
from start Index to endIndex–1. The resulting StringBuffer object
is returned.
The deleteCharAt( ) method deletes the character at the index
specified by loc. It returns the resulting StringBuffer object.
These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 37
38. JAVA Programming
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksforGeeks");
s.delete(0,5);
System.out.println(s); //returns forGeeks
s.deleteCharAt(7);
System.out.println(s); //returns forGeek
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 38
39. JAVA Programming
replace( ): It can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). The substring being replaced is
specified by the indexes start Index and endIndex. Thus, the substring at start
Index through endIndex–1 is replaced. The replacement string is passed in str.
The resulting StringBuffer object is returned. Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
Code Example:
import java.io.*;
class GFG
{
public static void main (String[] args)
{
StringBuffer s=new StringBuffer("GeeksforGeeks");
s.replace(5,8,"are");
System.out.println(s); //returns GeeksareGeeks
}
}
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 39
40. JAVA Programming
ensureCapacity( ): It is used to increase the capacity of a StringBuffer object.
The new capacity will be set to either the value we specify or twice the
current capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity
specifies the size of the buffer.
void ensureCapacity(int capacity)
Methods
December 8, 2022
Department of CSE, NCCE, Israna Panipat 40
41. JAVA Programming
StringTokenizer class in Java is used to break a string into tokens.
StringTokenizer class
December 8, 2022
Department of CSE, NCCE, Israna Panipat 41
42. JAVA Programming
Constructors:
StringTokenizer(String str) : str is string to be tokenized. Considers
default delimiters like new line, space, tab, carriage return and form
feed.
StringTokenizer(String str, String delim) : delim is set of delimiters that
are used to tokenize the given string.
StringTokenizer(String str, String delim, boolean flag): The first two
parameters have same meaning. The flag serves following purpose.
If the flag is false, delimiter characters serve to separate tokens. For
example, if string is "hello geeks" and delimiter is " ", then tokens are
"hello" and "geeks".
If the flag is true, delimiter characters are considered to be tokens. For
example, if string is "hello geeks" and delimiter is " ", then tokens are
"hello", " " and "geeks".
StringTokenizer class
December 8, 2022
Department of CSE, NCCE, Israna Panipat 42
43. JAVA Programming
/* A Java program to illustrate working of StringTokenizer
class:*/
import java.util.*;
public class NewClass
{
public static void main(String args[])
{
System.out.println("Using Constructor 1 - ");
StringTokenizer st1 = new StringTokenizer("Hello Geeks How are you", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");
StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("Using Constructor 3 - ");
StringTokenizer st3 = new StringTokenizer("JAVA : Code : String", " :", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
StringTokenizer class
December 8, 2022
Department of CSE, NCCE, Israna Panipat 43
44. JAVA Programming
What is an Exception?
• An 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.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should
not try to catch.
Exception: Exception indicates conditions that a reasonable application might
try to catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy. One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException is an example of
such an exception. Another branch, Error are used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 44
46. JAVA Programming
Default Exception Handling :
• Whenever inside a method, if an exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system(JVM). The exception object contains
name and description of the exception, and current state of the program where exception has
occurred. Creating the Exception Object and handling it to the run-time system is called throwing
an Exception. There might be the list of the methods that had been called to get to the method
where exception was occurred. This ordered list of the methods is called Call Stack. Now the
following procedure will happen.
The run-time system searches the call stack to find the method that contains block of code that can
handle the occurred exception. The block of the code is called Exception handler.
The run-time system starts searching from the method in which exception occurred, proceeds
through call stack in the reverse order in which methods were called.
If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler
means the type of the exception object thrown matches the type of the exception object it can
handle.
If run-time system searches all the methods on call stack and couldn’t have found the appropriate
handler then run-time system handover the Exception Object to default exception handler , which
is part of run-time system. This handler prints the exception information in the following format
and terminates program abnormally.
Exception in thread "xxx" Name of Exception : Description ... ...... .. // Call Stack
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 46
47. JAVA Programming
• See the below diagram to understand the flow of the call stack.
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 47
48. JAVA Programming
Example :
// Java program to demonstrate how exception is thrown.
class ThrowsExecp{
public static void main(String args[]){
String str = null;
System.out.println(str.length());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException at ThrowsExecp.main(File.java:8)
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 48
49. JAVA Programming
Let us see an example that illustrate how run-time system searches appropriate exception handling
code on the call stack :
// Java program to demonstrate exception is thrown
// how the runTime system searches th call stack
// to find appropriate exception handler.
class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){
// this statement will cause ArithmeticException(/ by zero)
int i = a/b;
return i;
}
// The runTime System searches the appropriate Exception handler
// in this method also but couldn't have found. So looking forward
// on the call stack.
static int computeDivision(int a, int b) {
int res =0;
try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 49
50. JAVA Programming
// In this method found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[]){
int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b);
}
// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}
Output: / by zero.
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 50
51. JAVA Programming
Customized Exception Handling : Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch
block) and handle it in some rational manner.
System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an
exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by
a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.
Consider the following java program.
// java program to demonstrate
// need of try-catch clause
class GFG {
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];
// this statement causes an exception
int i = arr[4];
// the following statement will never execute
System.out.println("Hi, I want to execute");
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at GFG.main(GFG.java:9)
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 51
52. JAVA Programming
How to use try-catch clause
try
{
// block of code to monitor for errors // the code you think can raise an exception
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// optional
finally
{
// block of code to be executed after try block ends
}
Exceptions
December 8, 2022
Department of CSE, NCCE, Israna Panipat 52