You are on page 1of 32

Java Programming

(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 {

public static void main(String[] args) {

// create first string

String first = "Java ";

System.out.println("First String: " + first);

// create second

String second = "Programming";

System.out.println("Second String: " + second);

// join two strings

String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);

Output :

First String: Java

Second String: Programming

Joined String: Java Programming


String Operator
3. Compare two Strings
 In Java, we can make comparisons between two strings using the equals() method. For example,
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}
Output :
Strings first and second are equal: true
Strings first and third are equal: false
Character Extraction
1. Extracting a Single Character
 Syntax : charAt(int index)
 The charAt() method returns the character value at the specified index.
class demo {
public static void main(String[] args) {
String str = "JavaGuides";
char ch = str.charAt(3);
System.out.println(ch);
}
}
 OUTPUT: a
Character Extraction
2. Extracting a Substring
 Syntax : substring(int beginIndex) and substring(int beginIndex, int endIndex)
 These methods return a new string that is a substring of the original string. The beginIndex is
inclusive, and the endIndex is exclusive.
class demo {
public static void main(String[] args) {
String str = "JavaGuides";
String subStr = str.substring(4, 10);
System.out.println(subStr);
}
}
 OUTPUT: Guides
Character Extraction
3. Extracting Characters into an Array
 The toCharArray method returns a newly allocated character array whose length is the length of the
string and whose contents are initialized to contain the character sequence represented by the
string.
 The getChars method copies characters from a string into the destination character array.
class demo {
public static void main(String[] args) {
String str = "JavaGuides";
char[] charArray = str.toCharArray();
System.out.println(charArray);
char[] dst = new char[5];
str.getChars(4, 9, dst, 0);
System.out.println(dst);
}
}

 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.

Replaces all occurrences of a specified character with another


replace(char oldChar, char newChar)
character.

substring(int beginIndex) Returns a substring from the specified index to the end.

Returns a substring from the specified beginning index to the


substring(int beginIndex, int endIndex)
end index.

toLowerCase() Converts all characters in the string to lowercase.

toUpperCase() Converts all characters in the string to upper case.

trim() Removes leading and trailing white spaces.

split(String regex) Splits the string around matches of the given regular expression.

Replaces each substring that matches the given regular


replaceAll(String regex, String replacement)
expression with the given replacement.

join(CharSequence delimiter, CharSequence...


Joins the given elements with the specified delimiter.
elements)
Searching Strings and Modifying Strings
1. concat(String str)
 Concatenates the specified string to the end of this string.
String str = "Java";
String result = str.concat("Guides");
// Result: "JavaGuides"
2. replace(char oldChar, char newChar)
 Replaces all occurrences of a specified character with another character.
String str = "Java";
String result = str.replace('a', 'o');
// Result: "Jovo“
3. toLowerCase() and toUpperCase()
Converts the string to lower case or upper case.
String str = "Java";
String lower = str.toLowerCase();
// Result: "java"
String upper = str.toUpperCase();
// Result: "JAVA"
Searching Strings and Modifying Strings
4. trim()
 Removes leading and trailing white spaces.
String str = " Java Guides ";
String result = str.trim();
// Result: "JavaGuides"
5. split(String regex)
 Splits the string around matches of the given regular expression.
String str = "Java,Guides";
String[] result = str.split(",");
// Result: ["Java", "Guides"]
6. replaceAll(String regex, String replacement)
 Replaces each substring that matches the given regular expression with the given replacement.
String str = "JavaGuides";
String result = str.replaceAll("a", "o");
// Result: "JovoGuides"
Buffer class and its methods
 StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string
without creating a new object every time.
 Here are some important features and methods of the StringBuffer class:
 StringBuffer objects are mutable, meaning that you can change the contents of the buffer
without creating a new object.
 The initial capacity of a StringBuffer can be specified when it is created, or it can be set later
with the ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the end of the
buffer.
 The insert() method is used to insert characters, strings, or other objects at a specified position
in the buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in the buffer.
Buffer class and its methods
Methods Action Performed
append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method

capacity() the total allocated capacity can be found by the capacity( ) method

This method returns the char value in this sequence at the


charAt()
specified index.

delete() Deletes a sequence of characters from the invoking object

deleteCharAt() Deletes the character at the index specified by the loc

ensureCapacity() Ensures capacity is at least equal to the given minimum.

insert() Inserts text at the specified index position

length() Returns the length of the string

reverse() Reverse the characters within a StringBuffer object

Replace one set of characters with another set inside a


replace()
StringBuffer object
Buffer class and its methods
1. append() method
 The append() method concatenates the given argument with this string.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
Output : Hello Java
Buffer class and its methods
2. insert() method
 The insert() method inserts the given string with this string at the given position.
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb);
}
}

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!!!!!

You might also like