0% found this document useful (0 votes)
17 views55 pages

Advanced Java String Handling Guide

The document provides an overview of string handling in Java, detailing the characteristics and functionalities of the String class, including its immutability, creation methods, and various operations. It explains how strings can be compared, concatenated, and manipulated using methods from the String class. Additionally, it discusses the importance of the CharSequence interface and the differences between String, StringBuffer, and StringBuilder.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views55 pages

Advanced Java String Handling Guide

The document provides an overview of string handling in Java, detailing the characteristics and functionalities of the String class, including its immutability, creation methods, and various operations. It explains how strings can be compared, concatenated, and manipulated using methods from the String class. Additionally, it discusses the importance of the CharSequence interface and the differences between String, StringBuffer, and StringBuilder.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced JAVA ****** 23CSP512

Advanced JAVA
23CSP512
MODULE 2

String Handling:

The String Constructors, String Length, Special String Operations, Character Extraction, String

Comparison, Searching Strings, Modifying a String, Data Conversion Using valueOf( ),

Changing the Case of Characters Within a String, joining strings, Additional String Methods,

StringBuffer , StringBuilder

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 1


Advanced JAVA ****** 23CSP512

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The [Link] class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters.


String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in
Java by using these three classes.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 2


Advanced JAVA ****** 23CSP512

The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.

We will discuss immutable string later. Let's first understand what String in Java is and how to
create the String object.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The [Link] class is used to create a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 3


Advanced JAVA ****** 23CSP512

2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

Java String Example

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 4


Advanced JAVA ****** 23CSP512

[Link]

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Test it Now

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.

Java String class methods

The [Link] class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 5


Advanced JAVA ****** 23CSP512

6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with


the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence It replaces all occurrences of the


new) specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 6


Advanced JAVA ****** 23CSP512

index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string. It


is an overloaded method.

Immutable String in Java

A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a new String object is created.

Let's try to understand the concept of immutability by the example given below:

[Link]

ADVERTISEMENT

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");//concat() method appends the string at the end
[Link](s);//will print Sachin because strings are immutable objects
}
}
Test it Now

Output:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 7


Advanced JAVA ****** 23CSP512

Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

For example:

[Link]

ADVERTISEMENT

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=[Link](" Tendulkar");
[Link](s);
}
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 8


Advanced JAVA ****** 23CSP512

Test it Now

Output:

Sachin Tendulkar

In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.

Why String objects are immutable in Java?


As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one
object "Sachin". If one reference variable changes the value of the object, it will be affected by
all the reference variables. That is why String objects are immutable in Java.

Following are some features of String which makes String objects immutable.

1. ClassLoader:

A ClassLoader in Java uses a String object as an argument. Consider, if the String object is
modifiable, the value might be changed and the class that is supposed to be loaded might be
different.

To avoid this kind of misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further errors by loading the
correct class. This leads to making the application program more secure. Consider an example of
banking software. The username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program more secure.

4. Heap Space:

The immutability of String helps to minimize the usage in the heap memory. When we try to
declare a new String object, the JVM checks whether the value already exists in the String pool
or not. If it exists, the same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.

Why String class is Final in Java?

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 9


Advanced JAVA ****** 23CSP512

The reason behind the String class being final is because no one can override the methods of the
String class. So that it can provide the same features to the new String objects as well as to the
old ones.

Java String compare

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1) By Using equals() Method

The String class equals() method compares the original content of the string. It compares values
of string for equality. String class provides the following two methods:

o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.

[Link]

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 10


Advanced JAVA ****** 23CSP512

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}
}
Test it Now

Output:

true
true
false

In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.

[Link]

class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
Test it Now

Output:

false
true

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 11


Advanced JAVA ****** 23CSP512

In the above program, the methods of String class are used. The equals() method returns true if
String objects are matching and both strings are of same case. equalsIgnoreCase() returns true
regardless of cases of strings.

2) By Using == operator

The == operator compares references not values.

[Link]

class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Test it Now

Output:

true
false

3) String compare by compareTo() method


The above code, demonstrates the use of == operator used for comparing two String objects.

3) By Using compareTo() method


The String class compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

o s1 == s2 : The method returns 0.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 12


Advanced JAVA ****** 23CSP512

o s1 > s2 : The method returns a positive value.


o s1 < s2 : The method returns a negative value.

[Link]

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
Test it Now

Output:

0
1
-1

String Concatenation in Java


In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method

1) String Concatenation by + (String concatenation) operator


Java String concatenation operator (+) is used to add strings. For Example:

[Link]

class TestStringConcatenation1{
public static void main(String args[]){

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 13


Advanced JAVA ****** 23CSP512

String s="Sachin"+" Tendulkar";


[Link](s);//Sachin Tendulkar
}
}
Test it Now

Output:

Sachin Tendulkar

The Java compiler transforms above code to this:

1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and it's append method. String concatenation operator produces a new String by appending the
second operand onto the end of the first operand. The String concatenation operator can
concatenate not only String but primitive values also. For Example:

[Link]

class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
[Link](s);//80Sachin4040
}
}
Test it Now

Output:

80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method


The String concat() method concatenates the specified string to the end of current string. Syntax:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 14


Advanced JAVA ****** 23CSP512

1. public String concat(String another)

Let's see the example of String concat() method.

[Link]

class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
} Test it Now

Output:

Sachin Tendulkar

The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.

There are some other possible ways to concatenate Strings in Java,

1. String concatenation using StringBuilder class


StringBuilder is class provides append() method to perform concatenation operation. The
append() method accepts arguments of different types like Objects, StringBuilder, int, char,
CharSequence, boolean, float, double. StringBuilder is the most popular and fastet way to
concatenate strings in Java. It is mutable class which means values stored in StringBuilder
objects can be updated or changed.

[Link]

public class StrBuilder


{
/* Driver Code */
public static void main(String args[])
{
StringBuilder s1 = new StringBuilder("Hello"); //String 1

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 15


Advanced JAVA ****** 23CSP512

StringBuilder s2 = new StringBuilder(" World"); //String 2


StringBuilder s = [Link](s2); //String 3 to store the result
[Link]([Link]()); //Displays result
}
}

Output:

Hello World

In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the
result of concatenation of s1 and s2 using append() method.

2. String concatenation using format() method


[Link]() method allows to concatenate multiple strings using format specifier like %s
followed by the string values or objects.

[Link]

public class StrFormat


{
/* Driver Code */
public static void main(String args[])
{
String s1 = new String("Hello"); //String 1
String s2 = new String(" World"); //String 2
String s = [Link]("%s%s",s1,s2); //String 3 to store the result
[Link]([Link]()); //Displays result
}
}

Output:

Hello World

Here, the String objects s is assigned the concatenated result of


Strings s1 and s2 using [Link]() method. format() accepts parameters as format specifier
followed by String objects or values.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 16


Advanced JAVA ****** 23CSP512

3. String concatenation using [Link]() method (Java Version 8+)

The [Link]() method is available in Java version 8 and all the above versions. [Link]()
method accepts arguments first a separator and an array of String objects.

[Link]:

public class StrJoin


{
/* Driver Code */
public static void main(String args[])
{
String s1 = new String("Hello"); //String 1
String s2 = new String(" World"); //String 2
String s = [Link]("",s1,s2); //String 3 to store the result
[Link]([Link]()); //Displays result
}
}

Output:

Hello World

In the above code snippet, the String object s stores the result of [Link]("",s1,s2) method. A
separator is specified inside quotation marks followed by the String objects or array of String
objects.

4. String concatenation using StringJoiner class (Java Version 8+)


StringJoiner class has all the functionalities of [Link]() method. In advance its constructor
can also accept optional arguments, prefix and suffix.

[Link]

public class StrJoiner


{
/* Driver Code */
public static void main(String args[])
{
StringJoiner s = new StringJoiner(", "); //StringeJoiner object

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 17


Advanced JAVA ****** 23CSP512

[Link]("Hello"); //String 1
[Link]("World"); //String 2
[Link]([Link]()); //Displays result
}
}

Output:

Hello, World

In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner()
accepts a separator value. A separator is specified inside quotation marks. The add() method
appends Strings passed as arguments.

5. String concatenation using [Link]() method (Java (Java Version 8+)

The Collectors class in Java 8 offers joining() method that concatenates the input elements in a
similar order as they occur.

[Link]

import [Link].*;
import [Link];
public class ColJoining
{
/* Driver Code */
public static void main(String args[])
{
List<String> liststr = [Link]("abc", "pqr", "xyz"); //List of String array
String str = [Link]().collect([Link](", ")); //performs joining operatio
[Link]([Link]()); //Displays result
}
}

Output:

abc, pqr, xyz

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 18


Advanced JAVA ****** 23CSP512

Here, a list of String array is declared. And a String object str stores the result
of [Link]() method.

Substring in Java
A part of String is called substring. In other words, substring is a subset of another String. Java
String class provides the built-in substring() method that extract a substring from the given string
by using the index values passed as an argument. In case of substring() method startIndex is
inclusive and endIndex is exclusive.

Suppose the string is "computer", then the substring will be com, compu, ter, etc.

Note: Index starts from 0.

You can get substring from the given String object by one of the two methods:

1. public String substring(int startIndex):


This method returns new String object containing the substring of the given string from
specified startIndex (inclusive). The method throws an IndexOutOfBoundException
when the startIndex is larger than the length of String or less than zero.
2. public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from
specified startIndex to endIndex. The method throws an IndexOutOfBoundException
when the startIndex is less than zero or startIndex is greater than endIndex or endIndex is
greater than length of String.

In case of String:

o startIndex: inclusive
o endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

String s="hello";
[Link]([Link](0,2)); //returns he as a substring

In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).

Example of Java substring() method

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 19


Advanced JAVA ****** 23CSP512

[Link]

public class TestSubstring{


public static void main(String args[]){
String s="SachinTendulkar";
[Link]("Original String: " + s);
[Link]("Substring starting from index 6: " +[Link](6));//Tendulkar
[Link]("Substring starting from index 0 to 6: "+[Link](0,6)); //Sachin
}
}

Output:

Original String: SachinTendulkar


Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin

The above Java programs, demonstrates variants of the substring() method of String class. The
startindex is inclusive and endindex is exclusive.

Using [Link]() method:


The split() method of String class can be used to extract a substring from a sentence. It accepts
arguments in the form of a regular expression.

[Link]

import [Link].*;

public class TestSubstring2


{
/* Driver Code */
public static void main(String args[])
{
String text= new String("Hello, My name is Sachin");
/* Splits the sentence by the delimeter passed as an argument */
String[] sentences = [Link]("\\.");
[Link]([Link](sentences));
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 20


Advanced JAVA ****** 23CSP512

Output:

[Hello, My name is Sachin]

In the above program, we have used the split() method. It accepts an argument \\. that checks a in
the sentence and splits the string into another string. It is stored in an array of String objects
sentences.

Java String Class Methods


The [Link] class provides a lot of built-in methods that are used to manipulate string
in Java. By the help of these methods, we can perform operations on String objects such as
trimming, concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.

Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method


The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.

[Link]

public class Stringoperation1


{
public static void main(String ar[])
{
String s="Sachin";
[Link]([Link]());//SACHIN
[Link]([Link]());//sachin
[Link](s);//Sachin(no change in original)
}
}
Test it Now

Output:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 21


Advanced JAVA ****** 23CSP512

SACHIN
sachin
Sachin

Java String trim() method


The String class trim() method eliminates white spaces before and after the String.

[Link]

public class Stringoperation2


{
public static void main(String ar[])
{
String s=" Sachin ";
[Link](s);// Sachin
[Link]([Link]());//Sachin
}
}

Output:

Sachin
Sachin

Java String startsWith() and endsWith() method


The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.

[Link]

public class Stringoperation3


{
public static void main(String ar[])
{
String s="Sachin";
[Link]([Link]("Sa"));//true
[Link]([Link]("n"));//true
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 22


Advanced JAVA ****** 23CSP512

Output:

true
true

Java String charAt() Method


The String class charAt() method returns a character at specified index.

[Link]

public class Stringoperation4


{
public static void main(String ar[])
{
String s="Sachin";
[Link]([Link](0));//S
[Link]([Link](3));//h
}
}

Output:

S
h

Java String length() Method


The String class length() method returns length of the specified String.

[Link]

public class Stringoperation5


{
public static void main(String ar[])
{
String s="Sachin";
[Link]([Link]());//6

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 23


Advanced JAVA ****** 23CSP512

}
} Test it Now

Output:

Java String intern() Method


A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a String equal to this String
object as determined by the equals(Object) method, then the String from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is returned.

[Link]

public class Stringoperation6


{
public static void main(String ar[])
{
String s=new String("Sachin");
String s2=[Link]();
[Link](s2);//Sachin
}
}

Output:

Sachin

Java String valueOf() Method


The String class valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into String.

[Link]

public class Stringoperation7


{
public static void main(String ar[])

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 24


Advanced JAVA ****** 23CSP512

{
int a=10;
String s=[Link](a);
[Link](s+10);
}
}

Output:

1010

Java String replace() Method


The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.

[Link]

public class Stringoperation8


{
public static void main(String ar[])
{
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=[Link]("Java","Kava");//replaces all occurrences of "Java" to "Kava"
[Link](replaceString);
}
}

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So
it is safe and will result in an order.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 25


Advanced JAVA ****** 23CSP512

Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier and Method Description


Type

public synchronized append(String s) It is used to append the specified string with this string. The
StringBuffer append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.

public synchronized insert(int offset, String s) It is used to insert the specified string with this string at the
StringBuffer specified position. The insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.

public synchronized replace(int startIndex, int It is used to replace the string from specified startIndex and
StringBuffer endIndex, String str) endIndex.

public synchronized delete(int startIndex, int It is used to delete the string from specified startIndex and
StringBuffer endIndex) endIndex.

public synchronized reverse() is used to reverse the string.


StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number of
characters.

public String substring(int beginIndex) It is used to return the substring from the specified beginIndex.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 26


Advanced JAVA ****** 23CSP512

public String substring(int beginIndex, int It is used to return the substring from the specified beginIndex and
endIndex) endIndex.

What is a mutable String?


A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method


The append() method concatenates the given argument with this String.

[Link]

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}

Output:

Hello Java

2) StringBuffer insert() Method


The insert() method inserts the given String with this string at the given position.

[Link]

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 27


Advanced JAVA ****** 23CSP512

Output:

HJavaello

3) StringBuffer replace() Method


The replace() method replaces the given String from the specified beginIndex and endIndex.

[Link]

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}

Output:

HJavalo

4) StringBuffer delete() Method


The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.

[Link]

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}

Output:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 28


Advanced JAVA ****** 23CSP512

Hlo

5) StringBuffer reverse() Method


The reverse() method of the StringBuilder class reverses the current String.

[Link]

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}

Output:

olleH

6) StringBuffer capacity() Method


The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of 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.

[Link]

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 29


Advanced JAVA ****** 23CSP512

Output:

16
16
34

7) StringBuffer ensureCapacity() method


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.

[Link]

class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}

Output:

16
16
34
34
70

Java StringBuilder Class


Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 30


Advanced JAVA ****** 23CSP512

1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String str) It creates a String Builder with the specified string.

StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder append(String It is used to append the specified string with this string. The
s) append() method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.

public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.

public StringBuilder replace(int It is used to replace the string from specified startIndex and
startIndex, int endIndex, String str) endIndex.

public StringBuilder delete(int It is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)

public StringBuilder reverse() It is used to reverse the string.

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number of
characters.

public String substring(int It is used to return the substring from the specified beginIndex.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 31


Advanced JAVA ****** 23CSP512

beginIndex)

public String substring(int It is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this String.

[Link]

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}

Output:

Hello Java

2) StringBuilder insert() method


The StringBuilder insert() method inserts the given string with this string at the given position.

[Link]

class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 32


Advanced JAVA ****** 23CSP512

Output:

HJavaello

3) StringBuilder replace() method


The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.

[Link]

class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}

Output:

HJavalo

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.

[Link]

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}

Output:

Hlo

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 33


Advanced JAVA ****** 23CSP512

5) StringBuilder reverse() method


The reverse() method of StringBuilder class reverses the current string.

[Link]

class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link]();
[Link](sb);//prints olleH
}
}

Output:

olleH

6) StringBuilder capacity() method


The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder 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.

[Link]

class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("Java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Output:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 34


Advanced JAVA ****** 23CSP512

16
16
34

7) StringBuilder ensureCapacity() method


The ensureCapacity() method of StringBuilder 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.

[Link]

class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("Java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}

Output:

16
16
34
34
70

Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 35


Advanced JAVA ****** 23CSP512

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) String is slow and consumes more memory when we StringBuffer is fast and consumes less
concatenate too many strings because every time it memory when we concatenate t strings.
creates new instance.

3) String class overrides the equals() method of Object class. StringBuffer class doesn't override the
So you can compare the contents of two strings by equals() method of Object class.
equals() method.

4) String class is slower while performing concatenation StringBuffer class is faster while performing
operation. concatenation operation.

5) String class uses String constant pool. StringBuffer uses Heap memory

Performance Test of String and StringBuffer

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 36


Advanced JAVA ****** 23CSP512

[Link]

public class ConcatTest{


public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "Tpoint";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
[Link]("Tpoint");
}
return [Link]();
}
public static void main(String[] args){
long startTime = [Link]();
concatWithString();
[Link]("Time taken by Concating with String: "+([Link]()-
startTime)+"ms");
startTime = [Link]();
concatWithStringBuffer();
[Link]("Time taken by Concating with StringBuffer: "+([Link]
llis()-startTime)+"ms");
}
}

Output:

Time taken by Concating with String: 578ms


Time taken by Concating with StringBuffer: 0ms

The above code, calculates the time required for concatenating a string using the String class and
StringBuffer class.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 37


Advanced JAVA ****** 23CSP512

String and StringBuffer HashCode Test


As we can see in the program given below, String returns new hashcode while performing
concatenation but the StringBuffer class returns same hashcode.

[Link]

public class InstanceTest{


public static void main(String args[]){
[Link]("Hashcode test of String:");
String str="java";
[Link]([Link]());
str=str+"tpoint";
[Link]([Link]());

[Link]("Hashcode test of StringBuffer:");


StringBuffer sb=new StringBuffer("java");
[Link]([Link]());
[Link]("tpoint");
[Link]([Link]());
}
}

Output:

Hashcode test of String:


3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Difference between StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 38


Advanced JAVA ****** 23CSP512

A list of differences between StringBuffer and StringBuilder is given below:

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread safe.
means two threads can't call the methods of It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

StringBuffer Example
[Link]

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 39


Advanced JAVA ****** 23CSP512

//Java Program to demonstrate the use of StringBuffer class.


public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
[Link]("java");
[Link](buffer);
}
}

Output:

hellojava

StringBuilder Example

[Link]

//Java Program to demonstrate the use of StringBuilder class.


public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
[Link]("java");
[Link](builder);
}
}

Output:

hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.

[Link]

//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.

public class ConcatTest{


public static void main(String[] args){

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 40


Advanced JAVA ****** 23CSP512

long startTime = [Link]();


StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
[Link]("Tpoint");
}
[Link]("Time taken by StringBuffer: " + ([Link]() -
startTime) + "ms");
startTime = [Link]();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
[Link]("Tpoint");
}
[Link]("Time taken by StringBuilder: " + ([Link]() -
startTime) + "ms");
}
}

Output:

Time taken by StringBuffer: 16ms


Time taken by StringBuilder: 0ms

How to create Immutable class?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable. We can also create
immutable class by creating final class that has final data members as the example given below:

Example to create Immutable class

In this example, we have created a final class named Employee. It has one final data member, a
parameterized constructor and getter method.

[Link]

public final class Employee


{
final String pancardNumber;
public Employee(String pancardNumber)

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 41


Advanced JAVA ****** 23CSP512

{
[Link]=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
public class ImmutableDemo
{
public static void main(String ar[])
{
Employee e = new Employee("ABC123");
String s1 = [Link]();
[Link]("Pancard Number: " + s1);
}
}

Output:

Pancard Number: ABC123

The above class is immutable because:

o The instance variable of the class is final i.e. we cannot change the value of it after
creating an object.
o The class is final so we cannot create the subclass.
o There are no setter methods i.e. we have no option to change the value of the instance
variable.

These points make this class as immutable.

Java toString() Method

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

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 42


Advanced JAVA ****** 23CSP512

overriding the toString() method, returns the desired output, it can be the state of an object etc.
depending on your implementation.

Advantage of Java toString() method

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

Let's see the simple code that prints reference.

[Link]

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


[Link]=rollno;
[Link]=name;
[Link]=city;
}

public static void main(String args[]){


Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

[Link](s1);//compiler writes here [Link]()


[Link](s2);//compiler writes here [Link]()
}
}

Output:

Student@1fee6fc
Student@1eed786

As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 43


Advanced JAVA ****** 23CSP512

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. Let's understand it with the
example given below:

Example of Java toString() method

Let's see an example of toString() method.

[Link]

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


[Link]=rollno;
[Link]=name;
[Link]=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");

[Link](s1);//compiler writes here [Link]()


[Link](s2);//compiler writes here [Link]()
}
}

Output:

101 Raj lucknow


102 Vijay ghaziabad

In the above program, Java compiler internally calls toString() method, overriding this method

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 44


Advanced JAVA ****** 23CSP512

will return the specified values of s1 and s2 objects of Student class.

StringTokenizer in Java

1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer

The [Link] class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 45


Advanced JAVA ****** 23CSP512

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, String It creates StringTokenizer with specified string and delimiter.
delim)

StringTokenizer(String str, String It creates StringTokenizer with specified string, delimiter and returnValue.
delim, boolean returnValue) If return value is true, delimiter characters are considered to be tokens. If it
is false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 46


Advanced JAVA ****** 23CSP512

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class


Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on
the basis of whitespace.

[Link]

import [Link];
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while ([Link]()) {
[Link]([Link]());
}
}
}

Output:

my
name
is
khan

The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().

Example of nextToken(String delim) method of the StringTokenizer class

[Link]

import [Link].*;

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 47


Advanced JAVA ****** 23CSP512

public class Test {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");

// printing next token


[Link]("Next token is : " + [Link](","));
}
}

Output:

Next token is : my

Note: The StringTokenizer class is deprecated now. It is recommended to use the split() method of
the String class or the Pattern class that belongs to the [Link] package.

Example of hasMoreTokens() method of the StringTokenizer class

This method returns true if more tokens are available in the tokenizer String otherwise returns
false.

[Link]

import [Link];
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenzer class
"," ");
/* Checks if the String has any more tokens */
while ([Link]())
{
[Link]([Link]());
}
}

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 48


Advanced JAVA ****** 23CSP512

Output:

Demonstrating
methods
from
StringTokenizer
class

The above Java program shows the use of two methods hasMoreTokens() and nextToken() of
StringTokenizer class.

Example of hasMoreElements() method of the StringTokenizer class

This method returns the same value as hasMoreTokens() method of StringTokenizer class. The
only difference is this class can implement the Enumeration interface.

[Link]

import [Link];
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
while ([Link]())
{
[Link]([Link]());
}
}
}

Output:

Hello
everyone
I
am
a
Java
developer

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 49


Advanced JAVA ****** 23CSP512

The above code demonstrates the use of hasMoreElements() method.

Example of nextElement() method of the StringTokenizer class

nextElement() returns the next token object in the tokenizer String. It can implement
Enumeration interface.

[Link]

import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Checks if the String has any more tokens */
while ([Link]())
{
/* Prints the elements from the String */
[Link]([Link]());
}
}
}

Output:

Hello
Everyone
Have
a
nice
day

The above code demonstrates the use of nextElement() method.

Example of countTokens() method of the StringTokenizer class

This method calculates the number of tokens present in the tokenizer String.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 50


Advanced JAVA ****** 23CSP512

[Link]

import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Prints the number of tokens present in the String */
[Link]("Total number of Tokens: "+[Link]());
}
}

Output:

Total number of Tokens: 6

The above Java code demonstrates the countTokens() method of StringTokenizer() class.

Java String FAQs or Interview Questions

A list of top Java String FAQs (Frequently Asked Questions) or interview questions are given
below. These questions can be asked by the interviewer.

1) How many objects will be created in the following code?


String s1="javatpoint";
String s2="javatpoint";

Answer: Only one.

2) What is the difference between equals() method and == operator?

The equals() method matches content of the strings whereas == operator matches object or
reference of the strings.

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 51


Advanced JAVA ****** 23CSP512

3) Is String class final?


Answer: Yes.

4) How to reverse String in java?

Input:

this is javatpoint

Output:

tnioptavaj si siht

5) How to check Palindrome String in java?

Input:

nitin

Output:

true

Input:

jatin

Output:

false

6) Write a java program to capitalize each word in string?

Input:

this is javatpoint

Output:

This Is Javatpoint

7) Write a java program to reverse each word in string?

Input:

this is javatpoint

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 52


Advanced JAVA ****** 23CSP512

Output:

siht si tnioptavaj

8) Write a java program to tOGGLE each word in string?

Input:

this is javatpoint

Output:

tHIS iS jAVATPOINT

9) Write a java program reverse tOGGLE each word in string?

Input:

this is javatpoint

Output:

sIHT sI tNIOPTAVAJ

10) What is the difference between String and StringBuffer in java?

11) What is the difference between StringBuffer and StringBuilder in java?

12) What does intern() method in java?

13) How to convert String to int in java?

14) How to convert int to String in java?

15) How to convert String to Date in java?

16) How to Optimize Java String Creation?

17) Java Program to check whether two Strings are anagram or not

18) Java program to find the percentage of uppercase, lowercase, digits and special
characters in a String

19) How to convert String to Integer and Integer to String in Java

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 53


Advanced JAVA ****** 23CSP512

20) Java Program to find duplicate characters in a String

21) Java Program to prove that strings are immutable in java

22) Java Program to remove all white spaces from a String

23) Java Program to check whether one String is a rotation of another

24) Java Program to count the number of words in a String

25) Java Program to reverse a given String with preserving the position of space

26) How to swap two String variables without third variable

27) How to remove a particular character from a String

How to reverse String in Java

There are many ways to reverse String in Java. We can reverse String using StringBuffer,
StringBuilder, iteration etc. Let's see the ways to reverse String in Java.

1) By StringBuilder / StringBuffer
File: [Link]

public class StringFormatter {


public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
[Link]();
return [Link]();
}
}

File: [Link]

public class TestStringFormatter {


public static void main(String[] args) {
[Link]([Link]("my name is khan"));
[Link]([Link]("I am sonoo jaiswal"));

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 54


Advanced JAVA ****** 23CSP512

}
}

Output:

nahk si eman ym
lawsiaj oonos ma I

2) By Reverse Iteration
File: [Link]

public class StringFormatter {


public static String reverseString(String str){
char ch[]=[Link]();
String rev="";
for(int i=[Link]-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}

File: [Link]

public class TestStringFormatter {


public static void main(String[] args) {
[Link]([Link]("my name is khan"));
[Link]([Link]("I am sonoo jaiswal"));
}
}

Output:

nahk si eman ym
lawsiaj oonos ma I

Mr. Dhananjaya M, Dept. of CSE, SJBIT Page 55

You might also like