SlideShare a Scribd company logo
MODULE 2
String Handling
Java Strings
• In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
• We use double quotes to represent a string in Java. For example
/ create a string
String type = "Java programming“
Here, we have created a string variable named type. The variable is initialized with
the string Java Programming.
Example: Create a String in Java
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
String length
• The length() method returns the number of characters in a string.
Example
class Main {
public static void main(String[] args) {
String str1 = "Java is fun";
// returns the length of str1
int length = str1.length();
System.out.println(str1.length());
}
}
// Output: 11
String length
length() Syntax
• The syntax of the string's length() method is:
string.length()
length() Arguments
The length() method doesn't take any arguments.
length() Return Value
The length() method returns the length of a given string.
Example: Java String length()
class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "";
System.out.println(str1.length()); // 4
System.out.println("Java".length()); // 4
// length of empty string
System.out.println(str2.length()); // 0
// new line is considered a single character
System.out.println("Javan".length()); // 5
System.out.println("Learn Java".length()); // 10
}
String constructors
• In Java, strings are represented by the String class, which is part of the
java.lang package (automatically imported in every Java program).
• The String class provides multiple ways (constructors) to create and
initialize string objects.
String constructors in java
• String()
• String(String str)
• String(char chars[ ])
• String(char chars[ ], int startIndex, int count)
• String(byte byteArr[ ])
• String(byte byteArr[ ], int startIndex, int count)
String()
• To create an empty string, we will call the default constructor. The
general syntax to create an empty string in Java program is as follows:
String s = new String();
• It will create a string object in the heap area with no value.
String(String str)
• This constructor will create a new string object in the heap area and
stores the given value in it. The general syntax to construct a string
object with the specified string str is as follows:
String st = new String(String str);
For example:
String s2 = new String("Hello Java");
Here, the object str contains Hello Java.
String(char chars[ ])
• This string constructor creates a string object and stores the array of characters in
it. The general syntax to create a string object with a specified array of characters
is as follows:
String str = new String(char char[])
For example:
char chars[] = { 'a', 'b', 'c', 'd' };
String s3 = new String(chars);
The object reference variable s3 contains the address of the value stored in the heap
area.
//we will create a string object and store an array of
characters in it.
package stringPrograms;
public class Science {
public static void main(String[ ] args)
{
char chars[] = {'s', 'c', 'i', 'e', 'n', 'c', 'e'};
String s = new String(chars);
System.out.println(s);
}
}
Output:
science
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. The
general syntax to create a string object with the specified subrange of
character array is as follows:
4. String(char chars[ ], int startIndex, int count)
String str = new String(char chars[ ], int startIndex, int count);
For example:
char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };
String str = new String(chars, 2, 3);
The object str contains the address of the value ”ndo” stored in the heap area
because the starting index is 2 and the total number of characters to be copied is 3.
package stringPrograms;
public class Windows {
public static void main(String[] args)
{
char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' };
String s = new String(chars, 0,4);
System.out.println(s);
}
}
Output:
wind
Java program where we will create a string object that contains the same characters sequence as
another string object.
package stringPrograms;
public class MakeString {
public static void main(String[] args)
{
char chars[] = { 'F', 'A', 'N' };
String s1 = new String(chars);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
FAN
FAN
5. String(byte byteArr[ ])
• This type of string 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.
package stringPrograms;
public class ByteArray {
public static void main(String[] args)
{
byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be
converted into corresponding characters.
String s = new String(b);
System.out.println(s);
}
}
Output:
abcd
Special string operations in JAVA
• String literals
• Concatenation of strings
• String Conversion using toString( )
• Character extraction
• String comparison
string literals
string literal in your program, Java automatically constructs a String object.
Thus string literal can be used to initialize a String object.
For example, the following code fragment creates two equivalent strings:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
● String object is created for every string literal, you can use a string literal
any place you can use a String object.
For example, you can call methods directly on a quoted string as if it were an object
reference, as the following statement shows.
It calls the length( ) method on the string “abc”. As expected, it prints “3”.
System.out.println("abc".length());
Concatenation of Strings
Java does not allow operators to be applied to String objects.
The one exception to this rule is the + operator, which concatenates two
strings, producing a String object as the result.
String age = "9";
String s = "He is " + age + " years old.";
This displays the string “He is 9 years old.”
String Concatenation with Other Data Types
You can concatenate strings with other types of data.
Be careful when you mix other types of operations with string concatenation
expressions,
however.
String in java, string constructors and operations
String Conversion using toString( )
• If you want to represent any object as a string, toString() method comes into
existence.
• The toString() method returns the String representation of the object.
• If you print any object, Java compiler internally invokes the toString() method on
the object. So overriding the toString() method, returns the desired output, it can
be the state of an object etc. depending on your implementation.
• By overriding the toString() method of the Object class, we can return values of
the object, so we don't need to write much code.
Understanding problem without toString() method
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc
in the above example, printing s1 and s2 prints the hashcode values of
the objects but I want to print the values of these objects. Since Java
compiler internally calls toString() method, overriding this method will
return the specified values.
Example of Java toString() method
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
101 Raj lucknow
102 Vijay ghaziabad
Character extraction
• The String class in Java provides several ways to extract characters from a String object
1. charAt(int index):
This method is used to return the char value at the specified index.
The value of the index must be nonnegative and specify a location within the string.
For example:
char ch;
ch = "abc".charAt(1);
Result:
assigns the value “b” to ch.
Character extraction
2. getChars( )
• To extract more than one character from a String object, we can use this method.
General form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
• Here, sourceStart specifies the starting index of the substring, and sourceEnd specifies an
index that is one past the end of the desired substring. The variable target specifies the
resultant array.
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
3. getBytes( ):
This is an alternative method to getChars( ). It stores the characters in a byte array.
General form:
byte[ ] getBytes( )
4. toCharArray( )
To convert all the characters of a String object into a character array, this method is used.
It returns a character array for the given string.
General form:
char[ ] toCharArray( )
String Comparison
• The String class in Java includes several methods to compare strings
or substrings
• Some of the important string operations in Java to compare strings are
given below:
1. equals( ) and equalsIgnoreCase( )
2. compareTo()
3. compareToIgnoreCase():
1. equals( ) and equalsIgnoreCase( )
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.
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.
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
Output :
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
The equals( ) method and the “==”operator perform different functions.
The equals( ) method compares the characters of a String object, whereas the ==
operator compares the references of two string objects to see whether they refer
to the same instance.
A simple program to demonstrate the above difference is given below:
The variable s1 is pointing to the String "Hello". The object pointed by s2 is
constructed with the help of s1. Thus, the values inside the two String objects are
the same, but they are distinct objects.
class Demo
{
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));
}
}
Output:
Hello equals Hello -> true
Hello == Hello -> false
2. compareTo()
The compareTo() method of the Java String class compares the string lexicographically. It returns a
positive, negative, or zero value. To perform a sorting operation on strings, the compareTo() method
comes in handy.
A string is less than another if it comes before in the dictionary order.
A string is greater than another if it comes after in the dictionary order.
General form:
int compareTo(String str)
Here, str is the string being compared with the invoking string.
class SortStringFunc
{
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men","to", "come", "to",
"the", "aid", "of", "their", "country" };
public static void main(String args[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Output:
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
3. compareToIgnoreCase():
This method is the same as compareTo( ), but it ignores the lowercase and
uppercase differences of the strings while comparing.
Searching Strings
The Java String class provides two methods that allow us to search a
character or substring in another string.
• indexOf( ): It searches the first occurrence of a character or substring.
• lastIndexOf( ): It searches the last occurrence of a character or
substring.
class indexOfDemo
{
public static void main(String args[])
{
String s = "Now is the time for all good men " + "to come to the aid of their
country.";
System.out.println(s);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}
Output:
Now is the time for all good men to come to
their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String
1. substring( )
2. concat( )
3. replace( )
4. trim( )
1. substring( )
• As the name suggests, ‘sub + string’, is a subset of a string. By subset, we
mean the contiguous part of a character array or string.
• The substring() method is used to fetch a substring from a string in Java.
General form:
• String substring(int startIndex)
• String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and endIndex specifies
the stopping point.
• The string returned contains all the characters from the beginning index,
up to, but not including, the ending index i.e [startindex,endindex-1]
/ Substring replacement.
class StringReplace
{
public static void main(String args[])
{
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do {
// replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1)
{
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
Output :
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
2. concat( )
• To concatenate two strings in Java, we can use the concat( ) method
apart from the “+” operator.
• General form:
• String concat(String str)
• This method creates a new object containing the invoking string with
the str appended to the end. This performs the same function as the +
operator. Refer to the comparison table below:
String in java, string constructors and operations
3. replace( )
• This method is used to replace a character with some other character in a string. It has two forms.
• The first replaces all occurrences of one character in the invoking string with another character.
• General form:
• String replace(char original, char replacement)
• Here, the original specifies the character to be replaced by the character specified by replacement.
The resulting string is returned.
• For example:
String s = "Hello".replace('l', 'w’);
Result: s= “Hewwo”
3. replace( )
• The second form replaces one character sequence with
another.
• General form:
• String replace(CharSequence original, CharSequence
replacement)
4. trim( )
• The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed.
General form:
• String trim( )
For example:
• String s = " Hello World ".trim();
• Result: s= “Hello World”
Data Conversion Using valueOf( )
• For converting different data types into strings, the valueOf() method is used. It is a static method
defined in the Java String class.
General form:
• static String valueOf(double num)
• static String valueOf(long num)
• static String valueOf(Object ob)
• static String valueOf(char chars[ ])
For example:
int num=20;
String s1=String.valueOf(num);
s1 = s1+10; //concatenating string s1 with 10
Result s1=2010
Changing the Case of Characters in a String
• 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.
// 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.
Joining strings
• In Java, you can join strings using the String.join() method. This method
allows you to concatenate multiple strings with a specified delimiter.
String fruits = String.join(" ", "Orange", "Apple", "Mango");
System.out.println(fruits);
The join() method takes two parameters.
delimiter - the delimiter to be joined with the elements
elements - elements to be joined
Syntax()
String.join(CharSequence delimiter, CharSequence... elements)
Here, ... signifies there can be one or more CharSequence.
String.join(CharSequence delimiter, Iterable elements)
class Main {
public static void main(String[] args) {
String str1 = "I";
String str2 = "love";
String str3 = "Java";
// join strings with space between them
String joinedStr = String.join(" ", str1, str2, str3);
System.out.println(joinedStr);
}
}
// Output: I love Java
class Main {
public static void main(String[] args) {
String result;
result = String.join("-", "Java", "is", "fun");
System.out.println(result); // Java-is-fun
}
}
StringBuffer in Java
• StringBuffer is a class in the java.lang package that represents a mutable sequence
of characters.
• Unlike the String class, StringBuffer allows you to modify the content of the
string object after it has been created.
StringBuffer buffer = new StringBuffer("Hello, ");
buffer.append("World!"); // appends to the existing value
buffer.insert(7, "Java "); // inserts at a specified index
buffer.reverse(); // reverses the characters
System.out.println(buffer); // prints: "!dlroW avaJ ,olleH"
Key Features of StringBuffer
• Mutable: StringBuffer provides the flexibility to change the content, making it ideal
for scenarios where you have to modify strings frequently.
• Synchronized: Being thread-safe, it ensures that only one thread can access the
buffer's methods at a time, making it suitable for multi-threaded environments.
• Performance Efficient: For repeated string manipulation, using StringBuffer can be
more efficient than the String class.
• Method Availability: StringBuffer offers several methods to manipulate strings.
These include append(), insert(), delete(), reverse(), and replace().
When to Use StringBuffer?
• When you need to perform several modifications to strings,
using StringBuffer is an efficient choice.
• Due to the mutability of StringBuffer, it doesn't create a new object for every
modification, leading to less memory consumption and improved
performance.
• StringBuffer is especially beneficial in a multithreaded environment due to its
synchronized methods, ensuring thread safety
1. append()
• The append() method adds the specified value to the end of the current
string.
StringBuffer buffer = new StringBuffer("javaguides");
buffer.append(" - For Beginners");
System.out.println(buffer);
// Output: "javaguides - For Beginners"
2. insert()
• The insert() method adds the specified value at the given index.
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
3. delete()
• 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(1, 3);
System.out.println(sb);
}}
Output
Hlo
4.replace()
• 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(1, 3, "Java");
System.out.println(sb);
}
}
Output
HJavalo
5.reverse()
• The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6.capacity()
• 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 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
}
}
Output:
16
16
34
7.ensureCapacity()
• The ensureCapacity() method of the 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
}
}
Output:
16
16
34
34
70
Important Constructors of StringBuffer Class
Constructor with CharSequence
StringBuilder sb = new StringBuilder(CharSequence seq);
This constructor creates a StringBuilder instance that contains the same characters as the specified
CharSequence. Like the constructor with a string, the initial capacity will be the length of the CharSequence
plus 16.
public class StringBuilderExample {
public static void main(String[] args) {
// Default constructor
StringBuilder sb1 = new StringBuilder();
sb1.append("Hello, World!");
System.out.println(sb1);
// Constructor with initial capacity
StringBuilder sb2 = new StringBuilder(50);
sb2.append("Initial capacity set to 50.");
System.out.println(sb2);
// Constructor with initial string
StringBuilder sb3 = new StringBuilder("Initial String");
sb3.append(" appended text.");
System.out.println(sb3);
// Constructor with CharSequence
CharSequence seq = "CharSequence example";
StringBuilder sb4 = new StringBuilder(seq);
sb4.append(" additional text.");
System.out.println(sb4);
}
}
output
Hello, World!
Initial capacity set to 50.
Initial String appended text.
CharSequence example additional text.
String builder
• A StringBuilder is a mutable sequence of characters used in
programming languages such as Java, C#, and others.
• It is designed to efficiently handle strings that undergo multiple
modifications, such as concatenations, insertions, deletions, or
appending operations.
• Unlike immutable string objects, StringBuilder allows for these
operations without creating new string objects, making it more
performance-efficient, especially in scenarios involving extensive
string manipulation.
• append: Appends the specified data to the end of the StringBuilder.
sb.append("Hello");
sb.append(123);
sb.append(true);
insert: Inserts the specified data at the specified position.
sb.insert(0, "Start: ");
delete: Removes the characters in a substring of this sequence.
sb.delete(5, 10);
deleteCharAt: Removes the character at the specified position.
sb.deleteCharAt(0);
commonly used methods of StringBuilder:
replace: Replaces the characters in a substring of this sequence with characters in the specified
string.
sb.replace(0, 5, "Hi");
reverse: Reverses the sequence of characters.
sb.reverse();
toString: Converts the StringBuilder to a String.
String result = sb.toString();
setLength: Sets the length of the character sequence.
sb.setLength(10);
commonly used methods of StringBuilder:
public class StringBuilderExample {
public static void main(String[] args) {
// Default constructor
StringBuilder sb = new StringBuilder();
// Appending different types of data
sb.append("Hello, ");
sb.append("World!");
sb.append(" Number: ").append(42);
sb.append(" Boolean: ").append(true);
System.out.println(sb.toString());
// Inserting text
sb.insert(7, "Java ");
System.out.println(sb.toString());
// Deleting text
sb.delete(7, 12);
System.out.println(sb.toString());
// Replacing text
sb.replace(7, 12, "Universe");
System.out.println(sb.toString());
// Reversing the sequence
sb.reverse();
System.out.println(sb.toString());
// Converting to String
String result = sb.toString();
System.out.println("Final result: " + result);
}
}
OUTPUT
Hello, World! Number: 42 Boolean: true
Hello, Java World! Number: 42 Boolean: true
Hello, World! Number: 42 Boolean: true
Hello, Universe! Number: 42 Boolean: true
eurt :naelooB 24 :rebmuN !esrevinU ,olleH
Final result: eurt :naelooB 24 :rebmuN !esrevinU ,olleH

More Related Content

PPTX
Java string handling
GaneshKumarKanthiah
 
PPTX
Java String
SATYAM SHRIVASTAV
 
PPTX
Constructors in java
chauhankapil
 
PPTX
Java arrays
Jin Castor
 
PPTX
EJB3 Basics
Emprovise
 
PPT
String Handling
Bharat17485
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PDF
Spring boot jpa
Hamid Ghorbani
 
Java string handling
GaneshKumarKanthiah
 
Java String
SATYAM SHRIVASTAV
 
Constructors in java
chauhankapil
 
Java arrays
Jin Castor
 
EJB3 Basics
Emprovise
 
String Handling
Bharat17485
 
9. Input Output in java
Nilesh Dalvi
 
Spring boot jpa
Hamid Ghorbani
 

What's hot (20)

PPTX
Java string handling
Salman Khan
 
PPSX
OOP with Java - Continued
Hitesh-Java
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
PPS
Introduction to class in java
kamal kotecha
 
PPTX
java input & output statements
VigneshManikandan11
 
PPTX
OOPs in Java
Ranjith Sekar
 
PPTX
Basic Graphics in Java
Prakash Kumar
 
PDF
Java String
Java2Blog
 
PDF
Strings in java
Kuppusamy P
 
PPTX
Servlets
Akshay Ballarpure
 
PPTX
Java Strings
RaBiya Chaudhry
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PPT
Java Threads and Concurrency
Sunil OS
 
PDF
Java Thread Synchronization
Benj Del Mundo
 
PPTX
Exceptions in Java
Vadym Lotar
 
PDF
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
PPTX
C programming - String
Achyut Devkota
 
PPT
Oop java
Minal Maniar
 
Java string handling
Salman Khan
 
OOP with Java - Continued
Hitesh-Java
 
20.3 Java encapsulation
Intro C# Book
 
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Introduction to class in java
kamal kotecha
 
java input & output statements
VigneshManikandan11
 
OOPs in Java
Ranjith Sekar
 
Basic Graphics in Java
Prakash Kumar
 
Java String
Java2Blog
 
Strings in java
Kuppusamy P
 
Java Strings
RaBiya Chaudhry
 
Java 8 Lambda Expressions
Scott Leberknight
 
Java Threads and Concurrency
Sunil OS
 
Java Thread Synchronization
Benj Del Mundo
 
Exceptions in Java
Vadym Lotar
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C programming - String
Achyut Devkota
 
Oop java
Minal Maniar
 
Ad

Similar to String in java, string constructors and operations (20)

PPTX
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
PPTX
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
PPTX
10619416141061941614.106194161fff4..pptx
Shwetamaurya36
 
PPTX
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
PPTX
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
PPS
String and string buffer
kamal kotecha
 
PPTX
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
PPTX
Strings in Java
Abhilash Nair
 
PPT
String classes and its methods.20
myrajendra
 
PPTX
Java string , string buffer and wrapper class
SimoniShah6
 
PDF
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PPTX
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
PDF
String notes
Prasadu Peddi
 
PPTX
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
PPTX
L13 string handling(string class)
teach4uin
 
PPTX
Programing with java for begniers .pptx
adityaraj7711
 
PPT
String and string manipulation
Shahjahan Samoon
 
PPTX
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
10619416141061941614.106194161fff4..pptx
Shwetamaurya36
 
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
String and string buffer
kamal kotecha
 
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
Strings in Java
Abhilash Nair
 
String classes and its methods.20
myrajendra
 
Java string , string buffer and wrapper class
SimoniShah6
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
String notes
Prasadu Peddi
 
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
L13 string handling(string class)
teach4uin
 
Programing with java for begniers .pptx
adityaraj7711
 
String and string manipulation
Shahjahan Samoon
 
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
Ad

Recently uploaded (20)

PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
Ppt for engineering students application on field effect
lakshmi.ec
 
Information Retrieval and Extraction - Module 7
premSankar19
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Introduction to Data Science: data science process
ShivarkarSandip
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 

String in java, string constructors and operations

  • 2. Java Strings • In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'. • We use double quotes to represent a string in Java. For example / create a string String type = "Java programming“ Here, we have created a string variable named type. The variable is initialized with the string Java Programming.
  • 3. Example: Create a String in Java class Main { public static void main(String[] args) { // create strings String first = "Java"; String second = "Python"; String third = "JavaScript"; // print strings System.out.println(first); // print Java System.out.println(second); // print Python System.out.println(third); // print JavaScript } }
  • 4. String length • The length() method returns the number of characters in a string. Example class Main { public static void main(String[] args) { String str1 = "Java is fun"; // returns the length of str1 int length = str1.length(); System.out.println(str1.length()); } } // Output: 11
  • 5. String length length() Syntax • The syntax of the string's length() method is: string.length() length() Arguments The length() method doesn't take any arguments. length() Return Value The length() method returns the length of a given string.
  • 6. Example: Java String length() class Main { public static void main(String[] args) { String str1 = "Java"; String str2 = ""; System.out.println(str1.length()); // 4 System.out.println("Java".length()); // 4 // length of empty string System.out.println(str2.length()); // 0 // new line is considered a single character System.out.println("Javan".length()); // 5 System.out.println("Learn Java".length()); // 10 }
  • 7. String constructors • In Java, strings are represented by the String class, which is part of the java.lang package (automatically imported in every Java program). • The String class provides multiple ways (constructors) to create and initialize string objects.
  • 8. String constructors in java • String() • String(String str) • String(char chars[ ]) • String(char chars[ ], int startIndex, int count) • String(byte byteArr[ ]) • String(byte byteArr[ ], int startIndex, int count)
  • 9. String() • To create an empty string, we will call the default constructor. The general syntax to create an empty string in Java program is as follows: String s = new String(); • It will create a string object in the heap area with no value.
  • 10. String(String str) • This constructor will create a new string object in the heap area and stores the given value in it. The general syntax to construct a string object with the specified string str is as follows: String st = new String(String str); For example: String s2 = new String("Hello Java"); Here, the object str contains Hello Java.
  • 11. String(char chars[ ]) • This string constructor creates a string object and stores the array of characters in it. The general syntax to create a string object with a specified array of characters is as follows: String str = new String(char char[]) For example: char chars[] = { 'a', 'b', 'c', 'd' }; String s3 = new String(chars); The object reference variable s3 contains the address of the value stored in the heap area.
  • 12. //we will create a string object and store an array of characters in it. package stringPrograms; public class Science { public static void main(String[ ] args) { char chars[] = {'s', 'c', 'i', 'e', 'n', 'c', 'e'}; String s = new String(chars); System.out.println(s); } } Output: science
  • 13. 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. The general syntax to create a string object with the specified subrange of character array is as follows:
  • 14. 4. String(char chars[ ], int startIndex, int count) String str = new String(char chars[ ], int startIndex, int count); For example: char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' }; String str = new String(chars, 2, 3); The object str contains the address of the value ”ndo” stored in the heap area because the starting index is 2 and the total number of characters to be copied is 3.
  • 15. package stringPrograms; public class Windows { public static void main(String[] args) { char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' }; String s = new String(chars, 0,4); System.out.println(s); } } Output: wind
  • 16. Java program where we will create a string object that contains the same characters sequence as another string object. package stringPrograms; public class MakeString { public static void main(String[] args) { char chars[] = { 'F', 'A', 'N' }; String s1 = new String(chars); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } Output: FAN FAN
  • 17. 5. String(byte byteArr[ ]) • This type of string 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. package stringPrograms; public class ByteArray { public static void main(String[] args) { byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be converted into corresponding characters. String s = new String(b); System.out.println(s); } } Output: abcd
  • 18. Special string operations in JAVA • String literals • Concatenation of strings • String Conversion using toString( ) • Character extraction • String comparison
  • 19. string literals string literal in your program, Java automatically constructs a String object. Thus string literal can be used to initialize a String object. For example, the following code fragment creates two equivalent strings: char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; // use string literal ● String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string “abc”. As expected, it prints “3”. System.out.println("abc".length());
  • 20. Concatenation of Strings Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. String age = "9"; String s = "He is " + age + " years old."; This displays the string “He is 9 years old.” String Concatenation with Other Data Types You can concatenate strings with other types of data. Be careful when you mix other types of operations with string concatenation expressions, however.
  • 22. String Conversion using toString( ) • If you want to represent any object as a string, toString() method comes into existence. • The toString() method returns the String representation of the object. • If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation. • By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
  • 23. Understanding problem without toString() method class Student{ int rollno; String name; String city; Student(int rollno, String name, String city){ this.rollno=rollno; this.name=name; this.city=city; } public static void main(String args[]){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println(s1);//compiler writes here s1.toString() System.out.println(s2);//compiler writes here s2.toString() } } Output: Student@1fee6fc in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString() method, overriding this method will return the specified values.
  • 24. Example of Java toString() method class Student{ int rollno; String name; String city; Student(int rollno, String name, String city){ this.rollno=rollno; this.name=name; this.city=city; } public String toString(){//overriding the toString() method return rollno+" "+name+" "+city; } public static void main(String args[]){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println(s1);//compiler writes here s1.toString() System.out.println(s2);//compiler writes here s2.toString() } } Output: 101 Raj lucknow 102 Vijay ghaziabad
  • 25. Character extraction • The String class in Java provides several ways to extract characters from a String object 1. charAt(int index): This method is used to return the char value at the specified index. The value of the index must be nonnegative and specify a location within the string. For example: char ch; ch = "abc".charAt(1); Result: assigns the value “b” to ch.
  • 26. Character extraction 2. getChars( ) • To extract more than one character from a String object, we can use this method. General form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) • Here, sourceStart specifies the starting index of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. The variable target specifies the resultant array.
  • 27. 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
  • 28. 3. getBytes( ): This is an alternative method to getChars( ). It stores the characters in a byte array. General form: byte[ ] getBytes( ) 4. toCharArray( ) To convert all the characters of a String object into a character array, this method is used. It returns a character array for the given string. General form: char[ ] toCharArray( )
  • 29. String Comparison • The String class in Java includes several methods to compare strings or substrings • Some of the important string operations in Java to compare strings are given below: 1. equals( ) and equalsIgnoreCase( ) 2. compareTo() 3. compareToIgnoreCase():
  • 30. 1. equals( ) and equalsIgnoreCase( ) 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. 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.
  • 31. class equalsDemo { public static void main(String args[]) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); } } Output : Hello equals Hello -> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true
  • 32. The equals( ) method and the “==”operator perform different functions. The equals( ) method compares the characters of a String object, whereas the == operator compares the references of two string objects to see whether they refer to the same instance. A simple program to demonstrate the above difference is given below: The variable s1 is pointing to the String "Hello". The object pointed by s2 is constructed with the help of s1. Thus, the values inside the two String objects are the same, but they are distinct objects.
  • 33. class Demo { 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)); } } Output: Hello equals Hello -> true Hello == Hello -> false
  • 34. 2. compareTo() The compareTo() method of the Java String class compares the string lexicographically. It returns a positive, negative, or zero value. To perform a sorting operation on strings, the compareTo() method comes in handy. A string is less than another if it comes before in the dictionary order. A string is greater than another if it comes after in the dictionary order. General form: int compareTo(String str) Here, str is the string being compared with the invoking string.
  • 35. class SortStringFunc { static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men","to", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } } Output: Now aid all come country for good is men of the the their time to to
  • 36. 3. compareToIgnoreCase(): This method is the same as compareTo( ), but it ignores the lowercase and uppercase differences of the strings while comparing.
  • 37. Searching Strings The Java String class provides two methods that allow us to search a character or substring in another string. • indexOf( ): It searches the first occurrence of a character or substring. • lastIndexOf( ): It searches the last occurrence of a character or substring.
  • 38. class indexOfDemo { public static void main(String args[]) { String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println(s); System.out.println("indexOf(t) = " + s.indexOf('t')); System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t')); System.out.println("indexOf(the) = " + s.indexOf("the")); System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the")); System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10)); System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60)); System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10)); System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60)); } } Output: Now is the time for all good men to come to their country. indexOf(t) = 7 lastIndexOf(t) = 65 indexOf(the) = 7 lastIndexOf(the) = 55 indexOf(t, 10) = 11 lastIndexOf(t, 60) = 55 indexOf(the, 10) = 44 lastIndexOf(the, 60) = 55
  • 39. Modifying a String 1. substring( ) 2. concat( ) 3. replace( ) 4. trim( )
  • 40. 1. substring( ) • As the name suggests, ‘sub + string’, is a subset of a string. By subset, we mean the contiguous part of a character array or string. • The substring() method is used to fetch a substring from a string in Java. General form: • String substring(int startIndex) • String substring(int startIndex, int endIndex) • Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. • The string returned contains all the characters from the beginning index, up to, but not including, the ending index i.e [startindex,endindex-1]
  • 41. / Substring replacement. class StringReplace { public static void main(String args[]) { String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i; do { // replace all matching substrings System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org = result; } } while(i != -1); } } Output : This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too.
  • 42. 2. concat( ) • To concatenate two strings in Java, we can use the concat( ) method apart from the “+” operator. • General form: • String concat(String str) • This method creates a new object containing the invoking string with the str appended to the end. This performs the same function as the + operator. Refer to the comparison table below:
  • 44. 3. replace( ) • This method is used to replace a character with some other character in a string. It has two forms. • The first replaces all occurrences of one character in the invoking string with another character. • General form: • String replace(char original, char replacement) • Here, the original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. • For example: String s = "Hello".replace('l', 'w’); Result: s= “Hewwo”
  • 45. 3. replace( ) • The second form replaces one character sequence with another. • General form: • String replace(CharSequence original, CharSequence replacement)
  • 46. 4. trim( ) • The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. General form: • String trim( ) For example: • String s = " Hello World ".trim(); • Result: s= “Hello World”
  • 47. Data Conversion Using valueOf( ) • For converting different data types into strings, the valueOf() method is used. It is a static method defined in the Java String class. General form: • static String valueOf(double num) • static String valueOf(long num) • static String valueOf(Object ob) • static String valueOf(char chars[ ]) For example: int num=20; String s1=String.valueOf(num); s1 = s1+10; //concatenating string s1 with 10 Result s1=2010
  • 48. Changing the Case of Characters in a String • 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.
  • 49. // 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.
  • 50. Joining strings • In Java, you can join strings using the String.join() method. This method allows you to concatenate multiple strings with a specified delimiter. String fruits = String.join(" ", "Orange", "Apple", "Mango"); System.out.println(fruits); The join() method takes two parameters. delimiter - the delimiter to be joined with the elements elements - elements to be joined
  • 51. Syntax() String.join(CharSequence delimiter, CharSequence... elements) Here, ... signifies there can be one or more CharSequence. String.join(CharSequence delimiter, Iterable elements)
  • 52. class Main { public static void main(String[] args) { String str1 = "I"; String str2 = "love"; String str3 = "Java"; // join strings with space between them String joinedStr = String.join(" ", str1, str2, str3); System.out.println(joinedStr); } } // Output: I love Java
  • 53. class Main { public static void main(String[] args) { String result; result = String.join("-", "Java", "is", "fun"); System.out.println(result); // Java-is-fun } }
  • 54. StringBuffer in Java • StringBuffer is a class in the java.lang package that represents a mutable sequence of characters. • Unlike the String class, StringBuffer allows you to modify the content of the string object after it has been created.
  • 55. StringBuffer buffer = new StringBuffer("Hello, "); buffer.append("World!"); // appends to the existing value buffer.insert(7, "Java "); // inserts at a specified index buffer.reverse(); // reverses the characters System.out.println(buffer); // prints: "!dlroW avaJ ,olleH"
  • 56. Key Features of StringBuffer • Mutable: StringBuffer provides the flexibility to change the content, making it ideal for scenarios where you have to modify strings frequently. • Synchronized: Being thread-safe, it ensures that only one thread can access the buffer's methods at a time, making it suitable for multi-threaded environments. • Performance Efficient: For repeated string manipulation, using StringBuffer can be more efficient than the String class. • Method Availability: StringBuffer offers several methods to manipulate strings. These include append(), insert(), delete(), reverse(), and replace().
  • 57. When to Use StringBuffer? • When you need to perform several modifications to strings, using StringBuffer is an efficient choice. • Due to the mutability of StringBuffer, it doesn't create a new object for every modification, leading to less memory consumption and improved performance. • StringBuffer is especially beneficial in a multithreaded environment due to its synchronized methods, ensuring thread safety
  • 58. 1. append() • The append() method adds the specified value to the end of the current string. StringBuffer buffer = new StringBuffer("javaguides"); buffer.append(" - For Beginners"); System.out.println(buffer); // Output: "javaguides - For Beginners"
  • 59. 2. insert() • The insert() method adds the specified value at the given index. 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
  • 60. 3. delete() • 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(1, 3); System.out.println(sb); }} Output Hlo
  • 61. 4.replace() • 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(1, 3, "Java"); System.out.println(sb); } } Output HJavalo
  • 62. 5.reverse() • The reverse() method of the StringBuilder class reverses the current String. class StringBufferExample5{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
  • 63. 6.capacity() • 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 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.
  • 64. 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 } } Output: 16 16 34
  • 65. 7.ensureCapacity() • The ensureCapacity() method of the 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.
  • 66. 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 } } Output: 16 16 34 34 70
  • 67. Important Constructors of StringBuffer Class Constructor with CharSequence StringBuilder sb = new StringBuilder(CharSequence seq); This constructor creates a StringBuilder instance that contains the same characters as the specified CharSequence. Like the constructor with a string, the initial capacity will be the length of the CharSequence plus 16.
  • 68. public class StringBuilderExample { public static void main(String[] args) { // Default constructor StringBuilder sb1 = new StringBuilder(); sb1.append("Hello, World!"); System.out.println(sb1); // Constructor with initial capacity StringBuilder sb2 = new StringBuilder(50); sb2.append("Initial capacity set to 50."); System.out.println(sb2); // Constructor with initial string StringBuilder sb3 = new StringBuilder("Initial String"); sb3.append(" appended text."); System.out.println(sb3); // Constructor with CharSequence CharSequence seq = "CharSequence example"; StringBuilder sb4 = new StringBuilder(seq); sb4.append(" additional text."); System.out.println(sb4); } } output Hello, World! Initial capacity set to 50. Initial String appended text. CharSequence example additional text.
  • 69. String builder • A StringBuilder is a mutable sequence of characters used in programming languages such as Java, C#, and others. • It is designed to efficiently handle strings that undergo multiple modifications, such as concatenations, insertions, deletions, or appending operations. • Unlike immutable string objects, StringBuilder allows for these operations without creating new string objects, making it more performance-efficient, especially in scenarios involving extensive string manipulation.
  • 70. • append: Appends the specified data to the end of the StringBuilder. sb.append("Hello"); sb.append(123); sb.append(true); insert: Inserts the specified data at the specified position. sb.insert(0, "Start: "); delete: Removes the characters in a substring of this sequence. sb.delete(5, 10); deleteCharAt: Removes the character at the specified position. sb.deleteCharAt(0); commonly used methods of StringBuilder:
  • 71. replace: Replaces the characters in a substring of this sequence with characters in the specified string. sb.replace(0, 5, "Hi"); reverse: Reverses the sequence of characters. sb.reverse(); toString: Converts the StringBuilder to a String. String result = sb.toString(); setLength: Sets the length of the character sequence. sb.setLength(10); commonly used methods of StringBuilder:
  • 72. public class StringBuilderExample { public static void main(String[] args) { // Default constructor StringBuilder sb = new StringBuilder(); // Appending different types of data sb.append("Hello, "); sb.append("World!"); sb.append(" Number: ").append(42); sb.append(" Boolean: ").append(true); System.out.println(sb.toString()); // Inserting text sb.insert(7, "Java "); System.out.println(sb.toString()); // Deleting text sb.delete(7, 12); System.out.println(sb.toString()); // Replacing text sb.replace(7, 12, "Universe"); System.out.println(sb.toString()); // Reversing the sequence sb.reverse(); System.out.println(sb.toString()); // Converting to String String result = sb.toString(); System.out.println("Final result: " + result); } } OUTPUT Hello, World! Number: 42 Boolean: true Hello, Java World! Number: 42 Boolean: true Hello, World! Number: 42 Boolean: true Hello, Universe! Number: 42 Boolean: true eurt :naelooB 24 :rebmuN !esrevinU ,olleH Final result: eurt :naelooB 24 :rebmuN !esrevinU ,olleH