0% found this document useful (0 votes)
324 views202 pages

String Notes

The document discusses Java strings including what they are, how to create and manipulate them, common string methods, and string builder/buffer classes. Strings are immutable objects representing character sequences. The text provides examples and details about string pooling, conversion between primitive types and strings, and string comparison/concatenation operations.

Uploaded by

CHANDAN SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
324 views202 pages

String Notes

The document discusses Java strings including what they are, how to create and manipulate them, common string methods, and string builder/buffer classes. Strings are immutable objects representing character sequences. The text provides examples and details about string pooling, conversion between primitive types and strings, and string comparison/concatenation operations.

Uploaded by

CHANDAN SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 202

Java String

What is String

Immutable String

String Comparison

String Concatenation

Substring

Methods of String class

StringBuffer class

StringBuilder class

String vs StringBuffer

StringBuffer vs Builder

Creating Immutable class

toString method

StringTokenizer class

Java String FAQs

String Handling quiz-1

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:

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

is same as:

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

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
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 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 parti


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, Object... It returns formatted string with g
args) locale.

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


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

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


the sequence of char value.

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


CharSequence... elements)

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


extends CharSequence> elements)

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


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


specified char value.

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


specified CharSequence.

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


check case.

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

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


and limit.

18 String intern() It returns an interned string.

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


index.

20 int indexOf(int ch, int fromIndex) It returns the specified char v


index starting with given index.

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

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


starting with given index.
23 String toLowerCase() It returns a string in lowercase.

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


specified locale.

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

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


specified locale.

27 String trim() It removes beginning and en


spaces of this string.

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


an overloaded method.

Do You Know?
o Why are String objects immutable?
o How to create an immutable class?
o What is string constant pool?
o What code is written by the compiler if you concatenate any string by +
(string concatenation operator)?
o What is the difference between StringBuffer and StringBuilder class?

What will we learn in String Handling?


o Concept of String
o Immutable String
o String Comparison
o String Concatenation
o Concept of Substring
o String class methods and its usage
o StringBuffer class
o StringBuilder class
o Creating Immutable class
o toString() method
o StringTokenizer class
Next Topic Immutable String

Next →

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

1. class Testimmutablestring{
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. }
Test it Now

Output:

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:

Testimmutablestring1.java

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. }
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?


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.

Next Topic String Comparison in java

← PrevNext →
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[]){
3. String s1="Sachin";
4. String s2="Sachin";
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. }
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.

Teststringcomparison2.java

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

Output:

false
true

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

Click here for more about equals() method

2) By Using == operator
The == operator compares references not values.

Teststringcomparison3.java

1. class Teststringcomparison3{
2. public static void main(String args[]){
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. }
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.


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

Teststringcomparison4.java

1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
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. }
Test it Now

Output:

0
1
-1
Click me for more about compareTo() method

Next Topic String Concatenation in java

« prevnext »
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{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
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:

TestStringConcatenation2.java

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

1. public String concat(String another)

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

TestStringConcatenation3.java

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

StrBuilder.java

1. public class StrBuilder


2. {
3. /* Driver Code */
4. public static void main(String args[])
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
9. System.out.println(s.toString()); //Displays result
10. }
11. }

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


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

1. public class StrFormat


2. {
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. }

Output:

Hello World

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


2. {
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. }

Output:

Hello World

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 accept optional arguments, prefix and suffix.

StrJoiner.java

1. public class StrJoiner


2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringJoiner s = new StringJoiner(", "); //StringeJoiner object
7. s.add("Hello"); //String 1
8. s.add("World"); //String 2
9. System.out.println(s.toString()); //Displays result
10. }
11. }

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. import java.util.*;
2. import java.util.stream.Collectors;
3. public class ColJoining
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. List<String> liststr = Arrays.asList("abc", "pqr", "xyz"); //List of String array
9. String str = liststr.stream().collect(Collectors.joining(", ")); //performs joining operat
ion
10. System.out.println(str.toString()); //Displays result
11. }
12. }

Output:

abc, pqr, xyz

Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.

Next Topic Substring in java

← PrevNext →
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.
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


TestSubstring.java

1. public class TestSubstring{


2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. System.out.println("Original String: " + s);
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
7. }
8. }

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 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. import java.util.*;
2.
3. public class TestSubstring2
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. String text= new String("Hello, My name is Sachin");
9. /* Splits the sentence by the delimeter passed as an argument */
10. String[] sentences = text.split("\\.");
11. System.out.println(Arrays.toString(sentences));
12. }
13. }

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.

Next Topic Methods Of String class

← PrevNext →
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.

Stringoperation1.java

1. public class Stringoperation1


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase());//SACHIN
7. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s);//Sachin(no change in original)
9. }
10. }
Test it Now
Output:

SACHIN
sachin
Sachin

Java String trim() method


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

Stringoperation2.java

1. public class Stringoperation2


2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }
Test it Now

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.

Stringoperation3.java

1. public class Stringoperation3


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }
Test it Now

Output:

true
true

Java String charAt() Method


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

Stringoperation4.java

1. public class Stringoperation4


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0));//S
7. System.out.println(s.charAt(3));//h
8. }
9. }
Test it Now

Output:

S
h

Java String length() Method


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

Stringoperation5.java

1. public class Stringoperation5


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }
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.

Stringoperation6.java

1. public class Stringoperation6


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

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.

Stringoperation7.java

1. public class Stringoperation7


2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }

Output:

1010

Java String replace() Method


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

Stringoperation8.java

1. public class Stringoperation8


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

Output:

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


Next Topic StringBuffer class

← PrevNext →

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 st


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

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

public delete(int startIndex, int It is used to delete the string from specified startIn
synchronized endIndex) and 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


minimumCapacity) given minimum.

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

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

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

public String substring(int It is used to return the substring from the spec
beginIndex, int 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.
StringBufferExample.java

1. class StringBufferExample{
2. public static void main(String args[]){
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. }

Output:

Hello Java

2) StringBuffer insert() Method


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

StringBufferExample2.java

1. class StringBufferExample2{
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. }

Output:

HJavaello

3) StringBuffer replace() Method


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

StringBufferExample3.java

1. class StringBufferExample3{
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. }

Output:

HJavalo

4) StringBuffer delete() Method


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

StringBufferExample4.java

1. class StringBufferExample4{
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. }

Output:

Hlo

5) StringBuffer reverse() Method


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

StringBufferExample5.java

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

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.

StringBufferExample6.java

1. class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
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. }

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.

StringBufferExample7.java

1. class StringBufferExample7{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
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. 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. }

Output:

16
16
34
34
70

Next Topic StringBuilder class

← PrevNext →
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.
append(String s) append() method is overloaded like append(char), append(boole
append(int), append(float), append(double) etc.

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

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

public StringBuilder delete(int It is used to delete the string from specified startIndex and endIn
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 minim
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 numbe
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
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.

StringBuilderExample.java

1. class StringBuilderExample{
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. }

Output:

Hello Java

2) StringBuilder insert() method


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

StringBuilderExample2.java

1. class StringBuilderExample2{
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. }

Output:

HJavaello

3) StringBuilder replace() method


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

StringBuilderExample3.java

1. class StringBuilderExample3{
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. }
Output:

HJavalo

4) StringBuilder delete() method


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

StringBuilderExample4.java

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

Output:

Hlo

5) StringBuilder reverse() method


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

StringBuilderExample5.java

1. class StringBuilderExample5{
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. }

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.

StringBuilderExample6.java

1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
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. }

Output:

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.

StringBuilderExample7.java

1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
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. 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. }

Output:

16
16
34
34
70

Next Topic Difference between String and StringBuffer

← PrevNext →

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
concatenate too many strings because every time it creates memory when we concatenate t strin
new instance.

3) String class overrides the equals() method of Object class. So StringBuffer class doesn't override
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


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");
13. }
14. return sb.toString();
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. }

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.

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.

InstanceTest.java

1. public class InstanceTest{


2. public static void main(String args[]){
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.
9. System.out.println("Hashcode test of StringBuffer:");
10. StringBuffer sb=new StringBuffer("java");
11. System.out.println(sb.hashCode());
12. sb.append("tpoint");
13. System.out.println(sb.hashCode());
14. }
15. }

Output:

Hashcode test of String:


3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Next Topic Difference between StringBuffer and StringBuilder

← PrevNext →
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 th


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

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


2. public class BufferTest{
3. public static void main(String[] args){
4. StringBuffer buffer=new StringBuffer("hello");
5. buffer.append("java");
6. System.out.println(buffer);
7. }
8. }

Output:

hellojava

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){
4. StringBuilder builder=new StringBuilder("hello");
5. builder.append("java");
6. System.out.println(builder);
7. }
8. }

Output:

hellojava
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 cla


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

Output:

Time taken by StringBuffer: 16ms


Time taken by StringBuilder: 0ms

Next Topic How to create immutable class

← PrevNext
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


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

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

Next Topic Understanding toString() method

← PrevNext →
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.

Understanding problem without toString() method


Let's see the simple code that prints reference.

Student.java

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

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{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }

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.

Next Topic StringTokenizer in java

← PrevNext →
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.

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 returnV
delim, boolean returnValue) If return value is true, delimiter characters are considered to be tokens
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. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

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. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }

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. import java.util.StringTokenizer;
2. public class StringTokenizer1
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer cl
ass"," ");
9. /* Checks if the String has any more tokens */
10. while (st.hasMoreTokens())
11. {
12. System.out.println(st.nextToken());
13. }
14. }
15. }

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.

StringTokenizer2.java

1. import java.util.StringTokenizer;
2. public class StringTokenizer2
3. {
4. public static void main(String args[])
5. {
6. StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
7. while (st.hasMoreElements())
8. {
9. System.out.println(st.nextToken());
10. }
11. }
12. }

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.

StringTokenizer3.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. /* Checks if the String has any more tokens */
10. while (st.hasMoreTokens())
11. {
12. /* Prints the elements from the String */
13. System.out.println(st.nextElement());
14. }
15. }
16. }

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.

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.

Next Topic Java String FAQs

← PrevNext →

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.

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

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

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

Next Topic How to reverse String in Java.

← PrevNext
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: StringFormatter.java

1. public class StringFormatter {


2. public static String reverseString(String str){
3. StringBuilder sb=new StringBuilder(str);
4. sb.reverse();
5. return sb.toString();
6. }
7. }

File: TestStringFormatter.java
1. public class TestStringFormatter {
2. public static void main(String[] args) {
3. System.out.println(StringFormatter.reverseString("my name is khan"));
4. System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
5. }
6. }

Output:

nahk si eman ym
lawsiaj oonos ma I

2) By Reverse Iteration
File: StringFormatter.java

1. public class StringFormatter {


2. public static String reverseString(String str){
3. char ch[]=str.toCharArray();
4. String rev="";
5. for(int i=ch.length-1;i>=0;i--){
6. rev+=ch[i];
7. }
8. return rev;
9. }
10. }

File: TestStringFormatter.java

1. public class TestStringFormatter {


2. public static void main(String[] args) {
3. System.out.println(StringFormatter.reverseString("my name is khan"));
4. System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
5. }
6. }

Output:

nahk si eman ym
lawsiaj oonos ma I
Next Topic Java String FAQs

← PrevNext →

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.

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

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

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

Next Topic How to reverse String in Java.

← PrevNext →

Java String Methods

Java String Methods


1. String charAt()
2. String compareTo()
3. String concat()
4. String contains()
5. String endsWith()
6. String equals()
7. equalsIgnoreCase()
8. String format()
9. String getBytes()
10. String getChars()
11. String indexOf()
12. String intern()
13. String isEmpty()
14. String join()
15. String lastIndexOf()
16. String length()
17. String replace()
18. String replaceAll()
19. String split()
20. String startsWith()
21. String substring()
22. String toCharArray()
23. String toLowerCase()
24. String toUpperCase()
25. String trim()
26. String valueOf()

(1) Java String charAt()


The Java String class charAt() method returns a char value at the given index
number.

The index number starts from 0 and goes to n-1, where n is the length of the string.
It returns StringIndexOutOfBoundsException, if the given index number is greater
than or equal to this string length or a negative number.

Syntax

1. public char charAt(int index)

The method accepts index as a parameter. The starting index is 0. It returns a


character at a specific index position in a string. It
throws StringIndexOutOfBoundsException if the index is a negative value or
greater than this string length.
Specified by

CharSequence interface, located inside java.lang package.

Internal implementation

1. public char charAt(int index) {


2. if ((index < 0) || (index >= value.length)) {
3. throw new StringIndexOutOfBoundsException(index);
4. }
5. return value[index];
6. }

Java String charAt() Method Examples


Let's see Java program related to string in which we will use charAt() method that
perform some operation on the give string.

FileName: CharAtExample.java

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="javatpoint";
4. char ch=name.charAt(4);//returns the char value at the 4th index
5. System.out.println(ch);
6. }}
Test it Now

Output:

Let's see the example of the charAt() method where we are passing a greater index
value. In such a case, it throws StringIndexOutOfBoundsException at run time.

FileName: CharAtExample.java

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="javatpoint";
4. char ch=name.charAt(10);//returns the char value at the 10th index
5. System.out.println(ch);
6. }}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:


String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Accessing First and Last Character by Using the


charAt() Method
Let's see a simple example where we are accessing first and last character from the
provided string.

FileName: CharAtExample3.java

1. public class CharAtExample3 {


2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. int strLength = str.length();
5. // Fetching first character
6. System.out.println("Character at 0 index is: "+ str.charAt(0));
7. // The last Character is present at the string length-1 index
8. System.out.println("Character at last index is: "+ str.charAt(strLength-1));
9. }
10. }

Output:

Character at 0 index is: W


Character at last index is: l

Print Characters Presented at Odd Positions by


Using the charAt() Method
Let's see an example where we are accessing all the elements present at odd index.

FileName: CharAtExample4.java
1. public class CharAtExample4 {
2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. for (int i=0; i<=str.length()-1; i++) {
5. if(i%2!=0) {
6. System.out.println("Char at "+i+" place "+str.charAt(i));
7. }
8. }
9. }
10. }

Output:

Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place
Char at 23 place o
Char at 25 place t
Char at 27 place l

The position such as 7 and 21 denotes the space.

Counting Frequency of a character in a String by


Using the charAt() Method
Let's see an example in which we are counting frequency of a character in the given
string.

FileName: CharAtExample5.java

1. public class CharAtExample5 {


2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. int count = 0;
5. for (int i=0; i<=str.length()-1; i++) {
6. if(str.charAt(i) == 't') {
7. count++;
8. }
9. }
10. System.out.println("Frequency of t is: "+count);
11. }
12. }

Output:

Frequency of t is: 4

Counting the Number of Vowels in a String by


Using the chatAt() Method
Let's see an example where we are counting the number of vowels present in a string
with the help of the charAt() method.

FileName: CharAtExample6.java

1. // import statement
2. import java.util.*;
3.
4. public class CharAtExample6
5. {
6. ArrayList<Character> al;
7.
8. // constructor for creating and
9. // assigning values to the ArrayList al
10. CharAtExample6()
11. {
12. al = new ArrayList<Character>();
13. al.add('A'); al.add('E');
14. al.add('a'); al.add('e');
15. al.add('I'); al.add('O');
16. al.add('i'); al.add('o');
17. al.add('U'); al.add('u');
18. }
19.
20. // a method that checks whether the character c is a vowel or not
21. private boolean isVowel(char c)
22. {
23. for(int i = 0; i < al.size(); i++)
24. {
25. if(c == al.get(i))
26. {
27. return true;
28. }
29. }
30. return false;
31. }
32. // a method that calculates vowels in the String s
33. public int countVowels(String s)
34. {
35. int countVowel = 0; // store total number of vowels
36. int size = s.length(); // size of string
37. for(int j = 0; j < size; j++)
38. {
39. char c = s.charAt(j);
40. if(isVowel(c))
41. {
42. // vowel found!
43. // increase the count by 1
44. countVowel = countVowel + 1;
45. }
46. }
47.
48. return countVowel;
49. }
50.
51. // main method
52. public static void main(String argvs[])
53. {
54. // creating an object of the class CharAtExample6
55. CharAtExample6 obj = new CharAtExample6();
56.
57. String str = "Javatpoint is a great site for learning Java.";
58.
59. int noOfVowel = obj.countVowels(str);
60.
61. System.out.println("String: " + str);
62.
63. System.out.println("Total number of vowels in the string are: "+ noOfVowel + "\n");
64.
65. str = "One apple in a day keeps doctor away.";
66.
67. System.out.println("String: " + str);
68.
69. noOfVowel = obj.countVowels(str);
70.
71. System.out.println("Total number of vowels in the string are: "+ noOfVowel);
72. }
73. }

Output:

String: Javatpoint is a great site for learning Java.


Total number of vowels in the string are: 16

String: One apple in a day keeps doctor away.


Total number of vowels in the string are: 13

Next Topic Java String compareTo

← PrevNext →
Java String compareTo()
The Java String class compareTo() method compares the given string with the
current string lexicographically. It returns a positive number, negative number, or 0.

It compares strings on the basis of the Unicode value of each character in the strings.

If the first string is lexicographically greater than the second string, it returns a
positive number (difference of character value). If the first string is less than the
second string lexicographically, it returns a negative number, and if the first string is
lexicographically equal to the second string, it returns 0.
1. if s1 > s2, it returns positive number
2. if s1 < s2, it returns negative number
3. if s1 == s2, it returns 0

Syntax

1. public int compareTo(String anotherString)

The method accepts a parameter of type String that is to be compared with the
current string.

It returns an integer value. It throws the following two exceptions:

ClassCastException: If this object cannot get compared with the specified object.

NullPointerException: If the specified object is null.

Internal implementation
1. int compareTo(String anotherString) {
2. int length1 = value.length;
3. int length2 = anotherString.value.length;
4. int limit = Math.min(length1, length2);
5. char v1[] = value;
6. char v2[] = anotherString.value;
7.
8. int i = 0;
9. while (i < limit) {
10. char ch1 = v1[i];
11. char ch2 = v2[i];
12. if (ch1 != ch2) {
13. return ch1 - ch2;
14. }
15. i++;
16. }
17. return length1 - length2;
18. }
Java String compareTo() Method Example
FileName: CompareToExample.java

1. public class CompareToExample{


2. public static void main(String args[]){
3. String s1="hello";
4. String s2="hello";
5. String s3="meklo";
6. String s4="hemlo";
7. String s5="flag";
8. System.out.println(s1.compareTo(s2));//0 because both are equal
9. System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
10. System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
11. System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
12. }}
Test it Now

Output:

0
-5
-1
2

Java String compareTo(): empty string


When we compare two strings in which either first or second string is empty, the
method returns the length of the string. So, there may be two scenarios:

o If first string is an empty string, the method returns a negative


o If second string is an empty string, the method returns a positive number that is the
length of the first string.

FileName: CompareToExample2.java

1. public class CompareToExample2{


2. public static void main(String args[]){
3. String s1="hello";
4. String s2="";
5. String s3="me";
6. System.out.println(s1.compareTo(s2));
7. System.out.println(s2.compareTo(s3));
8. }}
Test it Now

Output:

5
-2

Java String compareTo(): case sensitive


To check whether the compareTo() method considers the case sensitiveness of
characters or not, we will make the comparison between two strings that contain the
same letters in the same sequence.

Suppose, a string having letters in uppercase, and the second string having the
letters in lowercase. On comparing these two string, if the outcome is 0, then the
compareTo() method does not consider the case sensitiveness of characters;
otherwise, the method considers the case sensitiveness of characters.

FileName: CompareToExample3.java

1. public class CompareToExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // input string in uppercase
8. String st1 = new String("INDIA IS MY COUNTRY");
9.
10. // input string in lowercase
11. String st2 = new String("india is my country");
12.
13. System.out.println(st1.compareTo(st2));
14. }
15. }

Output:
-32

Conclusion: It is obvious by looking at the output that the outcome is not equal to
zero. Hence, the compareTo() method takes care of the case sensitiveness of
characters.

Java String compareTo(): ClassCastException


The ClassCastException is thrown when objects of incompatible types get
compared. In the following example, we are comparing an object of the ArrayList (al)
with a string literal ("Sehwag").

FileName: CompareToExample4.java

1. // import statement
2. import java.util.*;
3.
4. class Players
5. {
6.
7. private String name;
8.
9. // constructor of the class
10. public Players(String str)
11. {
12. name = str;
13. }
14.
15. }
16.
17. public class CompareToExample4
18. {
19.
20. // main method
21. public static void main(String[] args)
22. {
23.
24. Players ronaldo = new Players("Ronaldo");
25. Players sachin = new Players("Sachin");
26. Players messi = new Players("Messi");
27. ArrayList<Players> al = new ArrayList<>();
28.
29. al.add(ronaldo);
30. al.add(sachin);
31. al.add(messi);
32.
33. // performing binary search on the list al
34. Collections.binarySearch(al, "Sehwag", null);
35. }
36.
37. }

Output:

Exception in thread "main" java.lang.ClassCastException: class Players


cannot be cast to class java.lang.Comparable

Java String compareTo(): NullPointerException


The NullPointerException is thrown when a null object invokes the compareTo()
method. Observe the following example.

FileName: CompareToExample5.java

1. public class CompareToExample5


2. {
3. // main method
4. public static void main(String[] args)
5. {
6.
7. String str = null;
8.
9. // null is invoking the compareTo method. Hence, the NullPointerException
10. // will be raised
11. int no = str.compareTo("India is my country.");
12.
13. System.out.println(no);
14. }
15. }

Output:

Exception in thread "main" java.lang.NullPointerException


at CompareToExample5.main(CompareToExample5.java:9)

Next Topic Java String concat()

← PrevNext →

Java String concat


The Java String class concat() method combines specified string at the end of this
string. It returns a combined string. It is like appending another string.

Signature
The signature of the string concat() method is given below:

1. public String concat(String anotherString)

Parameter
anotherString : another string i.e., to be combined at the end of this string.
Returns
combined string

Internal implementation

1. public String concat(String str) {


2. int otherLen = str.length();
3. if (otherLen == 0) {
4. return this;
5. }
6. int len = value.length;
7. char buf[] = Arrays.copyOf(value, len + otherLen);
8. str.getChars(buf, len);
9. return new String(buf, true);
10. }

Java String concat() method example


FileName: ConcatExample.java

1. public class ConcatExample{


2. public static void main(String args[]){
3. String s1="java string";
4. // The string s1 does not get changed, even though it is invoking the method
5. // concat(), as it is immutable. Therefore, the explicit assignment is required here.
6. s1.concat("is immutable");
7. System.out.println(s1);
8. s1=s1.concat(" is immutable so assign it explicitly");
9. System.out.println(s1);
10. }}
Test it Now

Output:

java string
java string is immutable so assign it explicitly

Java String concat() Method Example 2


Let's see an example where we are concatenating multiple string objects.

FileName: ConcatExample2.java

1. public class ConcatExample2 {


2. public static void main(String[] args) {
3. String str1 = "Hello";
4. String str2 = "Javatpoint";
5. String str3 = "Reader";
6. // Concatenating one string
7. String str4 = str1.concat(str2);
8. System.out.println(str4);
9. // Concatenating multiple strings
10. String str5 = str1.concat(str2).concat(str3);
11. System.out.println(str5);
12. }
13. }

Output:

HelloJavatpoint
HelloJavatpointReader

Java String concat() Method Example 3


Let's see an example where we are concatenating spaces and special chars to the
string object. It is done using the chaining of the concat() method.

FileName: ConcatExample3.java

1. public class ConcatExample3 {


2. public static void main(String[] args) {
3. String str1 = "Hello";
4. String str2 = "Javatpoint";
5. String str3 = "Reader";
6. // Concatenating Space among strings
7. String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
8. System.out.println(str4);
9. // Concatenating Special Chars
10. String str5 = str1.concat("!!!");
11. System.out.println(str5);
12. String str6 = str1.concat("@").concat(str2);
13. System.out.println(str6);
14. }
15. }

Output:

Hello Javatpoint Reader


Hello!!!
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-
cfemail="afe7cac3c3c0efe5ced9cedbdfc0c6c1db">[email protected]</a>

Java String concat() Method Example 4


Till now, we have seen that the concat() method appends the string at the end of the
string that invokes the method. However, we can do a bit of workaround to append
the string at the beginning of a string using the concat() method.

FileName: ConcatExample4.java

1. // A Java program that shows how to add


2. // a string at the beginning of another string
3. public class ConcatExample4
4. {
5. // main method
6. public static void main(String argvs[])
7. {
8. String str = "Country";
9.
10. // we have added the string "India is my" before the String str;
11. // Also, observe that a string literal can also invoke the concat() method
12. String s = "India is my ".concat(str);
13.
14. // displaying the string
15. System.out.println(s);
16.
17. }
18. }

Output:

India is my Country

Next Topic Java String contains()

← PrevNext →

Java String contains()


The Java String class contains() method searches the sequence of characters in this
string. It returns true if the sequence of char values is found in this string otherwise
returns false.

Signature
The signature of string contains() method is given below:

1. public boolean contains(CharSequence sequence)

Parameter
sequence : specifies the sequence of characters to be searched.

Returns
true if the sequence of char value exists, otherwise false.

Exception
NullPointerException : if the sequence is null.

Internal implementation

1. public boolean contains(CharSequence s) {


2. return indexOf(s.toString()) > -1;
3. }

Here, the conversion of CharSequence takes place into String. After that, the
indexOf() method is invoked. The method indexOf() either returns 0 or a number
greater than 0 in case the searched string is found.

However, when the searched string is not found, the indexOf() method returns -1.
Therefore, after execution, the contains() method returns true when the indexOf()
method returns a non-negative value (when the searched string is found); otherwise,
the method returns false.

Java String contains() Method Example


FileName: ContainsExample.java

1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}
Test it Now

Output:
true
true
false

Java String contains() Method Example 2


The contains() method searches case-sensitive char sequence. If the argument is not
case sensitive, it returns false. Let's see an example.

FileName: ContainsExample2.java

1. public class ContainsExample2 {


2. public static void main(String[] args) {
3. String str = "Hello Javatpoint readers";
4. boolean isContains = str.contains("Javatpoint");
5. System.out.println(isContains);
6. // Case Sensitive
7. System.out.println(str.contains("javatpoint")); // false
8. }
9. }

Output:

true
false

Java String contains() Method Example 3


The contains() method is helpful to find a char-sequence in the string. We can use it
in the control structure to produce the search-based result. Let's see an example.

FileName: ContainsExample3.java

1. public class ContainsExample3 {


2. public static void main(String[] args) {
3. String str = "To learn Java visit Javatpoint.com";
4. if(str.contains("Javatpoint.com")) {
5. System.out.println("This string contains javatpoint.com");
6. }else
7. System.out.println("Result not found");
8. }
9. }

Output:

This string contains javatpoint.com

Java String contains() Method Example 4


The contains() method raises the NullPointerException when one passes null in the
parameter of the method. The following example shows the same.

FileName: ContainsExample4.java

1. public class ContainsExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome to JavaTpoint!";
7.
8. // comparing a string to null
9. if(str.contains(null))
10. {
11. System.out.println("Inside the if block");
12. }
13. else
14. {
15. System.out.println("Inside the else block");
16. }
17.
18. }
19. }

Output:

Exception in thread "main" java.lang.NullPointerException


at java.base/java.lang.String.contains(String.java:2036)
at ContainsExample4.main(ContainsExample4.java:9)

Limitations of the Contains() method


Following are some limitations of the contains() method:

o The contains() method should not be used to search for a character in a string. Doing
so results in an error.
o The contains() method only checks for the presence or absence of a string in another
string. It never reveals at which index the searched index is found. Because of these
limitations, it is better to use the indexOf() method instead of the contains() method.

Next Topic Java String endsWith()

← PrevNext →

Java String endsWith()


The Java String class endsWith() method checks if this string ends with a given
suffix. It returns true if this string ends with the given suffix; else returns false.

Signature
The syntax or signature of endsWith() method is given below.

1. public boolean endsWith(String suffix)


Parameter
suffix : Sequence of character

Returns
true or false

Internal implementation

1. public boolean endsWith(String suffix) {


2. return startsWith(suffix, value.length - suffix.value.length);
3. }

The internal implementation shows that the endWith() method is dependent on the
startsWith() method of the String class.

Java String endsWith() Method Example


FileName: EndsWithExample.java

1. public class EndsWithExample{


2. public static void main(String args[]){
3. String s1="java by javatpoint";
4. System.out.println(s1.endsWith("t"));
5. System.out.println(s1.endsWith("point"));
6. }}
Test it Now

Output:

true
true

Java String endsWith() Method Example 2


Since the endsWith() method returns a boolean value, the method can also be used
in an if statement. Observe the following program.

FileName: EndsWithExample2.java
1. public class EndsWithExample2 {
2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint.com";
4. System.out.println(str.endsWith("point"));
5. if(str.endsWith(".com")) {
6. System.out.println("String ends with .com");
7. }else System.out.println("It does not end with .com");
8. }
9. }

Output:

false
String ends with .com

Java String endsWith() Method Example 3


The endsWith() method takes care of the case sensitiveness of the characters present
in a string. The following program shows the same.

FileName: EndsWithExample3.java

1. public class EndsWithExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome to JavaTpoint";
7.
8. // the result of the following display statement
9. // shows endsWith() considers the case sensitiveness of
10. // the charaters of a string
11. System.out.println(str.endsWith("javaTpoint")); // false because J and j are different
12. System.out.println(str.endsWith("Javatpoint")); // false because T and t are different
13. System.out.println(str.endsWith("JavaTpoint")); // true because every character is sam
e
14.
15. }
16. }
Output:

false
false
true

Java String endsWith() Method Example 4


When an empty string is passed in the parameter of the method endsWith(), the
method always returns a true value. The reason behind this is that a string never
changes when we append an empty string to it. For example,

The statement

1. String str = "Ladies and Gentlemen" + "";

results in

str = "Ladies and Gentlemen";

Thus, we can say that any string in Java ends with an empty string (""). Observe the

FileName: EndsWithExample4.java

1. public class EndsWithExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome to JavaTpoint";
7.
8. // prints true
9. System.out.println(str.endsWith(""));
10.
11. // prints false as there is no white space after the string
12. System.out.println(str.endsWith(" "));
13.
14. }
15. }
Output:

true
false

Java String endsWith() Method Example 5


The endsWith() method raises the NullPointerException if one passes null in the
parameter of the method. The following example shows the same.

FileName: EndsWithExample5.java

1. public class EndsWithExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome to JavaTpoint!";
7.
8. // invoking the method endsWith with the parameter as null
9. if(str.endsWith(null))
10. {
11. System.out.println("Inside the if block");
12. }
13. else
14. {
15. System.out.println("Inside the else block");
16. }
17.
18. }
19. }

Output:

Exception in thread "main" java.lang.NullPointerException


at java.base/java.lang.String.endsWith(String.java:1485)
at EndsWithExample5.main(EndsWithExample5.java:9)

Java String endsWith() Method Example 6


A String literal can also call the endsWith() method. The following program shows the
same.

FileName: EndsWithExample6.java

1. public class EndsWithExample6


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. // invoking the method endsWith() using the string literal
7. if("Welcome to JavaTpoint".endsWith(""))
8. {
9. System.out.println("Inside the if block");
10. }
11. else
12. {
13. System.out.println("Inside the else block");
14. }
15. // invoking the method endsWith() using the string literal
16. if("Welcome to JavaTpoint".endsWith("point"))
17. {
18. System.out.println("Inside the if block");
19. }
20. else
21. {
22. System.out.println("Inside the else block");
23. }
24. // invoking the method endsWith() using the string literal
25. if("Welcome to JavaTpoint".endsWith("xyz"))
26. {
27. System.out.println("Inside the if block");
28. }
29. else
30. {
31. System.out.println("Inside the else block");
32. }
33. }
34. }

Output:

Inside the if block


Inside the if block
Inside the else block

Next Topic Java String equals()

← PrevNext →

Java String equals()


The Java String class equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all characters
are matched, it returns true.

The String equals() method overrides the equals() method of the Object class.

Signature

1. publicboolean equals(Object anotherObject)


Parameter
anotherObject : another object, i.e., compared with this string.

Returns
true if characters of both strings are equal otherwise false.

Internal implementation

1. public boolean equals(Object anObject) {


2. if (this == anObject) {
3. return true;
4. }
5. if (anObject instanceof String) {
6. String anotherString = (String) anObject;
7. int n = value.length;
8. if (n == anotherString.value.length) {
9. char v1[] = value;
10. char v2[] = anotherString.value;
11. int i = 0;
12. while (n-- != 0) {
13. if (v1[i] != v2[i])
14. return false;
15. i++;
16. }
17. return true;
18. }
19. }
20. return false;
21. }

Java String equals() Method Example


FileName: EqualsExample.java

1. public class EqualsExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. String s2="javatpoint";
5. String s3="JAVATPOINT";
6. String s4="python";
7. System.out.println(s1.equals(s2));//true because content and case is same
8. System.out.println(s1.equals(s3));//false because case is not same
9. System.out.println(s1.equals(s4));//false because content is not same
10. }}
Test it Now

Output:

true
false
false

Java String equals() Method Example 2


The equals() method compares two strings and can be used in if-else control
structure.

FileName: EqualsExample2.java

1. public class EqualsExample2 {


2. public static void main(String[] args) {
3. String s1 = "javatpoint";
4. String s2 = "javatpoint";
5. String s3 = "Javatpoint";
6. System.out.println(s1.equals(s2)); // True because content is same
7. if (s1.equals(s3)) {
8. System.out.println("both strings are equal");
9. }else System.out.println("both strings are unequal");
10. }
11. }

Output:

true
both strings are unequal
Java String equals() Method Example 3
Let's see one more example to test the equality of string present in the list.

FileName: EqualsExample3.java

1. import java.util.ArrayList;
2. public class EqualsExample3 {
3. public static void main(String[] args) {
4. String str1 = "Mukesh";
5. ArrayList<String> list = new ArrayList<>();
6. list.add("Ravi");
7. list.add("Mukesh");
8. list.add("Ramesh");
9. list.add("Ajay");
10. for (String str : list) {
11. if (str.equals(str1)) {
12. System.out.println("Mukesh is present");
13. }
14. }
15. }
16. }

Output:

Mukesh is present

Java String equals() Method Example 4


The internal implementation of the equals() method shows that one can pass the
reference of any object in the parameter of the method. The following example
shows the same.

FileName: EqualsExample4.java

1. public class EqualsExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. // Strings
7. String str = "a";
8. String str1 = "123";
9. String str2 = "45.89";
10. String str3 = "false";
11. Character c = new Character('a');
12. Integer i = new Integer(123);
13. Float f = new Float(45.89);
14. Boolean b = new Boolean(false);
15. // reference of the Character object is passed
16. System.out.println(str.equals(c));
17. // reference of the Integer object is passed
18. System.out.println(str1.equals(i));
19. // reference of the Float object is passed
20. System.out.println(str2.equals(f));
21. // reference of the Boolean object is passed
22. System.out.println(str3.equals(b));
23. // the above print statements show a false value because
24. // we are comparing a String with different data types
25. // To achieve the true value, we have to convert
26. // the different data types into the string using the toString() method
27. System.out.println(str.equals(c.toString()));
28. System.out.println(str1.equals(i.toString()));
29. System.out.println(str2.equals(f.toString()));
30. System.out.println(str3.equals(b.toString()));
31. }
32. }

Output:

false
false
false
false
true
true
true
true
Next Topic Java String equalsIgnoreCase()

← PrevNext →

Java String equalsIgnoreCase()


The Java String class equalsIgnoreCase() method compares the two given strings
on the basis of the content of the string irrespective of the case (lower and upper) of
the string. It is just like the equals() method but doesn't check the case sensitivity. If
any character is not matched, it returns false, else returns true.
Signature

1. publicboolean equalsIgnoreCase(String str)

Parameter
str : another string i.e., compared with this string.

Returns
It returns true if characters of both strings are equal, ignoring case otherwise false.

Internal implementation

1. public boolean equalsIgnoreCase(String anotherString) {


2. return (this == anotherString) ? true
3. : (anotherString != null)
4. && (anotherString.value.length == value.length)
5. && regionMatches(true, 0, anotherString, 0, value.length);
6. }

It is obvious from looking at the implementation that the equalsIgnoreCase() method


is invoking the regionMatches() method. It makes the equalsIgnoreCase() method
case-insensitive. The signature of the regionMatches() method is mentioned below.

public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset,
int len)

The regionMatches() method parses five parameters. The first


parameter ignoreCase is set to true in the above implementation. Thus, when the
method is executed, it checks whether the ignoreCase flag is true or not. If yes, then
one character each from both the strings is taken and then compared. If the
comparison gives a false value, then both the character is converted to upper case
and then checked if the comparison still gives a false value, then both the characters
are converted to a lower case and then compared. If the comparison gives the true
value, then both the strings have equal contents; otherwise, not. Code Snippet of the
discussed comparison is mentioned below.

1. while (toffset < last)


2. {
3. char ch1 = getChar(value, toffset++);
4. char ch2 = getChar(other, ooffset++);
5. if (ch1 == ch2)
6. {
7. continue;
8. }
9. // convert each character to uppercase and
10. // then make the comparison.
11. // If the comparison yeilds a true value,
12. // then next pair of characters should be scanned
13. char uCh1 = Character.toUpperCase(ch1);
14. char uCh2 = Character.toUpperCase(ch2);
15. if (uCh1 == u2)
16. {
17. continue;
18. }
19.
20. // convert each character to lowercase and
21. // then make the comparison.
22. // If the comparison yeilds a true value,
23. // then next pair of characters should be scanned
24. // Otherwise, return false.
25. if (Character.toLowerCase(uCh1) == Character.toLowerCase(uCh2))
26. {
27. continue;
28. }
29. return false;
30. }
31.
32. // reaching here means the content of both the strings
33. // are the same after ignoring the case sensitiveness
34. return true;

One may argue that if we made a comparison after converting to uppercase, then
why do we need an extra comparison by converting characters to the lowercase. The
reason behind this is to provide to the requirement of Georgian alphabets.
Conversion in uppercase does not work properly for the Georgian alphabets, as they
have some strange rules about the case conversion. Therefore, one extra comparison,
by converting characters to the lowercase, is required.
Java String equalsIgnoreCase() Method
Example
FileName: EqualsIgnoreCaseExample.java

1. public class EqualsIgnoreCaseExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. String s2="javatpoint";
5. String s3="JAVATPOINT";
6. String s4="python";
7. System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are
same
8. System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
9. System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
10. }}
Test it Now

Output:

true
true
false

Java String equalsIgnoreCase() Method


Example 2
Let's see an example where we are testing string equality among the strings.

FileName: EqualsIgnoreCaseExample2.java

1. import java.util.ArrayList;
2. public class EqualsIgnoreCaseExample2 {
3. public static void main(String[] args) {
4. String str1 = "Mukesh Kumar";
5. ArrayList<String> list = new ArrayList<>();
6. list.add("Mohan");
7. list.add("Mukesh");
8. list.add("RAVI");
9. list.add("MuKesH kuMar");
10. list.add("Suresh");
11. for (String str : list) {
12. if (str.equalsIgnoreCase(str1)) {
13. System.out.println("Mukesh kumar is present");
14. }
15. }
16. }
17. }

Output:

Mukesh kumar is present

Next Topic Java String format()

← PrevNext →

Java String format()


The java string format() method returns the formatted string by given locale,
format and arguments.

If you don't specify the locale in String.format() method, it uses default locale by
calling Locale.getDefault() method.

The format() method of java language is like sprintf() function in c language


and printf() method of java language.

Internal implementation

1. public static String format(String format, Object... args) {


2. return new Formatter().format(format, args).toString();
3. }

Signature
There are two type of string format() method:

1. public static String format(String format, Object... args)


2. and,
3. public static String format(Locale locale, String format, Object... args)

Parameters
locale : specifies the locale to be applied on the format() method.

format : format of the string.

args : arguments for the format string. It may be zero or more.

Returns
formatted string
Throws
NullPointerException : if format is null.

IllegalFormatException : if format is illegal or incompatible.

Java String format() method example


1. public class FormatExample{
2. public static void main(String args[]){
3. String name="sonoo";
4. String sf1=String.format("name is %s",name);
5. String sf2=String.format("value is %f",32.33434);
6. String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling
with 0
7.
8. System.out.println(sf1);
9. System.out.println(sf2);
10. System.out.println(sf3);
11. }}
Test it Now
name is sonoo
value is 32.334340
value is 32.334340000000

Java String Format Specifiers


Here, we are providing a table of format specifiers supported by the Java String.

Format Data Type Output


Specifier

%a floating point (except BigDecimal) Returns Hex output of floating point number.

%b Any type "true" if non-null, "false" if null

%c character Unicode character


%d integer (incl. byte, short, int, long, Decimal Integer
bigint)

%e floating point decimal number in scientific notation

%f floating point decimal number

%g floating point decimal number, possibly in scientific not


depending on the precision and value.

%h any type Hex String of value from hashCode() method.

%n none Platform-specific line separator.

%o integer (incl. byte, short, int, long, Octal number


bigint)

%s any type String value

%t Date/Time (incl. long, Calendar, %t is the prefix for Date/Time conversions. M


Date and TemporalAccessor) formatting flags are needed after this. See Date/
conversion below.

%x integer (incl. byte, short, int, long, Hex string.


bigint)

Java String format() Method Example 2


This method supports various data types and formats them into a string type. Let us
see an example.

1. public class FormatExample2 {


2. public static void main(String[] args) {
3. String str1 = String.format("%d", 101); // Integer value
4. String str2 = String.format("%s", "Amar Singh"); // String value
5. String str3 = String.format("%f", 101.00); // Float value
6. String str4 = String.format("%x", 101); // Hexadecimal value
7. String str5 = String.format("%c", 'c'); // Char value
8. System.out.println(str1);
9. System.out.println(str2);
10. System.out.println(str3);
11. System.out.println(str4);
12. System.out.println(str5);
13. }
14.
15. }
Test it Now
101
Amar Singh
101.000000
65
c

Java String format() Method Example 3


Apart from formatting, we can set width, padding etc. of any value. Let us see an
example where we are setting width and padding for an integer value.

1. public class FormatExample3 {


2. public static void main(String[] args) {
3. String str1 = String.format("%d", 101);
4. String str2 = String.format("|%10d|", 101); // Specifying length of integer
5. String str3 = String.format("|%-10d|", 101); // Left-justifying within the specified
width
6. String str4 = String.format("|% d|", 101);
7. String str5 = String.format("|%010d|", 101); // Filling with zeroes
8. System.out.println(str1);
9. System.out.println(str2);
10. System.out.println(str3);
11. System.out.println(str4);
12. System.out.println(str5);
13. }
14. }
Test it Now
101
| 101|
|101 |
| 101|
|0000000101|
Next Topic Java String getBytes()

« PrevNext »

Java String getBytes()


The Java String class getBytes() method does the encoding of string into the
sequence of bytes and keeps it in an array of bytes.

Signature
There are three variants of getBytes() method. The signature or syntax of string
getBytes() method is given below:

1. public byte[] getBytes()


2. public byte[] getBytes(Charset charset)
3. public byte[] getBytes(String charsetName)throws UnsupportedEncodingException

Parameters
charset / charsetName - The name of a charset the method supports.

Returns
Sequence of bytes.

Exception Throws
UnsupportedEncodingException: It is thrown when the mentioned charset is not
supported by the method.

Internal implementation

1. public byte[] getBytes() {


2. return StringCoding.encode(value, 0, value.length);
3. }

String class getBytes() Method Example


The parameterless getBytes() method encodes the string using the default charset of
the platform, which is UTF - 8. The following two examples show the same.

FileName: StringGetBytesExample.java

1. public class StringGetBytesExample{


2. public static void main(String args[]){
3. String s1="ABCDEFG";
4. byte[] barr=s1.getBytes();
5. for(int i=0;i<barr.length;i++){
6. System.out.println(barr[i]);
7. }
8. }}
Test it Now

Output:

65
66
67
68
69
70
71

Java String class getBytes() Method


Example 2
FileName: StringGetBytesExample2.java

The method returns a byte array that again can be passed to the String constructor
to get String.

1. public class StringGetBytesExample2 {


2. public static void main(String[] args) {
3. String s1 = "ABCDEFG";
4. byte[] barr = s1.getBytes();
5. for(int i=0;i<barr.length;i++){
6. System.out.println(barr[i]);
7. }
8. // Getting string back
9. String s2 = new String(barr);
10. System.out.println(s2);
11. }
12. }
Test it Now

Output:

65
66
67
68
69
70
71
ABCDEFG

Java String class getBytes() Method


Example 3
The following example shows the encoding into a different charset.

FileName: StringGetBytesExample3.java

1. // Import statement
2. import java.io.*;
3.
4. public class StringGetBytesExample3
5. {
6. // main method
7. public static void main(String argvs[])
8. {
9. // input string
10. String str = "Welcome to JavaTpoint.";
11. System.out.println("The input String is : ");
12. System.out.println(str + "\n");
13.
14. // inside try block encoding is
15. // being done using different charsets
16. try
17. {
18. 16 - bit UCS Transformation format
19. byte[] byteArr = str.getBytes("UTF-16");
20. System.out.println("After converted into UTF-16 the String is : ");
21.
22. for (int j = 0; j < byteArr.length; j++)
23. {
24. System.out.print(byteArr[j]);
25. }
26.
27. System.out.println("\n");
28.
29. // Big Endian byte order, 16 - bit UCS Transformation format
30. byte[] byteArr1 = str.getBytes("UTF-16BE");
31. System.out.println("After converted into UTF-16BE the String is : ");
32.
33. for (int j = 0; j < byteArr1.length; j++)
34. {
35. System.out.print(byteArr1[j]);
36. }
37.
38. System.out.println("\n");
39.
40. // ISO Latin Alphabet
41. byte[] byteArr2 = str.getBytes("ISO-8859-1");
42. System.out.println("After converted into ISO-8859-1 the String is : ");
43.
44. for (int j = 0; j < byteArr2.length; j++)
45. {
46. System.out.print(byteArr2[j]);
47. }
48.
49. System.out.println("\n");
50.
51. // Little Endian byte order, 16 - bit UCS Transformation format
52. byte[] byteArr3 = str.getBytes("UTF-16LE");
53. System.out.println("After converted into UTF-16LE the String is : ");
54.
55. for (int j = 0; j < byteArr3.length; j++)
56. {
57. System.out.print(byteArr3[j]);
58. }
59.
60. }
61. catch (UnsupportedEncodingException g)
62. {
63. System.out.println("Unsupported character set" + g);
64. }
65.
66.
67. }
68. }

Output:

The input String is :


Welcome to JavaTpoint.

After converted into UTF-16 the String is :


-2-
108701010108099011101090101032011601110320740970118097084011201110105011001
16046

After converted into UTF-16BE the String is :


087010101080990111010901010320116011103207409701180970840112011101050110011
6046

After converted into ISO-8859-1 the String is :


871011089911110910132116111327497118978411211110511011646

After converted into UTF-16LE the String is :


870101010809901110109010103201160111032074097011809708401120111010501100116
0460

Java String class getBytes() Method


Example 4
The following example shows when the charset is not supported by the getBytes()
method, UnsupportedEncodingException is thrown.

FileName: StringGetBytesExample4.java

1. public class StringGetBytesExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. // input string
7. String str = "Welcome to JavaTpoint.";
8. System.out.println("The input String is : ");
9. System.out.println(str + "\n");
10.
11. // encoding into UTF - 17
12. byte[] byteArr = str.getBytes("UTF-17");
13. System.out.println("After converted into UTF-17 the String is : ");
14.
15. for (int j = 0; j < byteArr.length; j++)
16. {
17. System.out.print(byteArr[j]);
18. }
19.
20.
21. }
22. }

Output:

/StringGetBytesExample4.java:11: error: unreported exception


UnsupportedEncodingException; must be caught or declared to be thrown
byte[] byteArr = str.getBytes("UTF-17");
^
1 error

Next Topic Java String getChars()

← PrevNext →
Next →← Prev

Java String getChars()


The Java String class getChars() method copies the content of this string into a specified char
There are four arguments passed in the getChars() method. The signature of the getChars() meth
given below:

Signature

public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)

Parameters
int srcBeginIndex: The index from where copying of characters is started.

int srcEndIndex: The index which is next to the last character that is getting copied.

Char[] destination: The char array where characters from the string that invokes the getChars() meth
getting copied.

int dstEndIndex: It shows the position in the destination array from where the characters from the
will be pushed.

Returns
It doesn't return any value.

Exception Throws
The method throws StringIndexOutOfBoundsException when any one or more than one of the follo
conditions holds true.

o If srcBeginIndex is less than zero.


o If srcBeginIndex is greater than srcEndIndex.
o If srcEndIndex is greater than the size of the string that invokes the method
o If dstEndIndex is is less than zero.
o If dstEndIndex + (srcEndIndex - srcBeginIndex) is greater than the size of the destination array.

Internal implementation
The signature or syntax of string getChars() method is given below:

void getChars(char dst[], int dstBegin) {


// copies value from 0 to dst - 1
System.arraycopy(value, 0, dst, dstBegin, value.length);
}

Java String getChars() Method Example


FileName: StringGetCharsExample.java

public class StringGetCharsExample{


public static void main(String args[]){
String str = new String("hello javatpoint how r u");
char[] ch = new char[10];
try{
str.getChars(6, 16, ch, 0);
System.out.println(ch);
}catch(Exception ex){System.out.println(ex);}
}}
Test it Now

Output:

javatpoint

Java String getChars() Method Example 2


The method throws an exception if index value exceeds array range. Let's see an example.

FileName: StringGetCharsExample2.java

public class StringGetCharsExample2 {


public static void main(String[] args) {
String str = new String("Welcome to Javatpoint");
char[] ch = new char[20];
try {
str.getChars(1, 26, ch, 0);
System.out.println(ch);
} catch (Exception e) {
System.out.println(e);
10. }
11. }
12. }

Output:

java.lang.StringIndexOutOfBoundsException: offset 10, count 14, length 20

Java String getChars() Method Example 3


The getChars() method does not copy anything into the char array, provided the value of srcBegin
and srcEndIndex are the same. It is because the getChars() method copies from the srcBeginIndex
to srcEndIndex - 1 index. As srcBeginIndex is equal to srcEndIndex; therefore, srcEndIndex - 1 is less
srcBeginIndex. Therefore, the getChars() method copies nothing. The following example confirm
same.

FileName: StringGetCharsExample3.java

public class StringGetCharsExample3


{
// main method
public static void main(String argvs[])
{
String str = "Welcome to JavaTpoint!";

// creating a char arry of size 25


char[] chArr = new char[25];
10.
11. // start and end indices are same
12. int srcBeginIndex = 11;
13. int srcEndIndex = 11;
14. int dstBeginIndex = 2;
15.
16. try
17. {
18. // invoking the method getChars()
19. str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex);
20. System.out.println(chArr);
21. }
22. catch(Exception excpn)
23. {
24. System.out.println(excpn);
25. }
26. System.out.println("The getChars() method prints nothing as start and end indices are equal.");
27. }
28. }

Output:

The getChars() method prints nothing as start and end indices are equal.

Next Topic Java String indexOf()

← PrevNext →
Java String indexOf()
The Java String class indexOf() method returns the position of the first occurrence
of the specified character or string in a specified string.

Signature
There are four overloaded indexOf() method in Java. The signature of indexOf()
methods are given below:

No. Method Description

1 int indexOf(int ch) It returns the index position for the given char value

2 int indexOf(int ch, int fromIndex) It returns the index position for the given char value and
index

3 int indexOf(String substring) It returns the index position for the given substring

4 int indexOf(String substring, int It returns the index position for the given substring and
fromIndex) index

Parameters
ch: It is a character value, e.g. 'a'

fromIndex: The index position from where the index of the char value or substring is
returned.

substring: A substring to be searched in this string.

Returns
Index of the searched string or character.

Internal Implementation

1. public int indexOf(int ch) {


2. return indexOf(ch, 0);
3. }

Java String indexOf() Method Example


FileName: IndexOfExample.java

1. public class IndexOfExample{


2. public static void main(String args[]){
3. String s1="this is index of example";
4. //passing substring
5. int index1=s1.indexOf("is");//returns the index of is substring
6. int index2=s1.indexOf("index");//returns the index of index substring
7. System.out.println(index1+" "+index2);//2 8
8.
9. //passing substring with from index
10. int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
11. System.out.println(index3);//5 i.e. the index of another is
12.
13. //passing char value
14. int index4=s1.indexOf('s');//returns the index of s char value
15. System.out.println(index4);//3
16. }}
Test it Now

Output:

2 8
5
3

We observe that when a searched string or character is found, the method returns a
non-negative value. If the string or character is not found, -1 is returned. We can use
this property to find the total count of a character present in the given string.
Observe the following example.
FileName: IndexOfExample5.java

1. public class IndexOfExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = "Welcome to JavaTpoint";
8. int count = 0;
9. int startFrom = 0;
10. for(; ;)
11. {
12.
13. int index = str.indexOf('o', startFrom);
14.
15. if(index >= 0)
16. {
17. // match found. Hence, increment the count
18. count = count + 1;
19.
20. // start looking after the searched index
21. startFrom = index + 1;
22. }
23.
24. else
25. {
26. // the value of index is - 1 here. Therefore, terminate the loop
27. break;
28. }
29.
30. }
31.
32. System.out.println("In the String: "+ str);
33. System.out.println("The 'o' character has come "+ count + " times");
34. }
35. }
Output:

In the String: Welcome to JavaTpoint


The 'o' character has come 3 times

Java String indexOf(String substring)


Method Example
The method takes substring as an argument and returns the index of the first
character of the substring.

FileName: IndexOfExample2.java

1. public class IndexOfExample2 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing Substring
5. int index = s1.indexOf("method"); //Returns the index of this substring
6. System.out.println("index of substring "+index);
7. }
8.
9. }
Test it Now

Output:

index of substring 16

Java String indexOf(String substring, int


fromIndex) Method Example
The method takes substring and index as arguments and returns the index of the first
character that occurs after the given fromIndex.

FileName: IndexOfExample3.java

1. public class IndexOfExample3 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing substring and index
5. int index = s1.indexOf("method", 10); //Returns the index of this substring
6. System.out.println("index of substring "+index);
7. index = s1.indexOf("method", 20); // It returns -1 if substring does not found
8. System.out.println("index of substring "+index);
9. }
10. }
Test it Now

Output:

index of substring 16
index of substring -1

Java String indexOf(int char, int


fromIndex) Method Example
The method takes char and index as arguments and returns the index of the first
character that occurs after the given fromIndex.

FileName: IndexOfExample4.java

1. public class IndexOfExample4 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing char and index from
5. int index = s1.indexOf('e', 12); //Returns the index of this char
6. System.out.println("index of char "+index);
7. }
8. }
Test it Now

Output:

index of char 17

Next Topic Java String intern


« PrevNext »

Java String intern()


The Java String class intern() method returns the interned string. It returns the
canonical representation of string.

It can be used to return string from memory if it is created by a new keyword. It


creates an exact copy of the heap string object in the String Constant Pool.

Signature
The signature of the intern() method is given below:

1. public String intern()

Returns
interned string

The need and working of the String.intern()


Method
When a string is created in Java, it occupies memory in the heap. Also, we know that
the String class is immutable. Therefore, whenever we create a string using the new
keyword, new memory is allocated in the heap for corresponding string, which is
irrespective of the content of the array. Consider the following code snippet.

1. String str = new String("Welcome to JavaTpoint.");


2. String str1 = new String("Welcome to JavaTpoint");
3. System.out.println(str1 == str); // prints false

The println statement prints false because separate memory is allocated for each
string literal. Thus, two new string objects are created in the memory i.e. str and str1.
that holds different references.
We know that creating an object is a costly operation in Java. Therefore, to save time,
Java developers came up with the concept of String Constant Pool (SCP). The SCP is
an area inside the heap memory. It contains the unique strings. In order to put the
strings in the string pool, one needs to call the intern() method. Before creating an
object in the string pool, the JVM checks whether the string is already present in the
pool or not. If the string is present, its reference is returned.

1. String str = new String("Welcome to JavaTpoint").intern(); // statement - 1


2. String str1 = new String("Welcome to JavaTpoint").intern(); // statement - 2
3. System.out.println(str1 == str); // prints true

In the above code snippet, the intern() method is invoked on the String objects.
Therefore, the memory is allocated in the SCP. For the second statement, no new
string object is created as the content of str and str1 are the same. Therefore, the
reference of the object created in the first statement is returned for str1. Thus, str and
str1 both point to the same memory. Hence, the print statement prints true.

Java String intern() Method Example


FileName: InternExample.java

1. public class InternExample{


2. public static void main(String args[]){
3. String s1=new String("hello");
4. String s2="hello";
5. String s3=s1.intern();//returns string from pool, now it will be same as s2
6. System.out.println(s1==s2);//false because reference variables are pointing to different insta
nce
7. System.out.println(s2==s3);//true because reference variables are pointing to same in
stance
8. }}
Test it Now

Output:

false
true

Java String intern() Method Example 2


Let's see one more example to understand the string intern concept.

FileName: InternExample2.java

1. public class InternExample2 {


2. public static void main(String[] args) {
3. String s1 = "Javatpoint";
4. String s2 = s1.intern();
5. String s3 = new String("Javatpoint");
6. String s4 = s3.intern();
7. System.out.println(s1==s2); // True
8. System.out.println(s1==s3); // False
9. System.out.println(s1==s4); // True
10. System.out.println(s2==s3); // False
11. System.out.println(s2==s4); // True
12. System.out.println(s3==s4); // False
13. }
14. }
Test it Now

Output:

true
false
true
false
true
false

Points to Remember
Following are some important points to remember regarding the intern() method:

1) A string literal always invokes the intern() method, whether one mention the
intern() method along with the string literal or not. For example,

1. String s = "d".intern();
2. String p = "d"; // compiler treats it as String p = "d".intern();
3. System.out.println(s == p); // prints true
2) Whenever we create a String object using the new keyword, two objects are
created. For example,

1. String str = new ("Hello World");

Here, one object is created in the heap memory outside of the SCP because of the
usage of the new keyword. As we have got the string literal too ("Hello World");
therefore, one object is created inside the SCP, provided the literal "Hello World" is
already not present in the SCP.

Next Topic Java String isEmpty

« PrevNext »
Java String isEmpty()
The Java String class isEmpty() method checks if the input string is empty or not.
Note that here empty means the number of characters contained in a string is zero.

Signature
The signature or syntax of string isEmpty() method is given below:

1. public boolean isEmpty()

Returns
true if length is 0 otherwise false.

Since
1.6

Internal implementation

1. public boolean isEmpty() {


2. return value.length == 0;
3. }

Java String isEmpty() method example


FileName: StringIsEmptyExample.java

1. public class IsEmptyExample{


2. public static void main(String args[]){
3. String s1="";
4. String s2="javatpoint";
5.
6. System.out.println(s1.isEmpty());
7. System.out.println(s2.isEmpty());
8. }}
Test it Now

Output:

true
false

Java String isEmpty() Method Example 2


FileName: StringIsEmptyExample2.java

1. public class IsEmptyExample2 {


2. public static void main(String[] args) {
3. String s1="";
4. String s2="Javatpoint";
5. // Either length is zero or isEmpty is true
6. if(s1.length()==0 || s1.isEmpty())
7. System.out.println("String s1 is empty");
8. else System.out.println("s1");
9. if(s2.length()==0 || s2.isEmpty())
10. System.out.println("String s2 is empty");
11. else System.out.println(s2);
12. }
13. }

Output:

String s1 is empty
Javatpoint

Empty Vs. Null Strings


Earlier in this tutorial, we have discussed that the empty strings contain zero
characters. However, the same is true for a null string too. A null string is a string that
has no value.

1. String str = ""; // empty string


2. String str1 = null; // null string. It is also not containing any characters.

The isEmpty() method is not fit for checking the null strings. The following example
shows the same.

FileName: StringIsEmptyExample3.java

1. public class StringIsEmptyExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = null;
7. if(str.isEmpty())
8. {
9. System.out.println("The string is null.");
10. }
11. else
12. {
13. System.out.println("The string is not null.");
14. }
15. }
16. }

Output:

Exception in thread "main" java.lang.NullPointerException


at StringIsEmptyExample3.main(StringIsEmptyExample3.java:7)

Here, we can use the == operator to check for the null strings.

FileName: StringIsEmptyExample4.java

1. class StringIsEmptyExample4
2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = null;
7. if(str == null)
8. {
9. System.out.println("The string is null.");
10. }
11. else
12. {
13. System.out.println("The string is not null.");
14. }
15. }
16. }

Output:

The string is null.

Blank Strings
Blank strings are those strings that contain only white spaces. The isEmpty() method
comes in very handy to check for the blank strings. Consider the following example.

FileName: StringIsEmptyExample5.java

1. public class StringIsEmptyExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. // a blank string
7. String str = " ";
8. int size = str.length();
9.
10. // trim the white spaces and after that
11. // if the string results in the empty string
12. // then the string is blank; otherwise, not.
13. if(size == 0)
14. {
15. System.out.println("The string is empty. \n");
16. }
17. else if(size > 0 && str.trim().isEmpty())
18. {
19. System.out.println("The string is blank. \n");
20. }
21. else
22. {
23. System.out.println("The string is not blank. \n");
24. }
25.
26. str = " Welcome to JavaTpoint. ";
27. size = str.length();
28. if(size == 0)
29. {
30. System.out.println("The string is empty. \n");
31. }
32. if(size > 0 && str.trim().isEmpty())
33. {
34. System.out.println("The string is blank. \n");
35. }
36. else
37. {
38. System.out.println("The string is not blank. \n");
39. }
40. }
41. }

Output:

The string is blank.


The string is not blank.

Next Topic Java String join()


← PrevNext →

Java String join()


The Java String class join() method returns a string joined with a given delimiter. In
the String join() method, the delimiter is copied for each element. The join() method
is included in the Java string since JDK 1.8.

There are two types of join() methods in the Java String class.

Signature
The signature or syntax of the join() method is given below:

1. public static String join(CharSequence delimiter, CharSequence... elements)


2. and
3. public static String join(CharSequence delimiter, Iterable<? extends CharSequence>
elements)

Parameters
delimiter : char value to be added with each element

elements : char value to be attached with delimiter

Returns
joined string with delimiter

Exception Throws
NullPointerException if element or delimiter is null.

Since
1.8

Internal Implementation

1. // type - 1
2. public static String join(CharSequence delimiter, CharSequence... elements)
3. {
4. Objects.requireNonNull(elements);
5. Objects.requireNonNull(delimiter);
6.
7. StringJoiner jnr = new StringJoiner(delimiter);
8. for (CharSequence c: elements)
9. {
10. jnr.add(c);
11. }
12. return jnr.toString();
13. }
1. // type - 2
2. public static String join(CharSequence delimiter, CharSequence... elements)
3. {
4. Objects.requireNonNull(elements);
5. Objects.requireNonNull(delimiter);
6.
7. StringJoiner jnr = new StringJoiner(delimiter);
8. for (CharSequence c: elements)
9. {
10. jnr.add(c);
11. }
12. return jnr.toString();
13. }
14.
15. public static String join(CharSequence delimiter, Iterable<? extends CharSequence>
elements)
16. {
17.
18.
19. Objects.requireNonNull(elements);
20. Objects.requireNonNull(delimiter);
21.
22. StringJoiner jnr = new StringJoiner(delimiter);
23. for (CharSequence c: elements)
24. {
25. joiner.add(c);
26. }
27. return jnr.toString();
28. }

Java String join() Method Example


FileName: StringJoinExample.java

1. public class StringJoinExample{


2. public static void main(String args[]){
3. String joinString1=String.join("-","welcome","to","javatpoint");
4. System.out.println(joinString1);
5. }}
Test it Now

Output:

welcome-to-javatpoint

Java String join() Method Example 2


We can use a delimiter to format the string as we did in the below example to show
the date and time.

FileName: StringJoinExample2.java

1. public class StringJoinExample2 {


2. public static void main(String[] args) {
3. String date = String.join("/","25","06","2018");
4. System.out.print(date);
5. String time = String.join(":", "12","10","10");
6. System.out.println(" "+time);
7. }
8. }

Output:

25/06/2018 12:10:10

Java String join() Method Example 3


In the case of using null as a delimiter, we get the null pointer exception. The
following example confirms the same.

FileName: StringJoinExample3.java

1. public class StringJoinExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = null;
7. str = String.join(null, "abc", "bcd", "apple");
8. System.out.println(str);
9. }
10. }

Output:

Exception in thread "main" java.lang.NullPointerException


at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.lang.String.join(String.java:2393)
at StringJoinExample3.main(StringJoinExample3.java:7)

However, if the elements that have to be attached with the delimiter are null then, we
get the ambiguity. It is because there are two join() methods, and null is acceptable
for both types of the join() method. Observe the following example.

FileName: StringJoinExample4.java
1. public class StringJoinExample4
2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = null;
7. str = String.join("India", null);
8. System.out.println(str);
9. }
10. }

Output:

/StringJoinExample4.java:7: error: reference to join is ambiguous


str = String.join("India", null);
^
both method join(CharSequence,CharSequence...) in String and method
join(CharSequence,Iterable<? extends CharSequence>) in String match
/StringJoinExample4.java:7: warning: non-varargs call of varargs method
with inexact argument type for last parameter;
str = String.join("India", null);
^
cast to CharSequence for a varargs call
cast to CharSequence[] for a non-varargs call and to suppress this
warning
1 error
1 warning

Java String join() Method Example 4


If the elements that have to be attached with the delimiter have some strings, in
which a few of them are null, then the null elements are treated as a normal string,
and we do not get any exception or error. Let's understand it through an example.

FileName: StringJoinExample5.java

1. public class StringJoinExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = null;
7.
8. // one of the element is null however it will be treated as normal string
9. str = String.join("-", null, " wake up ", " eat ", " write content for JTP ", " eat ", " sleep "
);
10. System.out.println(str);
11. }
12. }

Output:

null- wake up - eat - write content for JTP - eat - sleep

Next Topic Java String lastIndexOf()

Java String lastIndexOf()


The Java String class lastIndexOf() method returns the last index of the given
character value or substring. If it is not found, it returns -1. The index counter starts
from zero.

Signature
There are four types of lastIndexOf() method in Java. The signature of the methods
are given below:

No. Method Description

1 int lastIndexOf(int ch) It returns last index position for the given char value

2 int lastIndexOf(int ch, int fromIndex) It returns last index position for the given char value
from index

3 int lastIndexOf(String substring) It returns last index position for the given substring

4 int lastIndexOf(String substring, int It returns last index position for the given substring
fromIndex) from index
Parameters
ch: char value i.e. a single character e.g. 'a'

fromIndex: index position from where index of the char value or substring is retured

substring: substring to be searched in this string

Returns
last index of the string

Internal Implementation
The internal implementation of the four types of the lastIndexOf() method is
mentioned below.

The internal implementation of the four types of the lastIndexOf() method is


mentioned below.

1. int lastIndexOf(int ch)

1. public int lastIndexOf(int ch)


2. {
3. return lastIndexOf(ch, value.length - 1);
4. }

2. int lastIndexOf(int ch, int fromIndex)

1. public int lastIndexOf(int ch, int fromIndex)


2. {
3. if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT)
4. {
5. // handling most of the cases here
6. // negative value means invalid code point
7. final char[] val = this.value;
8. int j = Math.min(fromIndex, val.length - 1);
9. for (; jj >= 0; j--)
10. {
11. if (val[i] == ch)
12. {
13. return j;
14. }
15. }
16. return -1;
17. }
18.
19. else
20. {
21. return lastIndexOfSupplementary(ch, fromIndex);
22. }
23. }
24.
25. // internal implementation of the method lastIndexOfSupplementary()
26. private int lastIndexOfSupplementary(int c, int fIndex)
27. {
28. if (Character.isValidCodePoint(c))
29. {
30. final char[] val = this.value;
31. char h = Character.highSurrogate(c);
32. char l = Character.lowSurrogate(c);
33. int j = Math.min(fIndex, value.length - 2);
34. for (; j >= 0; j--)
35. {
36. if (val[j] == h && val[j + 1] == l)
37. {
38. return j;
39. }
40. }
41. }
42. return -1;
43. }

3. int lastIndexOf(String subString)

1. public int lastIndexOf(String subString)


2. {
3. return lastIndexOf(subString, value.length);
4. }

4. int lastIndexOf(String substring, int fromIndex)

1. public int lastIndexOf(String substring, int fromIndex)


2. {
3. public int lastIndexOf(String str, int fromIndex)
4. {
5. return lastIndexOf(value, 0, value.length, str.value, 0, str.value.length, fromIndex);
6. }
7. }
8.
9. // src the characters that are being searched.
10. // srcOffset provides the offset of the src string.
11. // srcCount number of the source string.
12. // tar the characters that are being searched for.
13. // fromIndex the index to start search from.
14. static int lastIndexOf(char[] src, int srcOffset, int srcCount, String tar, int fromIndex)
15. {
16. return lastIndexOf(src, srcOffset, srcCount, tar.value, 0, tar.value.length, fromIndex);
17. }
18.
19.
20. static int lastIndexOf(char[] src, int srcOffset, int srcCount, char[] tar, int tarOffset, int tarCo
unt, int fromIndex)
21. {
22. int rightIndex = srcCount - tarCount;
23. if (fromIndex < 0)
24. {
25. return -1;
26. }
27. if (fromIndex > rightIndex)
28. {
29. fromIndex = rightIndex;
30. }
31. // an Empty string is always a match.
32. if (tarCount == 0)
33. {
34. return fromIndex;
35. }
36.
37. int lastStrIndex = tarOffset + tarCount - 1;
38. char lastStrChar = tar[strLastIndex];
39. int min = srcOffset + tarCount - 1;
40. int j = min + fromIndex;
41.
42. startLookForLastChar:
43. while (true)
44. {
45. while (j >= min && src[j] != lastStrChar)
46. {
47. j = j - 1;
48. }
49. if (j < min)
50. {
51. return -1;
52. }
53. int i = j - 1;
54. int begin = i - (tarCount - 1);
55. int m = lastStrIndex - 1;
56.
57. while (i > begin)
58. {
59. if (source[i--] != target[m--])
60. {
61. j = j + 1;
62. continue startLookForLastChar;
63. }
64. }
65. return begin - srcOffset + 1;
66. }
67. }
Java String lastIndexOf() method example
FileName: LastIndexOfExample.java

1. public class LastIndexOfExample{


2. public static void main(String args[]){
3. String s1="this is index of example";//there are 2 's' characters in this sentence
4. int index1=s1.lastIndexOf('s');//returns last index of 's' char value
5. System.out.println(index1);//6
6. }}
Test it Now

Output:

Java String lastIndexOf(int ch, int


fromIndex) Method Example
Here, we are finding the last index from the string by specifying fromIndex.

FileName: LastIndexOfExample2.java

1. public class LastIndexOfExample2 {


2. public static void main(String[] args) {
3. String str = "This is index of example";
4. int index = str.lastIndexOf('s',5);
5. System.out.println(index);
6. }
7. }
Test it Now

Output:

Java String lastIndexOf(String substring)


Method Example
It returns the last index of the substring.

FileName: LastIndexOfExample3.java

1. public class LastIndexOfExample3 {


2. public static void main(String[] args) {
3. String str = "This is last index of example";
4. int index = str.lastIndexOf("of");
5. System.out.println(index);
6. }
7. }
Test it Now

Output:

19

Java String lastIndexOf(String substring,


int fromIndex) Method Example
It returns the last index of the substring from the fromIndex.

FileName: LastIndexOfExample4.java

1. public class LastIndexOfExample4 {


2. public static void main(String[] args) {
3. String str = "This is last index of example";
4. int index = str.lastIndexOf("of", 25);
5. System.out.println(index);
6. index = str.lastIndexOf("of", 10);
7. System.out.println(index); // -1, if not found
8. }
9. }
Test it Now

Output:

19
-1
Next Topic Java String length()

← PrevNext →

Java String length()


The Java String class length() method finds the length of a string. The length of the
Java string is the same as the Unicode code units of the string.

Signature
The signature of the string length() method is given below:

1. public int length()

Specified by
CharSequence interface

Returns
Length of characters. In other words, the total number of characters present in the
string.

Internal implementation

1. public int length() {


2. return value.length;
3. }

The String class internally uses a char[] array to store the characters. The length
variable of the array is used to find the total number of elements present in the array.
Since the Java String class uses this char[] array internally; therefore, the length
variable can not be exposed to the outside world. Hence, the Java developers created
the length() method, the exposes the value of the length variable. One can also think
of the length() method as the getter() method, that provides a value of the class field
to the user. The internal implementation clearly depicts that the length() method
returns the value of then the length variable.

Java String length() method example


FileName: LengthExample.java

1. public class LengthExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. String s2="python";
5. System.out.println("string length is: "+s1.length());//10 is the length of javatpoint strin
g
6. System.out.println("string length is: "+s2.length());//6 is the length of python string
7. }}
Test it Now

Output:

string length is: 10


string length is: 6

Java String length() Method Example 2


Since the length() method gives the total number of characters present in the string;
therefore, one can also check whether the given string is empty or not.

FileName: LengthExample2.java

1. public class LengthExample2 {


2. public static void main(String[] args) {
3. String str = "Javatpoint";
4. if(str.length()>0) {
5. System.out.println("String is not empty and length is: "+str.length());
6. }
7. str = "";
8. if(str.length()==0) {
9. System.out.println("String is empty now: "+str.length());
10. }
11. }
12. }

Output:

String is not empty and length is: 10


String is empty now: 0

Java String length() Method Example 3


The length() method is also used to reverse the string.

FileName: LengthExample3.java

1. class LengthExample3
2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome To JavaTpoint";
7. int size = str.length();
8.
9. System.out.println("Reverse of the string: " + "'" + str + "'" + " is");
10.
11. for(int i = 0; i < size; i++)
12. {
13. // printing in reverse order
14. System.out.print(str.charAt(str.length() - i - 1));
15. }
16.
17. }
18. }

Output:

Reverse of the string: 'Welcome To JavaTpoint' is


tniopTavaJ oT emocleW

Java String length() Method Example 4


The length() method can also be used to find only the white spaces present in the
string. Observe the following example.

FileName: LengthExample4.java

1. public class LengthExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = " Welcome To JavaTpoint ";
7. int sizeWithWhiteSpaces = str.length();
8.
9. System.out.println("In the string: " + "'" + str + "'");
10.
11. str = str.replace(" ", "");
12. int sizeWithoutWhiteSpaces = str.length();
13.
14. // calculating the white spaces
15. int noOfWhieSpaces = sizeWithWhiteSpaces - sizeWithoutWhiteSpaces;
16.
17. System.out.print("Total number of whitespaces present are: " + noOfWhieSpaces);
18. }
19. }

Output:

In the string: ' Welcome To JavaTpoint '


Total number of whitespaces present are: 4
Next Topic Java String replace()

← PrevNext →

Java String replace()


The Java String class replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

Since JDK 1.5, a new replace() method is introduced that allows us to replace a
sequence of char values.

Signature
There are two types of replace() methods in Java String class.

1. public String replace(char oldChar, char newChar)


2. public String replace(CharSequence target, CharSequence replacement)

The second replace() method is added since JDK 1.5.

Parameters
oldChar : old character

newChar : new character

target : target sequence of characters

replacement : replacement sequence of characters

Returns
replaced string

Exception Throws
NullPointerException: if the replacement or target is equal to null.

Internal implementation

1. public String replace(char oldChar, char newChar) {


2. if (oldChar != newChar) {
3. int len = value.length;
4. int i = -1;
5. char[] val = value; /* avoid getfield opcode */
6.
7. while (++i < len) {
8. if (val[i] == oldChar) {
9. break;
10. }
11. }
12. if (i < len) {
13. char buf[] = new char[len];
14. for (int j = 0; j < i; j++) {
15. buf[j] = val[j];
16. }
17. while (i < len) {
18. char c = val[i];
19. buf[i] = (c == oldChar) ? newChar : c;
20. i++;
21. }
22. return new String(buf, true);
23. }
24. }
25. return this;
26. }
1. public String replace(CharSequence target, CharSequence replacement)
2. {
3. return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
4. this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
5. }

Java String replace(char old, char new)


method example
FileName: ReplaceExample1.java

1. public class ReplaceExample1{


2. public static void main(String args[]){
3. String s1="javatpoint is a very good website";
4. String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
5. System.out.println(replaceString);
6. }}
Test it Now

Output:

jevetpoint is e very good website

Java String replace(CharSequence target,


CharSequence replacement) method
example
FileName: ReplaceExample2.java

1. public class ReplaceExample2{


2. public static void main(String args[]){
3. String s1="my name is khan my name is java";
4. String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
5. System.out.println(replaceString);
6. }}
Test it Now

Output:

my name was khan my name was java

Java String replace() Method Example 3


FileName: ReplaceExample3.java

1. public class ReplaceExample3 {


2. public static void main(String[] args) {
3. String str = "oooooo-hhhh-oooooo";
4. String rs = str.replace("h","s"); // Replace 'h' with 's'
5. System.out.println(rs);
6. rs = rs.replace("s","h"); // Replace 's' with 'h'
7. System.out.println(rs);
8. }
9. }

Output:

oooooo-ssss-oooooo
oooooo-hhhh-oooooo

Java String replace() Method Example 4


The replace() method throws the NullPointerException when the replacement or
target is null. The following example confirms the same.

FileName: ReplaceExample4.java

1. public class ReplaceExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = "For learning Java, JavaTpoint is a very good site.";
8. int size = str.length();
9.
10. System.out.println(str);
11. String target = null;
12.
13. // replacing null with JavaTpoint. Hence, the NullPointerException is raised.
14. str = str.replace(target, "JavaTpoint ");
15.
16. System.out.println(str);
17.
18. }
19. }

Output:

For learning Java, JavaTpoint is a very good site.


Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.replace(String.java:2142)
at ReplaceExample4.main(ReplaceExample4.java:12)

Next Topic Java String replaceAll()

Java String replaceAll()


The Java String class replaceAll() method returns a string replacing all the sequence
of characters matching regex and replacement string.

Signature

1. public String replaceAll(String regex, String replacement)

Parameters
regex : regular expression

replacement : replacement sequence of characters


Returns
replaced string

Exception Throws
PatternSyntaxException: if the syntax of the regular expression is not valid.

Internal implementation

1. public String replaceAll(String regex, String replacement) {


2. return Pattern.compile(regex).matcher(this).replaceAll(replacement);
3. }

Java String replaceAll() example: replace


character
Let's see an example to replace all the occurrences of a single character.

FileName: ReplaceAllExample1.java

1. public class ReplaceAllExample1{


2. public static void main(String args[]){
3. String s1="javatpoint is a very good website";
4. String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"
5. System.out.println(replaceString);
6. }}
Test it Now

Output:

jevetpoint is e very good website

Java String replaceAll() example: replace word


Let's see an example to replace all the occurrences of a single word or set of words.

FileName: ReplaceAllExample2.java

1. public class ReplaceAllExample2{


2. public static void main(String args[]){
3. String s1="My name is Khan. My name is Bob. My name is Sonoo.";
4. String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"
5. System.out.println(replaceString);
6. }}
Test it Now

Output:

My name was Khan. My name was Bob. My name was Sonoo.

Java String replaceAll() example: remove white


spaces
Let's see an example to remove all the occurrences of white spaces.

FileName: ReplaceAllExample3.java

1. public class ReplaceAllExample3{


2. public static void main(String args[]){
3. String s1="My name is Khan. My name is Bob. My name is Sonoo.";
4. String replaceString=s1.replaceAll("\\s","");
5. System.out.println(replaceString);
6. }}
Test it Now

Output:

MynameisKhan.MynameisBob.MynameisSonoo.

Java String replaceAll() Method Example 4


The replaceAll() method throws the PatternSyntaxException when there is an
improper regular expression. Look at the following example.

FileName: ReplaceAllExample4.java

1. public class ReplaceAllExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // input string
8. String str = "For learning Java, JavaTpoint is a very good site.";
9.
10. System.out.println(str);
11.
12. String regex = "\\"; // the regular expression is not valid.
13.
14. // invoking the replaceAll() method raises the PatternSyntaxException
15. str = str.replaceAll(regex, "JavaTpoint ");
16.
17. System.out.println(str);
18.
19. }
20. }

Output:

For learning Java, JavaTpoint is a very good site.

Exception in thread "main" java.util.regex.PatternSyntaxException:


Unexpected internal error near index 1
\
at java.base/java.util.regex.Pattern.error(Pattern.java:2015)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1784)
at java.base/java.util.regex.Pattern.(Pattern.java:1427)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.replaceAll(String.java:2126)
at ReplaceExample4.main(ReplaceExample4.java:12)

Java String replaceAll() Method Example 5


The replaceAll() method can also be used to insert spaces between characters.

FileName: ReplaceAllExample5.java

1. public class ReplaceAllExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // input string
8. String str = "JavaTpoint";
9. System.out.println(str);
10.
11. String regex = "";
12. // adding a white space before and after every character of the input string.
13. str = str.replaceAll(regex, " ");
14.
15. System.out.println(str);
16.
17. }
18. }

Output:

JavaTpoint
J a v a T p o i n t

Java String replaceAll() Method Example 6


Even the null regular expression is also not accepted by the replaceAll() method as
the NullPointerException is raised.

FileName: ReplaceAllExample6.java

1. public class ReplaceAllExample6


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // input string
8. String str = "JavaTpoint";
9. System.out.println(str);
10.
11. String regex = null; // regular expression is null
12.
13. str = str.replaceAll(regex, " ");
14.
15. System.out.println(str);
16.
17. }
18. }

Output:

JavaTpoint

Exception in thread "main" java.lang.NullPointerException


at java.base/java.util.regex.Pattern.(Pattern.java:1426)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.replaceAll(String.java:2126)
at ReplaceAllExample6.main(ReplaceAllExample6.java:13)

Next Topic Java String split()

« PrevNext »

Java String split()


The java string split() method splits this string against given regular expression and
returns a char array.

Internal implementation
1. public String[] split(String regex, int limit) {
2. /* fastpath if the regex is a
3. (1)one-char String and this character is not one of the
4. RegEx's meta characters ".$|()[{^?*+\\", or
5. (2)two-char String and the first char is the backslash and
6. the second is not the ascii digit or ascii letter.
7. */
8. char ch = 0;
9. if (((regex.value.length == 1 &&
10. ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
11. (regex.length() == 2 &&
12. regex.charAt(0) == '\\' &&
13. (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
14. ((ch-'a')|('z'-ch)) < 0 &&
15. ((ch-'A')|('Z'-ch)) < 0)) &&
16. (ch < Character.MIN_HIGH_SURROGATE ||
17. ch > Character.MAX_LOW_SURROGATE))
18. {
19. int off = 0;
20. int next = 0;
21. boolean limited = limit > 0;
22. ArrayList<String> list = new ArrayList<>();
23. while ((next = indexOf(ch, off)) != -1) {
24. if (!limited || list.size() < limit - 1) {
25. list.add(substring(off, next));
26. off = next + 1;
27. } else { // last one
28. //assert (list.size() == limit - 1);
29. list.add(substring(off, value.length));
30. off = value.length;
31. break;
32. }
33. }
34. // If no match was found, return this
35. if (off == 0)
36. return new String[]{this};
37.
38. // Add remaining segment
39. if (!limited || list.size() < limit)
40. list.add(substring(off, value.length));
41.
42. // Construct result
43. int resultSize = list.size();
44. if (limit == 0)
45. while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
46. resultSize--;
47. String[] result = new String[resultSize];
48. return list.subList(0, resultSize).toArray(result);
49. }
50. return Pattern.compile(regex).split(this, limit);
51. }

Signature
There are two signature for split() method in java string.

1. public String split(String regex)


2. and,
3. public String split(String regex, int limit)

Parameter
regex : regular expression to be applied on string.

limit : limit for the number of strings in array. If it is zero, it will returns all the strings
matching regex.

Returns
array of strings

Throws
PatternSyntaxException if pattern for regular expression is invalid

Since
1.4

Java String split() method example


The given example returns total number of words in a string excluding space only. It
also includes special characters.

1. public class SplitExample{


2. public static void main(String args[]){
3. String s1="java string split method by javatpoint";
4. String[] words=s1.split("\\s");//splits the string based on whitespace
5. //using java foreach loop to print elements of string array
6. for(String w:words){
7. System.out.println(w);
8. }
9. }}
Test it Now
java
string
split
method
by
javatpoint

Java String split() method with regex and


length example
1. public class SplitExample2{
2. public static void main(String args[]){
3. String s1="welcome to split world";
4. System.out.println("returning words:");
5. for(String w:s1.split("\\s",0)){
6. System.out.println(w);
7. }
8. System.out.println("returning words:");
9. for(String w:s1.split("\\s",1)){
10. System.out.println(w);
11. }
12. System.out.println("returning words:");
13. for(String w:s1.split("\\s",2)){
14. System.out.println(w);
15. }
16.
17. }}
Test it Now
returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world

Java String split() method with regex and


length example 2
Here, we are passing split limit as a second argument to this function. This limits the
number of splitted strings.

1. public class SplitExample3 {


2. public static void main(String[] args) {
3. String str = "Javatpointtt";
4. System.out.println("Returning words:");
5. String[] arr = str.split("t", 0);
6. for (String w : arr) {
7. System.out.println(w);
8. }
9. System.out.println("Split array length: "+arr.length);
10. }
11. }
Returning words:
Java
poin
Split array length: 2

Next Topic Java String startswith()

« PrevNext »

Java String startsWith()


The Java String class startsWith() method checks if this string starts with the given
prefix. It returns true if this string starts with the given prefix; else returns false.

Signature
The syntax or signature of startWith() method is given below.
1. public boolean startsWith(String prefix)
2. public boolean startsWith(String prefix, int offset)

Parameter
prefix : Sequence of character

offset: the index from where the matching of the string prefix starts.

Returns
true or false

Internal implementation of startsWith(String prefix,


int toffset)

1. public boolean startsWith(String prefix, int toffset) {


2. char ta[] = value;
3. int to = toffset;
4. char pa[] = prefix.value;
5. int po = 0;
6. int pc = prefix.value.length;
7. // Note: toffset might be near -1>>>1.
8. if ((toffset < 0) || (toffset > value.length - pc)) {
9. return false;
10. }
11. while (--pc >= 0) {
12. if (ta[to++] != pa[po++]) {
13. return false;
14. }
15. }
16. return true;
17. }

Internal Implementation of startsWith(String


prefix,)

1. // Since the offset is not mentioned in this type of startWith() method, the offset is
2. // considered as 0.
3. public boolean startsWith(String prefix)
4. {
5. // the offset is 0
6. return startsWith(prefix, 0);
7. }

Java String startsWith() method example


The startsWith() method considers the case-sensitivity of characters. Consider the
following example.

FileName: StartsWithExample.java

1. public class StartsWithExample


2. {
3. // main method
4. public static void main(String args[])
5. {
6. // input string
7. String s1="java string split method by javatpoint";
8. System.out.println(s1.startsWith("ja")); // true
9. System.out.println(s1.startsWith("java string")); // true
10. System.out.println(s1.startsWith("Java string")); // false as 'j' and 'J' are different
11. }
12. }

Output:

true
true
false

Java String startsWith(String prefix, int


offset) Method Example
It is an overloaded method of the startWith() method that is used to pass an extra
argument (offset) to the function. The method works from the passed offset. Let's see
an example.
FileName: StartsWithExample2.java

1. public class StartsWithExample2 {


2. public static void main(String[] args) {
3. String str = "Javatpoint";
4. // no offset mentioned; hence, offset is 0 in this case.
5. System.out.println(str.startsWith("J")); // True
6.
7. // no offset mentioned; hence, offset is 0 in this case.
8. System.out.println(str.startsWith("a")); // False
9. // offset is 1
10. System.out.println(str.startsWith("a",1)); // True
11. }
12. }

Output:

true
false
true

Java String startsWith() Method Example -


3
If we adding an empty string at the beginning of a string, then it has no impact at all
on the string.

"" + "Tokyo Olympics" = "Tokyo Olympics"s

It means one can say that a string in Java always starts with the empty string. Let's
confirm the same with the help of Java code.

FileName: StartsWithExample3.java

1. public class StartsWithExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. // input string
7. String str = "Tokyo Olympics";
8.
9. if(str.startsWith(""))
10. {
11. System.out.println("The string starts with the empty string.");
12. }
13. else
14. {
15. System.
16. out.println("The string does not start with the empty string.");
17. }
18.
19. }
20. }

Output:

The string starts with the empty string.

Next Topic Java String substring()

« PrevNext »

Java String substring()


The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method
where beginIndex is inclusive, and endIndex is exclusive. In other words, the
beginIndex starts from 0, whereas the endIndex starts from 1.

There are two types of substring methods in Java string.

Signature

1. public String substring(int startIndex) // type - 1


2. and
3. public String substring(int startIndex, int endIndex) // type - 2

If we don't specify endIndex, the method will return all the characters from
startIndex.

Parameters
startIndex : starting index is inclusive

endIndex : ending index is exclusive

Returns
specified string

Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following
conditions is met.

o if the start index is negative value


o end index is lower than starting index.
o Either starting or ending index is greater than the total number of characters present
in the string.

Internal implementation substring(int beginIndex)

1. public String substring(int beginIndex) {


2. if (beginIndex < 0) {
3. throw new StringIndexOutOfBoundsException(beginIndex);
4. }
5. int subLen = value.length - beginIndex;
6. if (subLen < 0) {
7. throw new StringIndexOutOfBoundsException(subLen);
8. }
9. return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
10. }

Internal implementation substring(int beginIndex,


int endIndex)

1. public String substring(int beginIndex, int endIndex)


2. {
3. if (beginIndex < 0)
4. {
5. throw new StringIndexOutOfBoundsException(beginIndex);
6. }
7. if (endIndex > value.length)
8. {
9. throw new StringIndexOutOfBoundsException(endIndex);
10. }
11. int subLen = endIndex - beginIndex;
12. if (subLen < 0)
13. {
14. throw new StringIndexOutOfBoundsException(subLen);
15. }
16. return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIn
dex, subLen);
17. }

Java String substring() method example


FileName: SubstringExample.java

1. public class SubstringExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}
Test it Now

Output:

va
vatpoint

Java String substring() Method Example 2


FileName: SubstringExample2.java

1. public class SubstringExample2 {


2. public static void main(String[] args) {
3. String s1="Javatpoint";
4. String substr = s1.substring(0); // Starts with 0 and goes to end
5. System.out.println(substr);
6. String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
7. System.out.println(substr2);
8. String substr3 = s1.substring(5,15); // Returns Exception
9. }
10. }

Output:

Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin
5, end 15, length 10

Applications of substring() Method


1) The substring() method can be used to do some prefix or suffix extraction. For
example, we can have a list of names, and it is required to filter out names with
surname as "singh". The following program shows the same.

FileName: SubstringExample3.java

1. public class SubstringExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str[] =
7. {
8. "Praveen Kumar",
9. "Yuvraj Singh",
10. "Harbhajan Singh",
11. "Gurjit Singh",
12. "Virat Kohli",
13. "Rohit Sharma",
14. "Sandeep Singh",
15. "Milkha Singh"
16. };
17.
18. String surName = "Singh";
19. int surNameSize = surName.length();
20.
21. int size = str.length;
22.
23. for(int j = 0; j < size; j++)
24. {
25. int length = str[j].length();
26. // extracting the surname
27. String subStr = str[j].substring(length - surNameSize);
28.
29. // checks whether the surname is equal to "Singh" or not
30. if(subStr.equals(surName))
31. {
32. System.out.println(str[j]);
33. }
34. }
35.
36. }
37. }
Output:

Yuvraj Singh
Harbhajan Singh
Gurjit Singh
Sandeep Singh
Milkha Singh

2) The substring() method can also be used to check whether a string is a palindrome
or not.

FileName: SubstringExample4.java

1. public class SubstringExample4


2. {
3. public boolean isPalindrome(String str)
4. {
5. int size = str.length();
6.
7. // handling the base case
8. if(size == 0 || size == 1)
9. {
10. // an empty string
11. // or a string of only one character
12. // is always a palindrome
13. return true;
14. }
15. String f = str.substring(0, 1);
16. String l = str.substring(size - 1);
17. // comparing first and the last character of the string
18. if(l.equals(f))
19. {
20. // recursively finding the solution using the substring() method
21. // reducing the number of characters of the by 2 for the next recursion
22. return isPalindrome(str.substring(1, size - 1));
23. }
24. return false;
25. }
26. // main method
27. public static void main(String argvs[])
28. {
29. // instantiating the class SubstringExample4
30. SubstringExample4 obj = new SubstringExample4();
31. String str[] =
32. {
33. "madam",
34. "rock",
35. "eye",
36. "noon",
37. "kill"
38. };
39. int size = str.length;
40.
41. for(int j = 0; j < size; j++)
42. {
43. if(obj.isPalindrome(str[j]))
44. {
45. System.out.println(str[j] + " is a palindrome.");
46. }
47. else
48. {
49. System.out.println(str[j] + " is not a palindrome.");
50. }
51. }
52. }
53. }

Output:

madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.

Next Topic Java String toCharArray()


Java String toCharArray()
The java string toCharArray() method converts this string into character array. It
returns a newly created character array, its length is similar to this string and its
contents are initialized with the characters of this string.

Internal implementation

1. public char[] toCharArray() {


2. // Cannot use Arrays.copyOf because of class initialization order issues
3. char result[] = new char[value.length];
4. System.arraycopy(value, 0, result, 0, value.length);
5. return result;
6. }

Signature
The signature or syntax of string toCharArray() method is given below:

1. public char[] toCharArray()

Returns
character array

Java String toCharArray() method example


1. public class StringToCharArrayExample{
2. public static void main(String args[]){
3. String s1="hello";
4. char[] ch=s1.toCharArray();
5. for(int i=0;i<ch.length;i++){
6. System.out.print(ch[i]);
7. }
8. }}
Test it Now

Output:

hello

Java String toCharArray() Method Example


2
Let's see one more example of char array. It is useful method which returns char array
from the string without writing any custom code.

1. public class StringToCharArrayExample2 {


2. public static void main(String[] args) {
3. String s1 = "Welcome to Javatpoint";
4. char[] ch = s1.toCharArray();
5. int len = ch.length;
6. System.out.println("Char Array length: " + len);
7. System.out.println("Char Array elements: ");
8. for (int i = 0; i < len; i++) {
9. System.out.println(ch[i]);
10. }
11. }
12. }

Output:

Char Array length: 21


Char Array elements:
W
e
l
c
o
m
e

t
o

J
a
v
a
t
p
o
i
n
t

Next Topic Java String toLowerCase()

« PrevNext »
Java String toLowerCase()
The java string toLowerCase() method returns the string in lowercase letter. In
other words, it converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method.


It internally uses the default locale.

Internal implementation

1. public String toLowerCase(Locale locale) {


2. if (locale == null) {
3. throw new NullPointerException();
4. }
5.
6. int firstUpper;
7. final int len = value.length;
8.
9. /* Now check if there are any characters that need to be changed. */
10. scan: {
11. for (firstUpper = 0 ; firstUpper < len; ) {
12. char c = value[firstUpper];
13. if ((c >= Character.MIN_HIGH_SURROGATE)
14. && (c <= Character.MAX_HIGH_SURROGATE)) {
15. int supplChar = codePointAt(firstUpper);
16. if (supplChar != Character.toLowerCase(supplChar)) {
17. break scan;
18. }
19. firstUpper += Character.charCount(supplChar);
20. } else {
21. if (c != Character.toLowerCase(c)) {
22. break scan;
23. }
24. firstUpper++;
25. }
26. }
27. return this;
28. }
29.
30. char[] result = new char[len];
31. int resultOffset = 0; /* result may grow, so i+resultOffset
32. * is the write location in result */
33.
34. /* Just copy the first few lowerCase characters. */
35. System.arraycopy(value, 0, result, 0, firstUpper);
36.
37. String lang = locale.getLanguage();
38. boolean localeDependent =
39. (lang == "tr" || lang == "az" || lang == "lt");
40. char[] lowerCharArray;
41. int lowerChar;
42. int srcChar;
43. int srcCount;
44. for (int i = firstUpper; i < len; i += srcCount) {
45. srcChar = (int)value[i];
46. if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
47. && (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
48. srcChar = codePointAt(i);
49. srcCount = Character.charCount(srcChar);
50. } else {
51. srcCount = 1;
52. }
53. if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGM
A
54. lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
55. } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
56. lowerChar = Character.ERROR;
57. } else {
58. lowerChar = Character.toLowerCase(srcChar);
59. }
60. if ((lowerChar == Character.ERROR)
61. || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
62. if (lowerChar == Character.ERROR) {
63. if (!localeDependent && srcChar == '\u0130') {
64. lowerCharArray =
65. ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.E
NGLISH);
66. } else {
67. lowerCharArray =
68. ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
69. }
70. } else if (srcCount == 2) {
71. resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - sr
cCount;
72. continue;
73. } else {
74. lowerCharArray = Character.toChars(lowerChar);
75. }
76.
77. /* Grow result if needed */
78. int mapLen = lowerCharArray.length;
79. if (mapLen > srcCount) {
80. char[] result2 = new char[result.length + mapLen - srcCount];
81. System.arraycopy(result, 0, result2, 0, i + resultOffset);
82. result = result2;
83. }
84. for (int x = 0; x < mapLen; ++x) {
85. result[i + resultOffset + x] = lowerCharArray[x];
86. }
87. resultOffset += (mapLen - srcCount);
88. } else {
89. result[i + resultOffset] = (char)lowerChar;
90. }
91. }
92. return new String(result, 0, len + resultOffset);
93. }

Signature
There are two variant of toLowerCase() method. The signature or syntax of string
toLowerCase() method is given below:

1. public String toLowerCase()


2. public String toLowerCase(Locale locale)

The second method variant of toLowerCase(), converts all the characters into
lowercase using the rules of given Locale.

Returns
string in lowercase letter.

Java String toLowerCase() method


example
1. public class StringLowerExample{
2. public static void main(String args[]){
3. String s1="JAVATPOINT HELLO stRIng";
4. String s1lower=s1.toLowerCase();
5. System.out.println(s1lower);
6. }}
Test it Now

Output:

javatpoint hello string

Java String toLowerCase(Locale locale)


Method Example 2
This method allows us to pass locale too for the various langauges. Let's see an
example below where we are getting string in english and turkish both.

1. import java.util.Locale;
2. public class StringLowerExample2 {
3. public static void main(String[] args) {
4. String s = "JAVATPOINT HELLO stRIng";
5. String eng = s.toLowerCase(Locale.ENGLISH);
6. System.out.println(eng);
7. String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i withou
t dot
8. System.out.println(turkish);
9. }
10. }

Output:

javatpoint hello string


javatpo?nt hello str?ng

Next Topic Java String toUpperCase

← PrevNext →
Java String toUpperCase()
The java string toUpperCase() method returns the string in uppercase letter. In
other words, it converts all characters of the string into upper case letter.

The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method.


It internally uses the default locale.

Internal implementation

1. public String toUpperCase(Locale locale) {


2. if (locale == null) {
3. throw new NullPointerException();
4. }
5.
6. int firstLower;
7. final int len = value.length;
8.
9. /* Now check if there are any characters that need to be changed. */
10. scan: {
11. for (firstLower = 0 ; firstLower < len; ) {
12. int c = (int)value[firstLower];
13. int srcCount;
14. if ((c >= Character.MIN_HIGH_SURROGATE)
15. && (c <= Character.MAX_HIGH_SURROGATE)) {
16. c = codePointAt(firstLower);
17. srcCount = Character.charCount(c);
18. } else {
19. srcCount = 1;
20. }
21. int upperCaseChar = Character.toUpperCaseEx(c);
22. if ((upperCaseChar == Character.ERROR)
23. || (c != upperCaseChar)) {
24. break scan;
25. }
26. firstLower += srcCount;
27. }
28. return this;
29. }
30.
31. char[] result = new char[len]; /* may grow */
32. int resultOffset = 0; /* result may grow, so i+resultOffset
33. * is the write location in result */
34.
35. /* Just copy the first few upperCase characters. */
36. System.arraycopy(value, 0, result, 0, firstLower);
37.
38. String lang = locale.getLanguage();
39. boolean localeDependent =
40. (lang == "tr" || lang == "az" || lang == "lt");
41. char[] upperCharArray;
42. int upperChar;
43. int srcChar;
44. int srcCount;
45. for (int i = firstLower; i < len; i += srcCount) {
46. srcChar = (int)value[i];
47. if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
48. (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
49. srcChar = codePointAt(i);
50. srcCount = Character.charCount(srcChar);
51. } else {
52. srcCount = 1;
53. }
54. if (localeDependent) {
55. upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
56. } else {
57. upperChar = Character.toUpperCaseEx(srcChar);
58. }
59. if ((upperChar == Character.ERROR)
60. || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
61. if (upperChar == Character.ERROR) {
62. if (localeDependent) {
63. upperCharArray =
64. ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
65. } else {
66. upperCharArray = Character.toUpperCaseCharArray(srcChar);
67. }
68. } else if (srcCount == 2) {
69. resultOffset += Character.toChars(upperChar, result, i + resultOffset) - src
Count;
70. continue;
71. } else {
72. upperCharArray = Character.toChars(upperChar);
73. }
74.
75. /* Grow result if needed */
76. int mapLen = upperCharArray.length;
77. if (mapLen > srcCount) {
78. char[] result2 = new char[result.length + mapLen - srcCount];
79. System.arraycopy(result, 0, result2, 0, i + resultOffset);
80. result = result2;
81. }
82. for (int x = 0; x < mapLen; ++x) {
83. result[i + resultOffset + x] = upperCharArray[x];
84. }
85. resultOffset += (mapLen - srcCount);
86. } else {
87. result[i + resultOffset] = (char)upperChar;
88. }
89. }
90. return new String(result, 0, len + resultOffset);
91. }

Signature
There are two variant of toUpperCase() method. The signature or syntax of string
toUpperCase() method is given below:
1. public String toUpperCase()
2. public String toUpperCase(Locale locale)

The second method variant of toUpperCase(), converts all the characters into
uppercase using the rules of given Locale.

Returns
string in uppercase letter.

Java String toUpperCase() method


example
1. public class StringUpperExample{
2. public static void main(String args[]){
3. String s1="hello string";
4. String s1upper=s1.toUpperCase();
5. System.out.println(s1upper);
6. }}
Test it Now

Output:

HELLO STRING

Java String toUpperCase(Locale locale)


Method Example 2
1. import java.util.Locale;
2. public class StringUpperExample2 {
3. public static void main(String[] args) {
4. String s = "hello string";
5. String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
6. String english = s.toUpperCase(Locale.forLanguageTag("en"));
7. System.out.println(turkish);//will print I with dot on upper side
8. System.out.println(english);
9. }
10. }

Output:

HELLO STR?NG
HELLO STRING

Next Topic Java String trim()

← PrevNext →
Java String trim()
The Java String class trim() method eliminates leading and trailing spaces. The
Unicode value of space character is '\u0020'. The trim() method in Java string checks
this Unicode value before and after the string, if it exists then the method removes
the spaces and returns the omitted string.

The string trim() method doesn't omit middle spaces.

Signature
The signature or syntax of the String class trim() method is given below:

1. public String trim()

Returns
string with omitted leading and trailing spaces

Internal implementation

1. public String trim() {


2. int len = value.length;
3. int st = 0;
4. char[] val = value; /* avoid getfield opcode */
5.
6. while ((st < len) && (val[st] <= ' ')) {
7. st++;
8. }
9. while ((st < len) && (val[len - 1] <= ' ')) {
10. len--;
11. }
12. return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
13. }
Java String trim() Method Example
FileName: StringTrimExample.java

1. public class StringTrimExample{


2. public static void main(String args[]){
3. String s1=" hello string ";
4. System.out.println(s1+"javatpoint");//without trim()
5. System.out.println(s1.trim()+"javatpoint");//with trim()
6. }}
Test it Now

Output

hello string javatpoint


hello stringjavatpoint

Java String trim() Method Example 2


The example demonstrates the use of the trim() method. This method removes all
the trailing spaces so the length of the string also reduces. Let's see an example.

FileName: StringTrimExample2.java

1. public class StringTrimExample2 {


2. public static void main(String[] args) {
3. String s1 =" hello java string ";
4. System.out.println(s1.length());
5. System.out.println(s1); //Without trim()
6. String tr = s1.trim();
7. System.out.println(tr.length());
8. System.out.println(tr); //With trim()
9. }
10. }

Output

22
hello java string
17
hello java string
Java String trim() Method Example 3
The trim() can be used to check whether the string only contains white spaces or not.
The following example shows the same.

FileName: TrimExample3.java

1. public class TrimExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = " abc ";
8.
9. if((str.trim()).length() > 0)
10. {
11. System.out.println("The string contains characters other than white spaces \n");
12. }
13. else
14. {
15. System.out.println("The string contains only white spaces \n");
16. }
17.
18. str = " ";
19.
20. if((str.trim()).length() > 0)
21. {
22. System.out.println("The string contains characters other than white spaces \n");
23. }
24. else
25. {
26. System.out.println("The string contains only white spaces \n");
27. }
28.
29. }
30. }
Output

The string contains characters other than white spaces

The string contains only white spaces

Java String trim() Method Example 4


Since strings in Java are immutable; therefore, when the trim() method manipulates
the string by trimming the whitespaces, it returns a new string. If the manipulation is
not done by the trim() method, then the reference of the same string is returned.
Observe the following example.

FileName: TrimExample4.java

1. public class TrimExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // the string contains white spaces
8. // therefore, trimming the spaces leads to the
9. // generation of new string
10. String str = " abc ";
11.
12. // str1 stores a new string
13. String str1 = str.trim();
14.
15. // the hashcode of str and str1 is different
16. System.out.println(str.hashCode());
17. System.out.println(str1.hashCode() + "\n");
18.
19. // no white space present in the string s
20. // therefore, the reference of the s is returned
21. // when the trim() method is invoked
22. String s = "xyz";
23. String s1 = s.trim();
24.
25. // the hashcode of s and s1 is the same
26. System.out.println(s.hashCode());
27. System.out.println(s1.hashCode());
28.
29. }
30. }

Output

The string contains characters other than white spaces

The string contains only white spaces

Next Topic Java String valueOf()

← PrevNext →
Java String valueOf()
The java string valueOf() method converts different types of values into string. By
the help of string valueOf() method, you can convert int to string, long to string,
boolean to string, character to string, float to string, double to string, object to string
and char array to string.

Internal implementation

1. public static String valueOf(Object obj) {


2. return (obj == null) ? "null" : obj.toString();
3. }

Signature
The signature or syntax of string valueOf() method is given below:

1. public static String valueOf(boolean b)


2. public static String valueOf(char c)
3. public static String valueOf(char[] c)
4. public static String valueOf(int i)
5. public static String valueOf(long l)
6. public static String valueOf(float f)
7. public static String valueOf(double d)
8. public static String valueOf(Object o)

Returns
string representation of given value
Java String valueOf() method example
1. public class StringValueOfExample{
2. public static void main(String args[]){
3. int value=30;
4. String s1=String.valueOf(value);
5. System.out.println(s1+10);//concatenating string with 10
6. }}
Test it Now

Output:

3010

Java String valueOf(boolean bol) Method


Example
This is a boolean version of overloaded valueOf() method. It takes boolean value and
returns a string. Let's see an example.

1. public class StringValueOfExample2 {


2. public static void main(String[] args) {
3. // Boolean to String
4. boolean bol = true;
5. boolean bol2 = false;
6. String s1 = String.valueOf(bol);
7. String s2 = String.valueOf(bol2);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

true
false
Java String valueOf(char ch) Method
Example
This is a char version of overloaded valueOf() method. It takes char value and returns
a string. Let's see an example.

1. public class StringValueOfExample3 {


2. public static void main(String[] args) {
3. // char to String
4. char ch1 = 'A';
5. char ch2 = 'B';
6. String s1 = String.valueOf(ch1);
7. String s2 = String.valueOf(ch2);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

A
B

Java String valueOf(float f) and


valueOf(double d)
This is a float version of overloaded valueOf() method. It takes float value and returns
a string. Let's see an example.

1. public class StringValueOfExample4 {


2. public static void main(String[] args) {
3. // Float and Double to String
4. float f = 10.05f;
5. double d = 10.02;
6. String s1 = String.valueOf(f);
7. String s2 = String.valueOf(d);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

10.05
10.02

Java String valueOf() Complete Examples


Let's see an example where we are converting all primitives and objects into strings.

1. public class StringValueOfExample5 {


2. public static void main(String[] args) {
3. boolean b1=true;
4. byte b2=11;
5. short sh = 12;
6. int i = 13;
7. long l = 14L;
8. float f = 15.5f;
9. double d = 16.5d;
10. char chr[]={'j','a','v','a'};
11. StringValueOfExample5 obj=new StringValueOfExample5();
12. String s1 = String.valueOf(b1);
13. String s2 = String.valueOf(b2);
14. String s3 = String.valueOf(sh);
15. String s4 = String.valueOf(i);
16. String s5 = String.valueOf(l);
17. String s6 = String.valueOf(f);
18. String s7 = String.valueOf(d);
19. String s8 = String.valueOf(chr);
20. String s9 = String.valueOf(obj);
21. System.out.println(s1);
22. System.out.println(s2);
23. System.out.println(s3);
24. System.out.println(s4);
25. System.out.println(s5);
26. System.out.println(s6);
27. System.out.println(s7);
28. System.out.println(s8);
29. System.out.println(s9);
30. }
31. }
Test it Now

Output:

true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

Next Topic Java Regex

You might also like