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

What's hot (20)

Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
XPeppers
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
sunilchute1
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
Mahnoor Hashmi
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++
Guneesh Basundhra
 
Io streams
Io streamsIo streams
Io streams
Elizabeth alexander
 
Core java
Core java Core java
Core java
Ravi varma
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Constructor in Java - ITVoyagers
Constructor in Java - ITVoyagersConstructor in Java - ITVoyagers
Constructor in Java - ITVoyagers
ITVoyagers
 
Strings
StringsStrings
Strings
naslin prestilda
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
Byte code jvm
Byte code jvmByte code jvm
Byte code jvm
myrajendra
 
Strings in java
Strings in javaStrings in java
Strings in java
Kuppusamy P
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Lauren Yew
 
Java
JavaJava
Java
kavitha muneeshwaran
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
XPeppers
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
sunilchute1
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
Mahnoor Hashmi
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++
Guneesh Basundhra
 
Constructor in Java - ITVoyagers
Constructor in Java - ITVoyagersConstructor in Java - ITVoyagers
Constructor in Java - ITVoyagers
ITVoyagers
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Lauren Yew
 

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

21CS642 Module 3 Strings PPT.pptx VI SEM CSE
21CS642 Module 3 Strings PPT.pptx VI SEM CSE21CS642 Module 3 Strings PPT.pptx VI SEM CSE
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String handling
String handlingString handling
String handling
ssuser20c32b
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
1st.pptx
1st.pptx1st.pptx
1st.pptx
MahalCenteno
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
ishasharma835109
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
Raja Sekhar
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String Class
Vipul Verma
 
Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
Pamarthi Kumar
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
21CS642 Module 3 Strings PPT.pptx VI SEM CSE21CS642 Module 3 Strings PPT.pptx VI SEM CSE
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
Raja Sekhar
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
java.lang.String Class
java.lang.String Classjava.lang.String Class
java.lang.String Class
Vipul Verma
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
Ad

Recently uploaded (20)

Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Ad

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