Signed in as:
filler@godaddy.com
Signed in as:
filler@godaddy.com
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
is same as:
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.
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.
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.
There are two ways to create String object:
Java String literal is created by using double quotes. For Example:
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:
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.
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
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).
StringExample.java
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.
ADAD
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
1 char charAt(int index) : It returns char value for the particular index
2 int length() : It returns string length
3 static String format(String format, Object... args) : It returns a formatted string.
4 static String format(Locale l, String format, Object... args) : It returns formatted string with given locale.
5 String substring(int beginIndex) : It returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) : It returns substring for given begin index and end index.
7 boolean contains(CharSequence s) : It returns true or false after matching the sequence of char value.
8 static String join(CharSequence delimiter, CharSequence... elements) : It returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) : It returns a joined string.
10 boolean equals(Object another) : It checks the equality of string with the given object.
11 boolean isEmpty() : It checks if string is empty.
12 String concat(String str) : It concatenates the specified string.
13 String replace(char old, char new) : It replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) : It replaces all occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) : It compares another string. It doesn't check case.
16 String[] split(String regex) : It returns a split string matching regex.
17 String[] split(String regex, int limit) : It returns a split string matching regex and limit.
18 String intern() : It returns an interned string.
19 int indexOf(int ch) : It returns the specified char value index.
20 int indexOf(int ch, int fromIndex) : It returns the specified char value index starting with given index.
21 int indexOf(String substring) : It returns the specified substring index.
22 int indexOf(String substring, int fromIndex) : It returns the specified substring index starting with given index.
23 String toLowerCase() : It returns a string in lowercase.
24 String toLowerCase(Locale l) : It returns a string in lowercase using specified locale.
25 String toUpperCase() : It returns a string in uppercase.
26 String toUpperCase(Locale l) : It returns a string in uppercase using specified locale.
27 String trim() : It removes beginning and ending spaces of this string.
28 static String valueOf(int value) : It converts given type into string. It is an overloaded method.
==============================================================================
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
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
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.
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.
AD
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:
AD
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.
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.
=============================================================================
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:
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:
Teststringcomparison1.java
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
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.
The == operator compares references not values.
Teststringcomparison3.java
Test it Now
Output:
true
false
The above code, demonstrates the use of == operator used for comparing two String objects.
AD
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:
ADAD
Teststringcomparison4.java
AD
Test it Now
Output:
0
1
-1
==============================================================================
In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java:
Java String concatenation operator (+) is used to add strings. For Example:
TestStringConcatenation1.java
Test it Now
Output:
Sachin Tendulkar
The Java compiler transforms above code to this:
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
Test it Now
Output:
80Sachin4040
The String concat() method concatenates the specified string to the end of current string. Syntax:
Let's see the example of String concat() method.
TestStringConcatenation3.java
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,
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
Output:
ADAD
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.
String.format() method allows to concatenate multiple strings using format specifier like %s followed by the string values or objects.
StrFormat.java
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.
ADAD
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:
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.
StringJoiner class has all the functionalities of String.join() method. In advance its constructor can also accept optional arguments, prefix and suffix.
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.
The Collectors class in Java 8 offers joining() method that concatenates the input elements in a similar order as they occur.
ColJoining.java
Output:
abc, pqr, xyz
Here, a list of String array is declared. And a String object str stores the result of Collectors.joining() method.
==============================================================================
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:
Let's understand the startIndex and endIndex by the code given below.
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end index is exclusive).
TestSubstring.java
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.
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
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.
=============================================================================
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.
The Java String toUpperCase() method converts this String into uppercase letter and String toLowerCase() method into lowercase letter.
Stringoperation1.java
Test it Now
Output:
SACHIN
sachin
Sachin
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
Test it Now
Output:
Sachin
Sachin
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
Test it Now
Output:
true
true
The String class charAt() method returns a character at specified index.
Stringoperation4.java
Test it Now
Output:
S
h
The String class length() method returns length of the specified String.
Stringoperation5.java
ADAD
Test it Now
Output:
6
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
Test it Now
Output:
ADAD
Sachin
The String class valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into String.
Stringoperation7.java
Output:
1010
The String class replace() method replaces all occurrence of first sequence of character with second sequence of character.
Stringoperation8.java
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
=============================================================================
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.
ConstructorDescriptionStringBuffer() : 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.
public synchronized StringBufferappend(String s) : It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBufferinsert(int offset, String s) : It is used to insert the specified string with this string at 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 synchronized StringBufferreplace(int startIndex, int endIndex, String str) : It is used to replace the string from specified startIndex and endIndex.
public synchronized StringBufferdelete(int startIndex, int endIndex) : It is used to delete the string from specified startIndex and endIndex.
public synchronized StringBufferreverse() : is used to reverse the string.
public intcapacity() : It is used to return the current capacity.
public voidensureCapacity(int minimumCapacity) : It is used to ensure the capacity at least equal to the given minimum.
public charcharAt(int index) : It is used to return the character at the specified position.
public intlength() : It is used to return the length of the string i.e. total number of characters.
public Stringsubstring(int beginIndex) : It is used to return the substring from the specified beginIndex.
public Stringsubstring(int beginIndex, int endIndex) : It is used to return the substring from the specified beginIndex and endIndex.
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
StringBufferExample.java
Output:
Hello Java
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
Output:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.
StringBufferExample4.java
Output:
Hlo
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
Output:
ADAD
olleH
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
Output:
16
16
34
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
ADAD
Output:
16
16
34
34
70
=============================================================================
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.
ConstructorDescriptionStringBuilder() : 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.
public StringBuilder append(String s) : It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s) : It is used to insert the specified string with this string at 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 replace(int startIndex, int endIndex, String str) : It is used to replace the string from specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) : It is used to delete the string from specified startIndex and 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 minimumCapacity) : It is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) : It is used to return the character at the specified position.
public int length() : It is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) : It is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) : It is used to return the substring from the specified beginIndex and endIndex.
Let's see the examples of different methods of StringBuilder class.
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java
Output:
Hello Java
The StringBuilder insert() method inserts the given string with this string at the given position.
StringBuilderExample2.java
Output:
HJavaello
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
StringBuilderExample3.java
Output:
HJavalo
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
StringBuilderExample4.java
Output:
Hlo
The reverse() method of StringBuilder class reverses the current string.
StringBuilderExample5.java
Output:
ADAD
olleH
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
Output:
16
16
34
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
ADAD
Output:
16
16
34
34
70
=============================================================================
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
String
1) The String class is immutable.
2)String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance.
3)String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
4)String class is slower while performing concatenation operation.
5)String class uses String constant pool.
StringBuffer
1) The StringBuffer class is mutable.
2) StringBuffer is fast and consumes less memory when we concatenate t strings.
3) StringBuffer class doesn't override the equals() method of Object class.
4) StringBuffer class is faster while performing concatenation operation.
5) StringBuffer uses Heap memory .
ConcatTest.java
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.
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
Output:
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462
=============================================================================
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:
StringBuffer
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
2) StringBuffer is less efficient than StringBuilder.
3) StringBuffer was introduced in Java 1.0.
StringBuilder
1) StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuilder is more efficient than StringBuffer.
3) StringBuilder was introduced in Java 1.5 .
BufferTest.java
Output:
hellojava
BuilderTest.java
Output:
hellojava
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
ConcatTest.java
Output:
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
=============================================================================
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:
In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.
ImmutableDemo.java
Output:
Pancard Number: ABC123
The above class is immutable because:
These points makes this class as immutable.
=============================================================================
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.
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.
Let's see the simple code that prints reference.
Student.java
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:
Let's see an example of toString() method.
Student.java
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.
=============================================================================
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.
There are 3 constructors defined in the StringTokenizer class.
ConstructorDescriptionStringTokenizer(String str)It creates StringTokenizer with specified string.StringTokenizer(String str, String delim)It creates StringTokenizer with specified string and delimiter.StringTokenizer(String str, String delim, boolean returnValue)It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.
The six useful methods of the StringTokenizer class are as follows:
MethodsDescriptionboolean 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.
Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.
Simple.java
Output:
my
name
is
khan
The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken().
Test.java
Output:
Next token is : my
This method returns true if more tokens are available in the tokenizer String otherwise returns false.
StringTokenizer1.java
Output:
Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and nextToken() of 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
ADAD
Output:
Hello
everyone
I
am
a
Java
developer
The above code demonstrates the use of hasMoreElements() method.
nextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface.
StringTokenizer3.java
Output:
ADAD
Hello
Everyone
Have
a
nice
day
The above code demonstrates the use of nextElement() method.
This method calculates the number of tokens present in the tokenizer String.
StringTokenizer4.java
Output:
Total number of Tokens: 6
The above Java code demonstrates the countTokens() method of StringTokenizer() class.
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.