String Notes
String Notes
What is String
Immutable String
String Comparison
String Concatenation
Substring
StringBuffer class
StringBuilder class
String vs StringBuffer
StringBuffer vs Builder
toString method
StringTokenizer class
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.
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.
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.
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".
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).
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.
4 static String format(Locale l, String format, Object... It returns formatted string with g
args) locale.
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?
Next →
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".
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.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
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.
← PrevNext →
Java String compare
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.
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
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
« 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:
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
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.
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
StrBuilder.java
Output:
Hello World
Output:
Hello World
StrJoin.java:
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.
StrJoiner.java
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:
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() method.
← 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.
You can get substring from the given String object by one of the two methods:
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).
Output:
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:
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.
← 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.
Stringoperation1.java
SACHIN
sachin
Sachin
Stringoperation2.java
Output:
Sachin
Sachin
Stringoperation3.java
Output:
true
true
Stringoperation4.java
Output:
S
h
Stringoperation5.java
Output:
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
Output:
Sachin
Stringoperation7.java
Output:
1010
Stringoperation8.java
Output:
← PrevNext →
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.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
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 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)
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
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
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
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
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
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
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
← 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.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
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 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.
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
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
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
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
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
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
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
← PrevNext →
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.
Output:
The above code, calculates the time required for concatenating a string using the
String class and StringBuffer class.
InstanceTest.java
Output:
← 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.
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
Output:
hellojava
StringBuilder Example
BuilderTest.java
Output:
hellojava
Performance Test of StringBuffer and
StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
ConcatTest.java
Output:
← 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:
ImmutableDemo.java
Output:
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.
← PrevNext →
Java toString() Method
If you want to represent any object as a string, toString() method comes into
existence.
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.
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:
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:
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.
← PrevNext →
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
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, 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.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
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().
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.
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
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
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:
← PrevNext →
this is javatpoint
Output:
tnioptavaj si siht
nitin
Output:
true
Input:
jatin
Output:
false
this is javatpoint
Output:
This Is Javatpoint
this is javatpoint
Output:
siht si tnioptavaj
this is javatpoint
Output:
tHIS iS jAVATPOINT
Output:
sIHT sI tNIOPTAVAJ
← 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
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
File: TestStringFormatter.java
Output:
nahk si eman ym
lawsiaj oonos ma I
Next Topic Java String FAQs
← PrevNext →
this is javatpoint
Output:
tnioptavaj si siht
nitin
Output:
true
Input:
jatin
Output:
false
this is javatpoint
Output:
This Is Javatpoint
this is javatpoint
Output:
siht si tnioptavaj
this is javatpoint
Output:
tHIS iS jAVATPOINT
this is javatpoint
Output:
sIHT sI tNIOPTAVAJ
← PrevNext →
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
Internal implementation
FileName: CharAtExample.java
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
Output:
FileName: CharAtExample3.java
Output:
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
FileName: CharAtExample5.java
Output:
Frequency of t is: 4
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:
← 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
The method accepts a parameter of type String that is to be compared with the
current string.
ClassCastException: If this object cannot get compared with the specified object.
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
Output:
0
-5
-1
2
FileName: CompareToExample2.java
Output:
5
-2
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
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.
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:
FileName: CompareToExample5.java
Output:
← PrevNext →
Signature
The signature of the string concat() method is given below:
Parameter
anotherString : another string i.e., to be combined at the end of this string.
Returns
combined string
Internal implementation
Output:
java string
java string is immutable so assign it explicitly
FileName: ConcatExample2.java
Output:
HelloJavatpoint
HelloJavatpointReader
FileName: ConcatExample3.java
Output:
FileName: ConcatExample4.java
Output:
India is my Country
← PrevNext →
Signature
The signature of string contains() method is given below:
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
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.
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
FileName: ContainsExample2.java
Output:
true
false
FileName: ContainsExample3.java
Output:
FileName: ContainsExample4.java
Output:
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.
← PrevNext →
Signature
The syntax or signature of endsWith() method is given below.
Returns
true or false
Internal implementation
The internal implementation shows that the endWith() method is dependent on the
startsWith() method of the String class.
Output:
true
true
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
FileName: EndsWithExample3.java
false
false
true
The statement
results in
Thus, we can say that any string in Java ends with an empty string (""). Observe the
FileName: EndsWithExample4.java
true
false
FileName: EndsWithExample5.java
Output:
FileName: EndsWithExample6.java
Output:
← PrevNext →
The String equals() method overrides the equals() method of the Object class.
Signature
Returns
true if characters of both strings are equal otherwise false.
Internal implementation
Output:
true
false
false
FileName: EqualsExample2.java
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
FileName: EqualsExample4.java
Output:
false
false
false
false
true
true
true
true
Next Topic Java String equalsIgnoreCase()
← PrevNext →
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
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset,
int len)
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
Output:
true
true
false
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:
← PrevNext →
If you don't specify the locale in String.format() method, it uses default locale by
calling Locale.getDefault() method.
Internal implementation
Signature
There are two type of string format() method:
Parameters
locale : specifies the locale to be applied on the format() method.
Returns
formatted string
Throws
NullPointerException : if format is null.
%a floating point (except BigDecimal) Returns Hex output of floating point number.
« PrevNext »
Signature
There are three variants of getBytes() method. The signature or syntax of string
getBytes() method is given below:
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
FileName: StringGetBytesExample.java
Output:
65
66
67
68
69
70
71
The method returns a byte array that again can be passed to the String constructor
to get String.
Output:
65
66
67
68
69
70
71
ABCDEFG
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:
FileName: StringGetBytesExample4.java
Output:
← PrevNext →
Next →← Prev
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.
Internal implementation
The signature or syntax of string getChars() method is given below:
Output:
javatpoint
FileName: StringGetCharsExample2.java
Output:
FileName: StringGetCharsExample3.java
Output:
The getChars() method prints nothing as start and end indices are equal.
← 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:
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.
Returns
Index of the searched string or character.
Internal Implementation
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
FileName: IndexOfExample2.java
Output:
index of substring 16
FileName: IndexOfExample3.java
Output:
index of substring 16
index of substring -1
FileName: IndexOfExample4.java
Output:
index of char 17
Signature
The signature of the intern() method is given below:
Returns
interned string
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.
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.
Output:
false
true
FileName: InternExample2.java
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,
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.
« 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:
Returns
true if length is 0 otherwise false.
Since
1.6
Internal implementation
Output:
true
false
Output:
String s1 is empty
Javatpoint
The isEmpty() method is not fit for checking the null strings. The following example
shows the same.
FileName: StringIsEmptyExample3.java
Output:
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:
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
Output:
There are two types of join() methods in the Java String class.
Signature
The signature or syntax of the join() method is given below:
Parameters
delimiter : char value to be added with each element
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. }
Output:
welcome-to-javatpoint
FileName: StringJoinExample2.java
Output:
25/06/2018 12:10:10
FileName: StringJoinExample3.java
Output:
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:
FileName: StringJoinExample5.java
Output:
Signature
There are four types of lastIndexOf() method in Java. The signature of the methods
are given below:
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
Returns
last index of the string
Internal Implementation
The internal implementation of the four types of the lastIndexOf() method is
mentioned below.
Output:
FileName: LastIndexOfExample2.java
Output:
FileName: LastIndexOfExample3.java
Output:
19
FileName: LastIndexOfExample4.java
Output:
19
-1
Next Topic Java String length()
← PrevNext →
Signature
The signature of the string length() method is given below:
Specified by
CharSequence interface
Returns
Length of characters. In other words, the total number of characters present in the
string.
Internal implementation
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.
Output:
FileName: LengthExample2.java
Output:
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:
FileName: LengthExample4.java
Output:
← PrevNext →
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.
Parameters
oldChar : old character
Returns
replaced string
Exception Throws
NullPointerException: if the replacement or target is equal to null.
Internal implementation
Output:
Output:
Output:
oooooo-ssss-oooooo
oooooo-hhhh-oooooo
FileName: ReplaceExample4.java
Output:
Signature
Parameters
regex : regular expression
Exception Throws
PatternSyntaxException: if the syntax of the regular expression is not valid.
Internal implementation
FileName: ReplaceAllExample1.java
Output:
FileName: ReplaceAllExample2.java
Output:
FileName: ReplaceAllExample3.java
Output:
MynameisKhan.MynameisBob.MynameisSonoo.
FileName: ReplaceAllExample4.java
Output:
FileName: ReplaceAllExample5.java
Output:
JavaTpoint
J a v a T p o i n t
FileName: ReplaceAllExample6.java
Output:
JavaTpoint
« PrevNext »
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.
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
« PrevNext »
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
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. }
FileName: StartsWithExample.java
Output:
true
true
false
Output:
true
false
true
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
Output:
« PrevNext »
Signature
If we don't specify endIndex, the method will return all the characters from
startIndex.
Parameters
startIndex : starting index is inclusive
Returns
specified string
Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following
conditions is met.
Output:
va
vatpoint
Output:
Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin
5, end 15, length 10
FileName: SubstringExample3.java
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
Output:
madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.
Internal implementation
Signature
The signature or syntax of string toCharArray() method is given below:
Returns
character array
Output:
hello
Output:
t
o
J
a
v
a
t
p
o
i
n
t
« 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.
Internal implementation
Signature
There are two variant of toLowerCase() method. The signature or syntax of string
toLowerCase() method is given below:
The second method variant of toLowerCase(), converts all the characters into
lowercase using the rules of given Locale.
Returns
string in lowercase letter.
Output:
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:
← 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.
Internal implementation
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.
Output:
HELLO STRING
Output:
HELLO STR?NG
HELLO STRING
← 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.
Signature
The signature or syntax of the String class trim() method is given below:
Returns
string with omitted leading and trailing spaces
Internal implementation
Output
FileName: StringTrimExample2.java
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
FileName: TrimExample4.java
Output
← 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
Signature
The signature or syntax of string valueOf() method is given below:
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
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.
Output:
A
B
Output:
10.05
10.02
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55