STRINGS
Introduction
In Java, string is basically an object that represents a sequence of char values.
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
Example:
String greeting = "Hello";
An array of characters works the same as a Java string.
For example:
char[] ch={'j','a','v','a'};
String s=new String(ch);
is same as:
String s="java";
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
String Literal
Java String literal is created by using double quotes. For Example:
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:
String s1="Welcome";
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 the 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 does Java use the concept of String literal?
1) 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
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
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example
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) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, returns a formatted string.
Object... args)
4 String substring(int beginIndex) returns substring for given begin index.
5 String substring(int beginIndex, returns substring for given begin index and end
int endIndex) index.
6 boolean contains(CharSequence s) returns true or false after matching the
sequence of char value.
7 static String join(CharSequence returns a joined string.
delimiter, CharSequence...
elements)
8 boolean equals(Object another) checks the equality of string with the given
object.
9 boolean isEmpty() checks if string is empty.
10 String concat(String str) concatenates the specified string.
11 String replace(char old, char new) replaces all occurrences of the specified char
value.
12 String replace(CharSequence old, replaces all occurrences of the specified
CharSequence new) CharSequence.
13 static String compares another string. It doesn't check case.
equalsIgnoreCase(String another)
14 String[] split(String regex) returns a split string matching regex.
15 String[] split(String regex, int returns a split string matching regex and limit.
limit)
16 String intern() returns an interned string.
17 int indexOf(int ch) returns the specified char value index.
18 int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.
19 int indexOf(String substring) returns the specified substring index.
20 int indexOf(String substring, int returns the specified substring index starting
fromIndex) with given index.
21 String toLowerCase() returns a string in lowercase.
22 String toLowerCase(Locale l) returns a string in lowercase using specified
locale.
23 String toUpperCase() returns a string in uppercase.
24 String toUpperCase(Locale l) returns a string in uppercase using specified
locale.
25 String trim() removes beginning and ending spaces of this
string.
26 static String valueOf(int value) converts given type into string. It is an
overloaded method.
Java String charAt()
The java string 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 length of the string. It
returns StringIndexOutOfBoundsException if given index number is greater than or equal
to this string length or a negative number.
Java String charAt() method example
public class CharAtExample{
public static void main(String args[]){
String name="java";
char ch=name.charAt(2);//returns the char value at the 2nd index
System.out.println(ch);
}}
Output:
V
Java String compareTo()
The java string 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 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.
Java String compareTo() method example
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//- because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f" }}
Output:
0
-5
-1
2
Java String concat
The java string concat() method combines specified string at the end of this string.
It returns a combined string. It is like appending another string.
Java String concat() method example
public class ConcatExample{
public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}
Output
java string
java string is immutable so assign it explicitly
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string. In
case of substring startIndex is inclusive and endIndex is exclusive.
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 a new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns a new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
String s="hello";
System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because the end index is exclusive).
Example of java substring
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
Output:
Tendulkar
Sachin
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
Output
Sachin
Sachin
Java String startsWith() and endsWith() method
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
Output
true
true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
output
Java String length() method
The string length() method returns length of the string.
String s="Sachin";
System.out.println(s.length());//6
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.
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
output
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
"Kava"
System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
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 string.
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is 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() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int creates an empty string buffer with the specified capacity as
capacity) length.
Important methods of StringBuffer class
Modifier and Method Description
Type
public append(String s) is used to append the specified string with this
synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.
public insert(int offset, is used to insert the specified string with this
synchronized String s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int is used to replace the string from specified
synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex, String
str)
public delete(int is used to delete the string from specified
synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex)
public reverse() is used to reverse the string.
synchronized
StringBuffer
public int capacity() is used to return the current capacity.
public void ensureCapacity(i is used to ensure the capacity at least equal to the
nt given minimum.
minimumCapaci
ty)
public char charAt(int is used to return the character at the specified
index) position.
public int length() is used to return the length of the string i.e. total
number of characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
} }
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as the StringBuffer class except that it is non-synchronized. It is
available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor
Description
StringBuilder() creates an empty string Builder with the initial
capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified
capacity as length.
Important methods of StringBuilder class
Method Description
public StringBuilder is used to append the specified string with this string.
append(String s) The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder is used to insert the specified string with this string at
insert(int offset, String s) the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder is used to replace the string from specified startIndex
replace(int startIndex, int and endIndex.
endIndex, String str)
public StringBuilder is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)
public StringBuilder is used to reverse the string.
reverse()
public int capacity() is used to return the current capacity.
public void is used to ensure the capacity at least equal to the given
ensureCapacity(int minimum.
minimumCapacity)
public char charAt(int is used to return the character at the specified position.
index)
public int length() is used to return the length of the string i.e. total
number of characters.
public String is used to return the substring from the specified
substring(int beginIndex) beginIndex.
public String is used to return the substring from the specified
substring(int beginIndex, beginIndex and endIndex.
int endIndex)
Java StringBuilder Examples
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given
position.
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
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) String class is immutable. StringBuffer class is
mutable.
2) String is slow and consumes more memory StringBuffer is fast and
when you concat too many strings because consumes less memory
every time it creates new instance. when you cancat strings.
3) String class overrides the equals() method of StringBuffer class doesn't
Object class. So you can compare the contents override the equals()
of two strings by equals() method. method of Object class.
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 are given below:
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e.
thread safe. It means two not thread safe. It means two threads
threads can't call the methods of can call the methods of StringBuilder
StringBuffer simultaneously. simultaneously.
2) StringBuffer is less efficient StringBuilder is more efficient than
than StringBuilder. StringBuffer.
StringBuffer Example
//Java Program to demonstrate the use of StringBuffer class.
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
hellojava
StringBuilder Example
//Java Program to demonstrate the use of StringBuilder class.
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
hellojava