Professional Documents
Culture Documents
Unit VI String - Handling
Unit VI String - Handling
(PCMC1050T)
Prof. Priya Kardile
Unit-VI - String Handling
String Constructors
Special String operators
Character Extraction
String Comparison
Searching Strings and Modifying Strings
Buffer class and its methods
String Basics
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.
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.
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.
Syntax :
String s=new String();
Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
String Constructors
String class supports several types of constructors in Java APIs.
The most commonly used constructors of the String class are as follows:
1. String()
2. String(String str)
3. String(char chars[ ])
4. String(char chars[ ], int startIndex, int count)
5. String(byte byteArr[ ])
6. String(byte byteArr[ ], int startIndex, int count)
1. String():
To create an empty String, we will call the default constructor.
Syntax:
String s=new String();
It will create a string object in the heap area with no value.
String Constructors
2. String(String str):
It will create a string object in the heap area and stores the given value in it.
Syntax:
String st = new String(String str);
Example:
String s2 = new String(“Hello Java”);
Here, the object str contains Hello Java.
3. String(char chars[ ]):
This constructor creates a string object and stores the array of characters in it.
Syntax:
String st = new String(char char[]);
Example:
char chars[] = {‘j’,’a’,’v’,’a’};
String s2 = new String(chars);
String Constructors
4. String(char chars[ ], int startIndex, int count):
This constructor creates and initializes a string object with a subrange of a character array.
The argument startIndex specifies the index at which the subrange begins and count specifies the
number of characters to be copied.
Syntax:
String str = new String(char chars[ ], int startIndex, int count);
Example:
char chars[] = {‘w’,’i’,’n’,’d’,’o’,’w’,’s’};
String str = new String(chars,2,3);
5. String(byte byteArr[ ]):
This constructor constructs a new string object by decoding the given array of bytes (i.e., by
decoding ASCII values into the characters) according to the system’s default character set.
String Constructors
5. String(byte byteArr[ ]):
Example:
public class demo
{
public static void main(String[] args)
{
byte b[] = { 97, 98, 99, 100 };
String s = new String(b);
System.out.println(s);
}
}
OUTPUT:
abcd
String Constructors
6. String(byte byteArr[ ], int startIndex, int count):
This constructor also creates a new string object by decoding the ASCII values using the system’s
default character set.
Example:
public class demo
{
public static void main(String[] args)
{
byte b[] = { 65, 66, 67, 68, 69, 70 };
String s = new String(b, 2, 4); // CDEF
System.out.println(s);
}
}
OUTPUT: CDEF
String Operator
• Java String provides various methods to perform different operations on strings. We will look into some of the commonly used
string operations.
1. Get length of a String:-
To find the length of a string, we use the length() method of the String. For example,
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}
}
Output :
String: Hello! World
Length: 12
String Operator
2. Join Two Java Strings
We can join two strings in Java using the concat() method. For example,
class Main {
// create second
Output :
OUTPUT: JavaGuides
Guide
Character Extraction
String Comparison
We can compare String in Java on the basis of content and reference.
There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method
1) By Using equals() Method:-
The String class equals() method compares the original content of the string. It
compares values of string for equality. String class provides the following two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.
String Comparison
class demo{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4=new String("Saurav");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}
Output: - true
true
false
String Comparison
class demo{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
}
}
Output :
false
true
In the above program, the methods of String class are used. The equals() method
returns true if String objects are matching and both strings are of same
case. equalsIgnoreCase() returns true regardless of cases of strings.
String Comparison
2) By Using == operator:-
The == operator compares references not values.
class demo{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
System.out.println(s1==s2);
}
}
Output :
true
String Comparison
3) By Using compareTo() method:-
The String class compareTo() method compares values and returns an integer value that
describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two String objects. If:
i. s1 == s2 : The method returns 0.
ii. s1 > s2 : The method returns a positive value(1,0).(s1 greater than s2)
iii. s1 < s2 : The method returns a negative value(-1,-0).(s1 less than s2)
class demo{
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 greater than s3)
System.out.println(s3.compareTo(s1));//-1(because s3 less than s1 )
}
}
Searching Strings and Modifying Strings
Method Description
concat(String str) Concatenates the specified string to the end of this string.
substring(int beginIndex) Returns a substring from the specified index to the end.
split(String regex) Splits the string around matches of the given regular expression.
capacity() the total allocated capacity can be found by the capacity( ) method
Output : HJavaello
Buffer class and its methods
3. replace() method
The replace() method replaces the given string from the specified beginIndex and
endIndex-1.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.replace(0, 3, "Java");
System.out.println(sb);
}
} Output : Javalo
Buffer class and its methods
4. delete() method
The delete() method of the StringBuffer class deletes the string from the specified
beginIndex to endIndex-1.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.delete(0, 2);
System.out.println(sb);
}
}
Output : llo
Buffer class and its methods
5. reverse() method
The reverse() method of the StringBuilder class reverses the current string.
import java.io.* ;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);
}
}
Output : olleH
Buffer class and its methods
6. capacity() method
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If
the number of characters increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.
For instance, if your current capacity is 16, it will be (16*2)+2=34.
import java.io.*;
class A {
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
}
}
Output : 16
16
34
Thank You!!!!!