MODULE_3-Java Notes
MODULE_3-Java Notes
Strings are constant; their values cannot be changed after they are created. String buffers support
mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
The class String includes methods for examining individual characters of the sequence, for comparing
strings, for searching strings, for extracting substrings, and for creating a copy of a string with all
characters translated to uppercase or to lowercase.
The Java language provides special support for the string concatentation operator ( + ), and for
conversion of other objects to strings. String concatenation is implemented through
the StringBuffer class and its append method. String conversions are implemented through the
method toString, defined by Object and inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.
String(char chars[ ])
Here is an example:
You can specify a subrange of a character array as an initializer using the following
constructor:
Here, startIndex specifies the index at which the subrange begins, and numChars specifies
You can construct a String object that contains the same character sequence as another
String(String strObj)
class MakeString {
System.out.println(s1);
System.out.println(s2);
Java
Java
As you can see, s1 and s2 contain the same string.
Syntax
Parameters
Return Value
This method returns the the length of the sequence of characters represented by this object.
Example
import java.io.*;
public class Test {
charAt()
getChars()
getBytes()
toCharArray()
charAt(int index)
To extract a single character from a String, you can refer directly to an individual character via
the charAt( ) method.
Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.
Example 2: Throws IndexOutOfBoundsException - if the index argument is negative or not less than the
length of this string.
String str = "Java Guides";
char ch1 = str.charAt(str.length() + 1);
System.out.println("character :: " + ch1);
Output:
getChars()
If you need to extract more than one character at a time, you can use the getChars( ) method. It has this
general form:
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index
that is one past the end of the desired substring. Thus, the substring contains the characters from
sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The
index within target at which the substring will be copied is passed in targetStart. Care must be taken to
assure that the target array is large enough to hold the number of characters in the specified substring.
demo
getBytes()
There are four versions of getBytes() methods. There is an alternative to getChars( ) that stores the
characters in an array of bytes.
byte[] getBytes() - Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.
byte[] getBytes(Charset charset) - Encodes this String into a sequence of bytes using the given charset,
storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) - Deprecated.
byte[] getBytes(String charsetName) - Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs1 = str.getBytes(Charset.forName("UTF-8"));
for (byte b: bs1) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs2 = str.getBytes("UTF-8");
for (byte b: bs2) {
System.out.println(b);
}
}
}
toCharArray()
}
}
Ouput:
j
a
v
a
g
u
i
d
e
s
Searching characters and substring in a String in Java
Searching a character in the String
indexOf(char c) : It searches the index of specified character within a given string. It starts searching
from beginning to the end of the string (from left to right) and returns the corresponding index if found
otherwise returns -1.
Note: If given string contains multiple occurrence of specified character then it returns index of only first
occurrence of specified character.
Syntax:
int indexOf(char c)
// Accepts character as argument, Returns index of the first occurrence of specified character
lastIndexOf(char c): It starts searching backward from end of the string and returns the index of
specified character whenever it is encountered.
Syntax:
public int lastIndexOf(char c)
// Accepts character as argument, Returns an index of the last occurrence specified character
IndexOf(char c, int indexFrom): It starts searching forward from the specified index in the string and
returns the corresponding index when the specified character is encountered otherwise returns -
1. Note: The returned index must be greater than or equal to the specified index.
Syntax:
public int IndexOf(char c, int indexFrom)
char: character to be searched.
indexfrom : an integer from where searching
// Returns an index of specified character that appeared at or after the specified index in forward
direction
lastIndexOf(char c, int fromIndex): It starts searching backward from the specified index in the string.
And returns the corresponding index when the specified character is encountered otherwise returns -1.
Note: The returned index must be less than or equal to the specified index.
Syntax:
public int lastIndexOf(char c, int fromIndex)
charAt(int indexNumber): Returns the character existing at the specified index, indexNumber in the
given string. If the specified index number does not exist in the string, the method throws an unchecked
exception, StringIndexOutOfBoundsException.
Syntax:
char charAt(int indexNumber)
// Java program to illustrate to find a character in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a character
// to be searched.
String str = "GeeksforGeeks is a computer science portal";
// throws StringIndexOutOfBoundsException
// char_at = str.charAt(50);
}
}
Output:
First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111
The methods used for searching a character in the string which are mentioned above can also be used
for searching the substring in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";
// Java program to illustrate how to find a substring in the string using contains
import java.io.*;
import java.lang.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// to be searched.
String test = "software";
boolean startsWith(String str): Returns true if the string str exist at the starting of the given string,
else false.
boolean startsWith(String str, int indexNum): Returns true if the string str exist at the starting of
the index indexNum in the given string, else false.
boolean endsWith(String str): Returns true if the string str exist at the ending of the given string,
else false.
class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";
System.out.println(str.startsWith("Geek"));
System.out.println(str.startsWith("is", 14));
System.out.println(str.endsWith("port"));
}
}
Output:
true
true
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
The String equals() method compares the original content of the string. It compares values of string for
equality. String class provides two methods:
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring
case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:
true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true
Output:
true
false
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
Java StringBuffer class: StringBuffer is a peer class of String that provides much of the
functionality of strings.As you know, String represents fixed-length, immutable character sequences.
In contrast,StringBuffer represents growable and writeable character sequences. StringBuffer may
have
characters and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more characters preallocated
than are actually needed, to allow room for growth. Java uses both classes heavily, but many
programmers deal only with String and let Java manipulate StringBuffers behind the scenes
by using the overloaded + operator.
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
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.
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as
length.
public synchronized append(String s) is used to append the specified string with this
StringBuffer string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.
public synchronized insert(int offset, String s) is used to insert the specified string with this string
StringBuffer at the specified position. The insert() method is
overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
public synchronized replace(int startIndex, int is used to replace the string from specified
StringBuffer endIndex, String str) startIndex and endIndex.
public synchronized delete(int startIndex, int is used to delete the string from specified startIndex
StringBuffer endIndex) and endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public void ensureCapacity(int is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.
public char charAt(int index) is used to return the character at the specified
position.
public int length() is used to return the length of the string i.e. total
number of characters.
public String substring(int beginIndex) is used to return the substring from the specified
beginIndex.
public String substring(int beginIndex, int is used to return the substring from the specified
endIndex) beginIndex and endIndex.
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between checked and
unchecked exceptions.
What is Exception in Java
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception handling.
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
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 exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.
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 important code of the program. It is executed whether an
exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute.
So, it is recommended not to keeping the code in try block that will not throw an exception.
Java catch block is used to handle the Exception by declaring the type of exception within the parameter.
The declared exception must be the parent class exception ( i.e., Exception) or the generated exception
type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.
Output:
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Let's see the solution of the above problem by a java try-catch block.
Example 2
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example 1
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
class Excep6
{
public static void main(String args[])
{
try
{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
1. }catch(Exception e){System.out.println("handeled");}
2.
3. System.out.println("normal flow..");
4. }
5. }
Java finally block is a block that is used to execute important code such as closing connection, stream
etc.
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
Why use java finally
o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.
throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If the age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
The Java throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling code so
that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:
There are many differences between final, finally and finalize. A list of differences between final, finally
and finalize are given below:
1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will perform clean up
inherited, final method can't be overridden and be executed whether processing just before
final variable value can't be changed. exception is handled or object is garbage
not. collected.
class FinalExample
{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}
}
class FinallyExample
{
public static void main(String[] args)
{
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
class FinalizeExample
{
public void finalize(){System.out.println("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}