String Class Methods
String Class Methods
In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:
char[] ch = {'j','a','v','a','t','p','o','i','n','t'};
String s = new String(ch);
is same as:
String s = "javatpoint";
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
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.
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
a. String s = “welcome”;
Note: String objects are stored in a special memory area known as the ”string constant pool”.
2. By new Keyword
Example:
No Method Description
1 char charAt(int index) returns char value for the particular index
4 static String format(Locale l, String format, Object... returns formatted string with given locale.
args)
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.
13 String replace(char old, char new) replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence replaces all occurrences of the specified CharSequence.
new)
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
17 String[] split(String regex, int limit) returns a split string matching regex and limit.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with
given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given
index.
23 String toLowerCase() returns a string in lowercase.
28 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.
Output:
Let's see the example of charAt() method where we are passing greater index value. In such case, it throws
StringIndexOutOfBoundsException at run time.
Output:
Let's see a simple example where we are accessing first and last character from the provided string.
Output:
Let's see an example where we are accessing all the elements present at odd index.
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
Let's see an example where we are counting frequency of a character in the string.
Output:
Frequency of t is: 4
Java String compareTo()
The java string compareTo() method compares the given string with current string lexicographically. It
returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive number (difference of
character value). If first string is less than second string lexicographically, it returns negative number and
if first string is lexicographically equal to second string, it returns 0.
Output:
0
-5
-1
2
If you compare string with blank or empty string, it returns length of the string. If second string is empty,
result would be positive. If first string is empty, result would be negative.
java string
java string is immutable so assign it explicitly
Output:
HelloJavatpoint
HelloJavatpointReader
Let's see an example where we are concatenating spaces and special chars to the string object.
Output:
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
Output
true
true
false
The contains() method searches case sensitive char sequence. If the argument is not case sensitive, it
returns false. Let's see an example below.
The contains() method is helpful to find a char-sequence in the string. We can use it in control structure to
produce search based result. Let us see an example below.
Output:
true
true
Output:
false
String ends with .com
Java String equals()
The java string equals() method compares the two given strings based on the content of the string. If
any character is not matched, it returns false. If all characters are matched, it returns true.
The String equals() method overrides the equals() method of Object class.
import java.util.ArrayList;
public class EqualsExample3 {
public static void main(String[] args) {
String str1 = "Mukesh";
ArrayList<String> list = new ArrayList<>();
list.add("Ravi");
list.add("Mukesh");
list.add("Ramesh");
list.add("Ajay");
for (String str : list) {
if (str.equals(str1)) {
System.out.println("Mukesh is present");
}
}
}
}
Mukesh is present
Java String equalsIgnoreCase()
The String equalsIgnoreCase() method compares the two given strings on the basis of content of the
string irrespective of case of the string. It is like equals() method but doesn't check case. If any character
is not matched, it returns false otherwise it returns true
Let's see an example where we are testing string equality among the strings.
import java.util.ArrayList;
public class EqualsIgnoreCaseExample2 {
public static void main(String[] args) {
String str1 = "Mukesh Kumar";
ArrayList<String> list = new ArrayList<>();
list.add("Mohan");
list.add("Mukesh");
list.add("RAVI");
list.add("MuKesH kuMar");
list.add("Suresh");
for (String str : list) {
if (str.equalsIgnoreCase(str1)) {
System.out.println("Mukesh kumar is present");
}
}
}
}
Output:
If you don't specify the locale in String.format() method, it uses default locale by
calling Locale.getDefault() method.
The format() method of java language is like sprintf() function in c language and printf() method of java
language.
System.out.println(sf1);
System.out.println(sf2);
System.out.println(sf3);
}}
Output
name is sonoo
value is 32.334340
value is 32.334340000000
This method supports various data types and formats them into a string type. Let us see an example.
}
Output
101
Amar Singh
101.000000
65
c
Apart from formatting, we can set width, padding etc. of any value. Let us see an example where we are
setting width and padding for an integer value.
Signature
There are 3 variant of getBytes() method. The signature or syntax of string getBytes() method is given
below:
Output:
65
66
67
68
69
70
71
This method returns a byte array that again can be passed to String constructor to get String.
Signature =
public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)
Returns = It doesn't return any value.
Throws = It throws StringIndexOutOfBoundsException if beginIndex is greater than endIndex
Output:
javatpoint
It throws an exception if index value exceeds array range. Let's see an example.
Output:
Signature
There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value and
from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int returns index position for the given substring and
fromIndex) from index
Parameters
fromIndex: index position from where index of the char value or substring is retured
Returns
This method takes substring as an argument and returns index of first character of the substring.
}
Output
index of substring 16
This method takes substring and index as arguments and returns index of first character occured after the
given fromIndex.
This method takes char and index as arguments and returns index of first character occured after the
given fromIndex.
The isEmpty() method of String class is included in java string since JDK 1.6.
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}
Output
true
false
In case of null element, "null" is added. The join() method is included in java string since JDK 1.8.
Signature
1.8
We can use delimeter to format the string as we did in the below example to show date and time.
Signature
There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods are given below:
1 int lastIndexOf(int ch) returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex) returns last index position for the given char value and from
index
3 int lastIndexOf(String substring) returns last index position for the given substring
4 int lastIndexOf(String substring, int returns last index position for the given substring and from
fromIndex) index
Parameters
fromIndex: index position from where index of the char value or substring is retured
Output:
Here, we are finding last index from the string by specifying fromIndex
Output:
3
Java String lastIndexOf(String substring) Method Example
Output:
19
Output:
19
-1
Java String length()
The java string length() method length of the string. It returns count of total number of characters. The
length of java string is same as the unicode code units of the string.
Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char values.
Signature
Parameters
Let's see an example to replace all the occurrences of single word or set of words.
Signature
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching regex.
The given example returns total number of words in a string excluding space only. It also includes special
characters.
}}
Output
returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world
Here, we are passing split limit as a second argument to this function. This limits the number of splitted
strings.
Output:
true
true
This is overloaded method of startWith() method which is used to pass one extra argument (offset) to the
function. This method works from the passed offset. Let's see an example.
Output:
true
false
true
Java String substring()
The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where start index is
inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts
from 1.
Signature
public String substring(int startIndex)
and
public String substring(int startIndex, int endIndex)
If you don't specify endIndex, java substring() method will return all the characters from startIndex.
Parameters
startIndex : starting index is inclusive
Output:
va
vatpoint
Output:
hello
Let's see one more example of char array. It is useful method which returns char array from the string without
writing any custom code.
Output:
z
u
p
Java String toLowerCase()
The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all
characters of the string into lower case letter.
The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default
locale.
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.
Output:
This method allows us to pass locale too for the various langauges. Let's see an example below where we are getting
string in english and turkish both.
import java.util.Locale;
public class StringLowerExample2 {
public static void main(String[] args) {
String s = "JAVATPOINT HELLO stRIng";
String eng = s.toLowerCase(Locale.ENGLISH);
System.out.println(eng);
String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot
System.out.println(turkish);
}
}
Output:
The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It internally uses the default
locale.
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase() method is given
below:
The second method variant of toUpperCase(), converts all the characters into uppercase using the rules of given
Locale.
Output:
HELLO STRING
import java.util.Locale;
public class StringUpperExample2 {
public static void main(String[] args) {
String s = "hello string";
String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
String english = s.toUpperCase(Locale.forLanguageTag("en"));
System.out.println(turkish);//will print I with dot on upper side
System.out.println(english);
}
}
Output:
HELLO STR?NG
HELLO STRING
Java String trim()
The java string 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
removes the spaces and returns the omitted string.
This example demonstrate the use of trim method. This method removes all the trailing spaces so the length of string
also reduces. Let's see an example.
Returns
Let's see an example where we are converting all primitives and objects into strings.
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55