403-Java-Unit-3
403-Java-Unit-3
The String class supports several constructors. To create an empty String, you call the
default constructor. For example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create
strings that have initial values. The String class provides a variety of constructors to handle
this.
• To create a String initialized by an array of characters, use the constructor shown
here:
String(char chars[ ])
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
• You can specify a subrange of a character array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars
specifies the number of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
• You can construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
output
Java
Java
• The String class provides constructors that initialize a string when given a byte array.
Their forms are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify
a subrange. In each of these constructors, the byte-to-character conversion is done
by using the default character encoding of the platform. The following program
illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}}
output
ABCDEF
CDE
Methods
String Length
The length of a string is the number of characters that it contains. To obtain this value, call
the
int length( )
The following fragment prints “3”, since there are three characters in the string s:
String Concatenation
the + operator, which concatenates two strings, producing a String object as the result.
This allows you to chain together a series of + operations. For example, the following
fragment concatenates three strings or String Concatenation with Other Data Types:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
String s2 = "four: " + (2 + 2);
System.out.println(s2);
String Conversion
1.String.valueOf()
The String.valueOf() method converts int to String. The valueOf() is the static method of
String class. The signature of valueOf() method is given below:
public static String valueOf(int i)
example:
public class IntToStringExample1{
public static void main(String args[]){
int i=200;
String s=String.valueOf(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation operator
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
}}
Output:
300
200100
2.Integer.toString()
The Integer.toString() method converts int to String. The toString() is the static method of
Integer class. The signature of toString() method is given below:
public static String toString(int i)
Example:
public class IntToStringExample2{
public static void main(String args[]){
int i=200;
String s=Integer.toString(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation operator
}}
Output:
300
200100
3.String.format()
The String.format() method is used to format given arguments into String. It is introduced
since Jdk 1.5.
public static String format(String format, Object... args)
example:
public class IntToStringExample3{
public static void main(String args[]){
int i=200;
String s=String.format("%d",i);
System.out.println(s);
}}
Output
200
Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Each is examined here. Although the characters that comprise a string within
a String object cannot be indexed as if they were a character array, many of the String
methods employ an index (or offset) into the string for their operation. Like arrays, the
string indexes begin at zero.
charAt( )
To extract a single character from a String, you can refer directly to an individual character
via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must
be nonnegative and specify a location within the string. charAt( ) returns the character at
the specified location. For example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
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.
The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}}
output
demo
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions
provided by the platform. Here is its simplest form:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are
exporting a String value into an environment that does not support 16-bit Unicode
characters. For example, most Internet protocols and text file formats use 8-bit ASCII for
all text interchange.
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest
way is to call toCharArray( ). It returns an array of characters for the entire string. It has
this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve
the same result.
String s = "GeeksForGeeks";
char[] gfg = s.toCharArray();
System.out.println(gfg);
String Comparison
The String class includes several methods that compare strings or substrings within strings.
Each is examined here.
equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns true
if the strings contain the same characters in the same order, and false otherwise.
The comparison is case-sensitive. To perform a comparison that ignores case
differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be
the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns
true if the strings contain the same characters in the same order, and false otherwise.
Example:
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
output
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
regionMatches( )
The regionMatches() method of the String class has two variants that can be used to test
if two string regions are matching or equal.
Syntax:
1. Case sensitive test method:
public boolean regionMatches(int toffset, String other, int offset, int len)
2. It has the option to consider or ignore the case method:
public boolean regionMatches(boole+an ignoreCase, int toffset, String other,
int offset, int len)
Parameters:
• ignoreCase: if true, ignore the case when comparing characters.
• toffset: the starting offset of the subregion in this string.
• other: the string argument being compared.
• offset: the starting offset of the subregion in the string argument.
• len: the number of characters to compare.
Example:
// Java Program to find if substrings
// or regions of two strings are equal
import java.io.*;
class CheckIfRegionsEqual {
public static void main(String args[])
{
System.out.print("Foobar".endsWith("bar"))
System.out.print("Foobar".startsWith("Foo"))
Output
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
true
true.
Asecond form of startsWith( ), shown here, lets you specify a starting point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the invoking string at which point the search will
begin. For example,
System.out.print("Foobar".startsWith("bar", 3))
Output
true.
equals( ) Versus ==
The equals( ) method and the == operator perform two different operations.
The equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they refer to the same
instance.
The following program shows how two different String objects can contain the same
characters, but references to these objects will not compare as equal:
EXAMPLE:
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}}
The variable s1 refers to the String instance created by “Hello”. The object referred to by
s2 is created with s1 as an initializer. Thus, the contents of the two String objects are
identical, but they are distinct objects. This means that s1 and s2 do not refer to the same
objects and are, therefore, not ==, as is shown here by the output of the preceding
example:
Hello equals Hello -> true
Hello == Hello -> false
compareTo( )
Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next.
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted, as shown here:
0 if the string is equal to the other string.
< 0 if the string is lexicographically less than the other string
> 0 if the string is lexicographically greater than the other string (more characters)
Here is a sample program that sorts an array of strings. The program uses compareTo( )
to determine sort ordering for a bubble sort:
These two methods are overloaded in several different ways. In all cases, the methods
return the index at which the character or substring was found, or –1 on failure. To search
for the first occurrence of a character, use
int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the
search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs
from startIndex to zero. The following example shows how to use the various index
methods to search inside of Strings:
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use one of the following String
methods, which will construct a new copy of the string with your modifications complete.
substring( )
The substring() method has two variants and returns a new string that is a substring of
this string. The substring begins with the character at the specified index and extends to
the end of this string. Endindex of the substring starts from 1 and not from 0.
public String substring(int begIndex, int endIndex);
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.optional
example:
String Str = new String("Welcome to geeksforgeeks");
// using substring() to extract substring
System.out.println(Str.substring(10));
System.out.println(Str.substring(10, 16));
Output:
Geeksforgeeks
geeks
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str
appended to the end. concat( ) performs the same function as +. For example, String s1 =
"one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character. It has the following general form:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed. It has this general form:
String trim( )
Example:
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently
been entered by the user.
The java string valueOf() method converts different types of values into string. By the help
of string valueOf() method, you can convert int to string, long to string, boolean to string,
character to string, float to string, double to string, object to string and char array to string.
example:
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
Output
3010
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase
to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the
general
forms of these methods:
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that contains the uppercase or lowercase equivalent
of the invoking String.
Example
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Output:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
StringBuffer class and its constructors & StringBuffer methods :
(append(),insert(),update(), delete(), reverse(),capacity())
StringBuffer Class in Java:
String in general is a sequence of characters that is immutable(unchangeable) in
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
nature. But java provides a class called StringBuffer that facilitates the programmer to
create a string that is mutable in nature.
Every class in java has two main attributes:
1. Constructors
2. Methods
A string that facilitates modification or change is known as a mutable string. The
StringBuffer and StringBuilder classes allow us to create mutable strings.
StringBuffer Constructors in Java:
Constructor(Syntax) Description
Let us discuss some of the important methods present in Java StringBuffer class:
1. Java append():
This method is used to concatenate two strings.
Example
public class Append
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Data");
str.append("Flair");
System.out.println(str);
}
}
The output of the above code:
DataFlair
2. Java insert():
The insert method inserts the given string into the StringBuffer object at the given
position.
Example
public class Insert
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Data");
str.insert(4,"Flair");
System.out.println(str);
}
}
The output of the above code:
DataFlair
3. Java replace():
This method replaces the StringBuffer object with the specified string at the
specified position.
Example
public class Replace
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Data");
sb.replace(2,3,"Flair"); //from 2 to 3-1
System.out.println(sb);
}
}
The output of the above code:
DaFlaira
4. Java delete():
This method deletes the StringBuffer object from the specified position.
Example
public class Delete
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("DataFlair");
sb.delete(2,4);//delete ta
System.out.println(sb);
}
}
The output of the above code:
DaFlair
5. Java reverse():
This method is used to reverse the String present in the StringBuffer object.
Example
public class Reverse
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("DataFlair");
str.reverse();
System.out.println(str);
}
}
The output of the above code:
rialFataD
6. Java capacity():
The capacity() method returns the current capacity of the StringBuffer object. The default
capacity of the StringBuffer object is 16.
If the number of characters increases from its current capacity, it increases the capacity
by:(old capacity*2)+2.
For example, if your current capacity is 16, then the capacity will be calculated as:
(16*2)+2= 34.
Example
public class Capacity
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());// 16
sb.append("DataFlair");
System.out.println(sb.capacity());//16
sb.append("DataFlair is company that teaches programming!!!");
System.out.println(sb.capacity());//50
}
}
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement
5; therest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is whywe use exception handling in Java
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
that must be either caught or declared in the method signature using the
throws keyword.
For example, IOException, SQLException, etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException 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.
Try The "try" keyword is used to specify a block where we should place an
exception code(statement that causes an exception). 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.
a[10]=50; //ArrayIndexOutOfBoundsException
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled,JVM provides a
default exception handler that performs the following tasks:
But if the application programmer handles the exception, the normal flow of the
application ismaintained, i.e., rest of the code is executed.
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
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
Note: If you don't handle the exception, before terminating the program, JVM executesfinally
block (if any).
o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
C.B.PATEL COMPUTER COLLEGE (B.C.A.)
403-JAVA PROGRAMMING LANGUAGE
The syntax of the Java throw keyword is given below.throw Instance i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new NullPointerException ("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a
parameter. Ifthe age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
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...");
}
}
Example:
import java.util.*;
class TestThrow1 {
public static void main(String arg[])
{ try
{
System.out.print("enter m1");
Scanner s=new Scanner(System.in);
int m1=s.nextInt();
if (m1<0)
throw new ArithmeticException("invalid");
else
System.out.print("valid");
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}
Java throws Keyword
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class Main
{ static void checkAge(int age) throws ArithmeticException
{if (age < 18)
{throw new ArithmeticException("Access denied - You must be at least 18 years
old.");
}
Else
{System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Definition and Usage
The throws keyword indicates what exception type may be thrown by a method.There
are many exception types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException,
S ecurityException, etc.
Differences between throw and throws:
Throw Throws
Used to throw an exception for a Used to indicate what exception type may be
method thrown by a method
int age=15;
try
{
if(age<18)
// Throw an object of user defined exception
throw new MyException("Person is not eligible to vote");
}
catch (MyException ex)
{
System.out.println("Caught My Exception");
// Print the message from
MyException object
System.out.println(ex.getMessage()
);
}
finally
{
System.out.println(“I am always here”);
}
}
Output
Caught My Exception Person is not eligible to vote I am always here
Example
class invstd extends Exception
{invstd(String s)
{super(s);
}
}
class A{
public static void main(String arg[]) throws invstd
{ int std=Integer.parseInt(arg[0]);
if (std !=12)
{throw new invstd("invalid std");
}
else
System.out.print("welcome");
}
}
Runjava A 12 or java A 11