Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java String

In Java, a string is an object representing a sequence of characters, with the String class providing various methods for string operations. Strings in Java are immutable, meaning any modification creates a new string instance, while mutable alternatives like StringBuffer and StringBuilder exist. The document also covers string creation methods, comparison techniques, and concatenation methods, highlighting the efficiency and security of immutable strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java String

In Java, a string is an object representing a sequence of characters, with the String class providing various methods for string operations. Strings in Java are immutable, meaning any modification creates a new string instance, while mutable alternatives like StringBuffer and StringBuilder exist. The document also covers string creation methods, comparison techniques, and concatenation methods, highlighting the efficiency and security of immutable strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

* 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 java.lang.String 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.

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 java.lang.String 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";
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


StringExample.java Output:

1. public class StringExample{ java


strings
2. public static void main(String args[]){ example
3. String s1="java";//creating string by Java string literal
1. char ch[]={'s','t','r','i','n','g','s'};
2. String s2=new String(ch);//converting char array to string
3. String s3=new String("example");//creating Java string by new keyword
4. System.out.println(s1);
5. System.out.println(s2);
6. System.out.println(s3);
7. }}

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 java.lang.String 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 It returns a formatted string.


format, Object... args)

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


String format, Object... args)

5 Stringsubstring(int It returns substring for given begin index.


beginIndex)

6 String substring(int It returns substring for given begin index and end index.
beginIndex, int endIndex)
7 boolean It returns true or false after matching the sequence of char
contains(CharSequence s) value.

8 static String It returns a joined string.


join(CharSequence delimiter,
CharSequence... elements)

9 static String It returns a joined string.


join(CharSequence delimiter,
Iterable<? extends
CharSequence> elements)

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

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 It replaces all occurrences of the specified char value.
new)

14 String replace(CharSequence It replaces all occurrences of the specified CharSequence.


old, CharSequence new)

15 static String It compares another string. It doesn't check case.


equalsIgnoreCase(String
another)

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

17 String[] split(String regex, int It returns a split string matching regex and limit.
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 It returns the specified char value index starting with given
fromIndex) index.

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

22 int indexOf(String substring, It returns the specified substring index starting with given
int fromIndex) 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:

Testimmutablestring.java
Output:
1. class Testimmutablestring{
Sachin
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }

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:

Testimmutablestring1.java Output:

Sachin Tendulkar
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }

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?


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.

Teststringcomparison1.java

1. class Teststringcomparison1{
2. public static void main(String args[]){ Output:
3. String s1="Sachin"; true
true
4. String s2="Sachin"; false
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }

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.

Teststringcomparison2.java

1. class Teststringcomparison2{
2. public static void main(String args[]){
Output:
3. String s1="Sachin";
false
4. String s2="SACHIN";
true
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }

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.

Teststringcomparison3.java
Output:
1. class Teststringcomparison3{
true
2. public static void main(String args[]){ false
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }

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.


o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
Teststringcomparison4.java

1. class Teststringcomparison4{
Output:
2. public static void main(String args[]){
0
3. String s1="Sachin"; 1
4. String s2="Sachin"; -1

5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }

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:

TestStringConcatenation1.java

1. class TestStringConcatenation1{ Output:


2. public static void main(String args[]){ Sachin Tendulkar
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }

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:

TestStringConcatenation2.java

1. class TestStringConcatenation2{
Output:
2. public static void main(String args[]){
80Sachin4040
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }

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:

1. public String concat(String another)

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

TestStringConcatenation3.java 1. String s2="Tendulkar";


2. String s3=s1.concat(s2);
1. class TestStringConcatenation3{ 3. System.out.println(s3);//Sachin Tendulkar
2. public static void main(String args[]){ 4. }
3. String s1="Sachin "; 5. }
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.

StrBuilder.java 1. System.out.println(s.toString()); //Displays result


2. }
1. public class StrBuilder
3. }
2. {
3. /* Driver Code */ Output:
4. public static void main(String args[]) Hello World
5. {
6. StringBuilder s1 = new StringBuilder("Hello"); //String 1
7. StringBuilder s2 = new StringBuilder(" World"); //String 2
8. StringBuilder s = s1.append(s2); //String 3 to store the result
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


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

StrFormat.java

Output:
1. public class StrFormat
2. { Hello World
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.format("%s%s",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }

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


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

3. String concatenation using String.join() method (Java Version 8+)


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

StrJoin.java:

1. public class StrJoin Output:


2. {
Hello World
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.join("",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }
In the above code snippet, the String object s stores the result of String.join("",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 String.join() method. In advance its constructor can also
1. StringJoiner s = new StringJoiner(", "); //StringeJoiner object
accept optional arguments, prefix and suffix.
2. s.add("Hello"); //String 1
StrJoiner.java 3. s.add("World"); //String 2
4. System.out.println(s.toString()); //Displays result
1. public class StrJoiner
5. }
2. {
6. }
3. /* Driver Code */
4. public static void main(String args[])
5. {
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 Collectors.joining() 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.

ColJoining.java 1. List<String> liststr = Arrays.asList("abc", "pqr",


"xyz"); //List of String array
1. import java.util.*;
2. String str = liststr.stream().collect(Collectors.j
2. import java.util.stream.Collectors;
oining(", ")); //performs joining operation
3. public class ColJoining
3. System.out.println(str.toString()); //Displays re
4. {
sult
5. /* Driver Code */
4. }
6. public static void main(String args[])
5. }
7. {

Output:

abc, pqr, xyz

Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() 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(intstartIndex, 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.

1. String s="hello";
2. System.out.println(s.substring(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


1. }
TestSubstring.java
2. }
1. public class TestSubstring{
Output:
2. public static void main(String args[]){
3. String s="SachinTendulkar"; Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
4. System.out.println("Original String: " + s); Substring starting from index 0 to 6: Sachin
5. System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
6. System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
The above Java programs, demonstrates variants of the substring() method of String class. The
startindex is inclusive and endindex is exclusive.

Using String.split() 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.

TestSubstring2.java 1. String text= new String("Hello, My name is Sachin");


2. /* Splits the sentence by the delimeter passe
1. import java.util.*; d as an argument */
2. public class TestSubstring2 3. String[] sentences = text.split("\\.");
3. { 4. System.out.println(Arrays.toString(sentences)
4. /* Driver Code */ );
5. public static void main(String args[]) 5. }
6. { 6. }
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 java.lang.String 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.
1. System.out.println(s.toLowerCase());//sachin
Stringoperation1.java
2. System.out.println(s);//Sachin(no change in origi
1. public class Stringoperation1
nal)
2. {
3. }
3. public static void main(String ar[])
4. }
4. { Output:
5. String s="Sachin"; SACHIN
6. System.out.println(s.toUpperCase());//SACHIN sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.

Stringoperation2.java 1. {
2. String s=" Sachin ";
1. public class Stringoperation2 3. System.out.println(s);// Sachin
2. { 4. System.out.println(s.trim());//Sachin
3. public static void main(String ar[]) 5. }
Output:
6. }
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.

Stringoperation3.java 1. {
2. String s="Sachin";
1. public class Stringoperation3 3. System.out.println(s.startsWith("Sa"));//true
2. { 4. System.out.println(s.endsWith("n"));//true
3. public static void main(String ar[]) 5. }
Output:
6. }
true
true

Java String charAt() Method


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

Stringoperation4.java 1. {
2. String s="Sachin";
1. public class Stringoperation4
3. System.out.println(s.charAt(0));//S
2. {
4. System.out.println(s.charAt(3));//h
3. public static void main(String ar[])
5. }
Output:
6. }
S
h

Java String length() Method


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

Stringoperation5.java

1. public class Stringoperation5


2. {
Output:
3. public static void main(String ar[])
6
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }

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.

Stringoperation6.java

1. public class Stringoperation6


2. { Output:
3. public static void main(String ar[]) Sachin
4. {
5. String s=new String("Sachin");
6. String s2=s.intern();
7. System.out.println(s2);//Sachin
8. }
9. }

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.
1. String s=String.valueOf(a);
Stringoperation7.java
2. System.out.println(s+10);
1. public class Stringoperation7 3. }

2. { 4. }

3. public static void main(String ar[]) Output:


1010
4. {
5. int a=10;

Java String replace() Method


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

1. public class Stringoperation8 Kava is a programming language. Kava is a


platform. Kava is an Island.
2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an Island.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"
7. System.out.println(replaceString);
8. }
9. }

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.

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 append(String s) It is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float), append(double)
etc.
public insert(int offset, String s) It is used to insert the specified string with this string at the
synchronized specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.

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

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

public reverse() is used to reverse the string.


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

public String substring(int beginIndex, It is used to return the substring from the specified beginIndex
int endIndex) and 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.

StringBufferExample.java
1. class StringBufferExample{ Output:
2. public static void main(String args[]){
Hello Java
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() Method


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

StringBufferExample2.java
Output:
1. class StringBufferExample2{ HJavaello
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() Method


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

StringBufferExample3.java
Output:
1. class StringBufferExample3{ HJavalo
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuffer delete() Method


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

StringBufferExample4.java Output:

1. class StringBufferExample4{ Hlo

2. public static void main(String args[]){


3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuffer reverse() Method


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

StringBufferExample5.java

1. class StringBufferExample5{
Output:
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); olleH

4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

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.

StringBufferExample6.java

1. class StringBufferExample6{ Output:

2. public static void main(String args[]){ 16


16
3. StringBuffer sb=new StringBuffer(); 34
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }

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.
StringBufferExample7.java

1. class StringBufferExample7{
Output:
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer(); 16
16
4. System.out.println(sb.capacity());//default 16 34
34
5. sb.append("Hello"); 70
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

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 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 It is used to append the specified string with this string. The append() method
append(String s) 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 specified position.
offset, String s) 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 endIndex.
startIndex, int endIndex, String
str)

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.
beginIndex)

public String substring(int It is used to return the substring from the specified beginIndex and endIndex.
beginIndex, int 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.

StringBuilderExample.java
Output:
1. class StringBuilderExample{ Hello Java
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuilder insert() method


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

StringBuilderExample2.java
Output:
1. class StringBuilderExample2{
HJavaello
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuilder replace() method


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

StringBuilderExample3.java
Output:
1. class StringBuilderExample3{
HJavalo
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuilder delete() method


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

StringBuilderExample4.java

1. class StringBuilderExample4{
Output:
2. public static void main(String args[]){
Hlo
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

5) StringBuilder reverse() method


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

StringBuilderExample5.java
Output:
1. class StringBuilderExample5{
olleH
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }

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.

StringBuilderExample6.java

1. class StringBuilderExample6{ 1. }
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder(); Output:
4. System.out.println(sb.capacity());//default 16 16
5. sb.append("Hello"); 16
34
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }

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.

StringBuilderExample7.java
1. class StringBuilderExample7{
2. public static void main(String args[]){ Output:
3. StringBuilder sb=new StringBuilder();
16
4. System.out.println(sb.capacity());//default 16 16
34
5. sb.append("Hello"); 34
6. System.out.println(sb.capacity());//now 16 70

7. sb.append("Java is my favourite language");


8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Difference between String and StringBuffer


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

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 creates memory when we concatenate t strings.
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() equals() method of Object class.
method.

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

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

Performance Test of String and StringBuffer


ConcatTest.java
1. public class ConcatTest{
2. public static String concatWithString() {
3. String t = "Java";
4. for (int i=0; i<10000; i++){
5. t = t + "Tpoint";
6. }
7. return t;
8. }
9. public static String concatWithStringBuffer(){
10. StringBuffer sb = new StringBuffer("Java");
11. for (int i=0; i<10000; i++){
12. sb.append("Tpoint"); Output:
13. } Time taken by Concating with String: 578ms
14. return sb.toString(); Time taken by Concating with StringBuffer: 0ms

15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-
startTime)+"ms");
20. startTime = System.currentTimeMillis();
21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-
startTime)+"ms");
23. }
24. }

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

String and StringBuffer HashCode Test


As we can see in the program given below, String returns new hashcode while performing
Output:
concatenation but the StringBuffer class returns same hashcode.
Hashcode test of String:
InstanceTest.java 3254818
229541438
Hashcode test of StringBuffer:
1. public class InstanceTest{ 118352462
2. public static void main(String args[]){ 118352462

3. System.out.println("Hashcode test of String:");


4. String str="java";
5. System.out.println(str.hashCode());
6. str=str+"tpoint";
7. System.out.println(str.hashCode());
8. System.out.println("Hashcode test of StringBuffer:");
9. StringBuffer sb=new StringBuffer("java");
10. System.out.println(sb.hashCode());
11. sb.append("tpoint");
12. System.out.println(sb.hashCode());
13. }
14. }

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.

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
means two threads can't call the methods of safe. 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
BufferTest.java

Hello Java Program for Beginners

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


2. public class BufferTest{
3. public static void main(String[] args){
Output:
4. StringBuffer buffer=new StringBuffer("hello");
5. buffer.append("java"); hellojava

6. System.out.println(buffer);
7. }
8. }

StringBuilder Example
BuilderTest.java

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


2. public class BuilderTest{
3. public static void main(String[] args){ Output:
4. StringBuilder builder=new StringBuilder("hello");
hellojava
5. builder.append("java");
6. System.out.println(builder);
7. }
8. }

Performance Test of StringBuffer and StringBuilder


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

ConcatTest.java

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


2. public class ConcatTest{
1. }
3. public static void main(String[] args){
2. System.out.println("Time taken by St
4. long startTime = System.currentTimeMillis();
ringBuilder: " + (System.currentTimeMillis
5. StringBuffer sb = new StringBuffer("Java");
() - startTime) + "ms");
6. for (int i=0; i<10000; i++){
3. }
7. sb.append("Tpoint");
4. }
8. }
9. System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) +
"ms");
10. startTime = System.currentTimeMillis(); Output:
11. StringBuilder sb2 = new StringBuilder("Java"); Time taken by StringBuffer: 16ms
12. for (int i=0; i<10000; i++){ Time taken by StringBuilder: 0ms

13. sb2.append("Tpoint");

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 have 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 have one final datamember, a
parameterized constructor and getter method.

ImmutableDemo.java

1. public final class Employee


1. Employee e = new Employee("ABC123");
2. {
2. String s1 = e.getPancardNumber();
3. final String pancardNumber;
3. System.out.println("Pancard Number: " + s1);
4. public Employee(String pancardNumber)
4. }
5. {
5. }
6. this.pancardNumber=pancardNumber;
7. } Output: of Java
8. public String getPancardNumber(){
Pancard Number: ABC123
9. return pancardNumber;
10. }
11. }
12. public class ImmutableDemo
13. {
14. public static void main(String ar[])
15. {

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 is no setter methods i.e. we have no option to change the value of the instance variable.

These points makes 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
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.

HTML Tutorial
Understanding problem without toString() method
Let's see the simple code that prints reference.

Student.java
1. public static void main(String args[]){
2. Student s1=new Student(101,"Raj","lucknow
1. class Student{
");
2. int rollno;
3. Student s2=new Student(102,"Vijay","ghaziabad
3. String name;
");
4. String city;
4.
5.
5. System.out.println(s1);//compiler writes here s1.t
6. Student(int rollno, String name, String city){
oString()
7. this.rollno=rollno;
6. System.out.println(s2);//compiler writes here
8. this.name=name;
s2.toString()
9. this.city=city;
7. }
10. }
8. }

Output:
Student@1fee6fc
Student@1eed786

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

Example of Java toString() method


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

Student.java

1. class Student{
1. return rollno+" "+name+" "+city;
2. int rollno;
2. }
3. String name;
3. public static void main(String args[]){
4. String city;
4. Student s1=new Student(101,"Raj","lucknow");
5. Student(int rollno, String name, String city){
5. Student s2=new Student(102,"Vijay","ghaziabad");
6. this.rollno=rollno;
6.
7. this.name=name;
7. System.out.println(s1);//compiler writes here s1.toSt
8. this.city=city;
ring()
9. }
8. System.out.println(s2);//compiler writes here s2.toString(
10.
)
11. public String toString()
9. }
12. {//overriding the toString() method
10. }
Output:

101 Raj lucknow


102 Vijay ghaziabad

In the above program, Java compiler internally calls toString() method, overriding this method 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 java.util.StringTokenizer 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.f Java

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. If
delim, boolean returnValue) 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.

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.

Simple.java
1. while (st.hasMoreTokens()) {
1. import java.util.StringTokenizer; 2. System.out.println(st.nextToken());
2. public class Simple{ 3. }
3. public static void main(String args[]){ 4. }
4. 5. }
5. StringTokenizer st = new StringTokenizer("my name is khan"," ");

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


Test.java
1. System.out.println("Next token is : " +
1. import java.util.*; st.nextToken(","));
2. 2. }
3. public class Test { 3. }
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6. // printing next token

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 java.util.regex 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.

StringTokenizer1.java 1. /* Checks if the String has any more tokens


*/
1. import java.util.StringTokenizer;
2. while (st.hasMoreTokens())
2. public class StringTokenizer1
3. {
3. {
4. System.out.println(st.nextToken());
4. /* Driver Code */
5. }
5. public static void main(String args[])
6. }
6. {
7. }
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class"," ");

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.
1. while (st.hasMoreElements())
StringTokenizer2.java
2. {
1. import java.util.StringTokenizer; 3. System.out.println(st.nextToken());
2. public class StringTokenizer2 4. }
3. { 5. }
4. public static void main(String args[]) 6. }
5. {
6. StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");

Output:

Hello
everyone
I
am
a
Java
developer

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.
1. /* StringTokenizer object */
StringTokenizer3.java 2. StringTokenizer st = new StringTokenizer("Hello Everyone
Have a nice day"," ");
1. import java.util.StringTokenizer; 3. /* Checks if the String has any more tokens */
2. public class StringTokenizer3 4. while (st.hasMoreTokens())
3. { 5. {
4. /* Driver Code */ 6. /* Prints the elements from the String */
5. public static void main(String args[]) 7. System.out.println(st.nextElement());
6. { 8. }
9. } }
Output:
10. }
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.

StringTokenizer4.java

1. import java.util.StringTokenizer;
2. public class StringTokenizer3
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
9. /* Prints the number of tokens present in the String */
10. System.out.println("Total number of Tokens: "+st.countTokens());
11. }
12. }

Output:

Total number of Tokens: 6

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

You might also like