Signed in as:
filler@godaddy.com
Signed in as:
filler@godaddy.com
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.
The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length.
Specified by
CharSequence interface, located inside java.lang package.
Let's see Java program related to string in which we will use charAt() method that perform some operation on the give string.
FileName: CharAtExample.java
Test it Now
Output:
t
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:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)
Let's see a simple example where we are accessing first and last character from the provided string.
FileName: CharAtExample3.java
Output:
Character at 0 index is: W
Character at last index is: l
Let's see an example where we are accessing all the elements present at odd index.
FileName: CharAtExample4.java
Output:
ADAD
Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place
Char at 23 place o
Char at 25 place t
Char at 27 place l
The position such as 7 and 21 denotes the space.
Let's see an example in which we are counting frequency of a character in the given string.
FileName: CharAtExample5.java
Output:
Frequency of t is: 4
Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method.
ADAD
FileName: CharAtExample6.java
Output:
String: Javatpoint is a great site for learning Java.
Total number of vowels in the string are: 16
String: One apple in a day keeps doctor away.
Total number of vowels in the string are: 13
=============================================================================
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.
The method accepts a parameter of type String that is to be compared with the current string.
It returns an integer value. It throws the following two exceptions:
ClassCastException: If this object cannot get compared with the specified object.
NullPointerException: If the specified object is null.
FileName: CompareToExample.java
Test it Now
Output:
0
-5
-1
2
When we compare two strings in which either first or second string is empty, the method returns the length of the string. So, there may be two scenarios:
FileName: CompareToExample2.java
Test it Now
Output:
5
-2
To check whether the compareTo() method considers the case sensitiveness of characters or not, we will make the comparison between two strings that contain the same letters in the same sequence.
Suppose, a string having letters in uppercase, and the second string having the letters in lowercase. On comparing these two string, if the outcome is 0, then the compareTo() method does not consider the case sensitiveness of characters; otherwise, the method considers the case sensitiveness of characters.
FileName: CompareToExample3.java
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.
ADAD
The ClassCastException is thrown when objects of incompatible types get compared. In the following example, we are comparing an object of the ArrayList (al) with a string literal ("Sehwag").
FileName: CompareToExample4.java
Output:
Exception in thread "main" java.lang.ClassCastException: class Players cannot be cast to class java.lang.Comparable
The NullPointerException is thrown when a null object invokes the compareTo() method. Observe the following example.
FileName: CompareToExample5.java
ADAD
Output:
Exception in thread "main" java.lang.NullPointerException
at CompareToExample5.main(CompareToExample5.java:9)
=============================================================================
The Java String class concat() method combines specified string at the end of this string. It returns a combined string. It is like appending another string.
The signature of the string concat() method is given below:
anotherString : another string i.e., to be combined at the end of this string.
combined string
FileName: ConcatExample.java
Test it Now
Output:
java string
java string is immutable so assign it explicitly
Let's see an example where we are concatenating multiple string objects.
FileName: ConcatExample2.java
Output:
HelloJavatpoint
HelloJavatpointReader
Let's see an example where we are concatenating spaces and special chars to the string object. It is done using the chaining of the concat() method.
FileName: ConcatExample3.java
Output:
Hello Javatpoint Reader
Hello!!!
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afe7cac3c3c0efe5ced9cedbdfc0c6c1db">[email protected]</a>
Till now, we have seen that the concat() method appends the string at the end of the string that invokes the method. However, we can do a bit of workaround to append the string at the beginning of a string using the concat() method.
FileName: ConcatExample4.java
Output:
India is my Country
===========================================================================
The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false.
The signature of string contains() method is given below:
sequence : specifies the sequence of characters to be searched.
true if the sequence of char value exists, otherwise false.
NullPointerException : if the sequence is null.
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.
FileName: ContainsExample.java
Test it Now
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.
FileName: ContainsExample2.java
Output:
true
false
The contains() method is helpful to find a char-sequence in the string. We can use it in the control structure to produce the search-based result. Let's see an example.
FileName: ContainsExample3.java
Output:
This string contains javatpoint.com
ADAD
The contains() method raises the NullPointerException when one passes null in the parameter of the method. The following example shows the same.
FileName: ContainsExample4.java
AD
Output:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.contains(String.java:2036)
at ContainsExample4.main(ContainsExample4.java:9)
Following are some limitations of the contains() method:
The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false.
The signature of string contains() method is given below:
sequence : specifies the sequence of characters to be searched.
true if the sequence of char value exists, otherwise false.
NullPointerException : if the sequence is null.
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.
FileName: ContainsExample.java
Test it Now
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.
FileName: ContainsExample2.java
Output:
true
false
The contains() method is helpful to find a char-sequence in the string. We can use it in the control structure to produce the search-based result. Let's see an example.
FileName: ContainsExample3.java
Output:
This string contains javatpoint.com
ADAD
The contains() method raises the NullPointerException when one passes null in the parameter of the method. The following example shows the same.
FileName: ContainsExample4.java
AD
Output:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.contains(String.java:2036)
at ContainsExample4.main(ContainsExample4.java:9)
Following are some limitations of the contains() method:
============================================================================
The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false.
The syntax or signature of endsWith() method is given below.
suffix : Sequence of character
true or false
The internal implementation shows that the endWith() method is dependent on the startsWith() method of the String class.
FileName: EndsWithExample.java
Test it Now
Output:
true
true
Since the endsWith() method returns a boolean value, the method can also be used in an if statement. Observe the following program.
FileName: EndsWithExample2.java
Output:
false
String ends with .com
The endsWith() method takes care of the case sensitiveness of the characters present in a string. The following program shows the same.
FileName: EndsWithExample3.java
Output:
false
false
true
ADAD
When an empty string is passed in the parameter of the method endsWith(), the method always returns a true value. The reason behind this is that a string never changes when we append an empty string to it. For example,
The statement
results in
str = "Ladies and Gentlemen";
ADAD
Thus, we can say that any string in Java ends with an empty string (""). Observe the
FileName: EndsWithExample4.java
Output:
true
false
The endsWith() method raises the NullPointerException if one passes null in the parameter of the method. The following example shows the same.
FileName: EndsWithExample5.java
ADAD
Output:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.endsWith(String.java:1485)
at EndsWithExample5.main(EndsWithExample5.java:9)
A String literal can also call the endsWith() method. The following program shows the same.
FileName: EndsWithExample6.java
Output:
Inside the if block
Inside the if block
Inside the else block
=============================================================================
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
The String equals() method overrides the equals() method of the Object class.
anotherObject : another object, i.e., compared with this string.
true if characters of both strings are equal otherwise false.
FileName: EqualsExample.java
Test it Now
Output:
true
false
false
The equals() method compares two strings and can be used in if-else control structure.
FileName: EqualsExample2.java
Output:
true
both strings are unequal
Let's see one more example to test the equality of string present in the list.
FileName: EqualsExample3.java
Output:
Mukesh is present
ADAD
The internal implementation of the equals() method shows that one can pass the reference of any object in the parameter of the method. The following example shows the same.
FileName: EqualsExample4.java
Output:
false
false
false
false
true
true
true
true
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
The String equals() method overrides the equals() method of the Object class.
Signature
publicboolean equals(Object anotherObject)
Parameter
anotherObject : another object, i.e., compared with this string.
Returns
true if characters of both strings are equal otherwise false.
Internal implementation
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Java String equals() Method Example
FileName: EqualsExample.java
public class EqualsExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
Test it Now
Output:
true
false
false
Java String equals() Method Example 2
The equals() method compares two strings and can be used in if-else control structure.
FileName: EqualsExample2.java
public class EqualsExample2 {
public static void main(String[] args) {
String s1 = "javatpoint";
String s2 = "javatpoint";
String s3 = "Javatpoint";
System.out.println(s1.equals(s2)); // True because content is same
if (s1.equals(s3)) {
System.out.println("both strings are equal");
}else System.out.println("both strings are unequal");
}
}
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
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");
}
}
}
}
Output:
Mukesh is present
AD
AD
Java String equals() Method Example 4
The internal implementation of the equals() method shows that one can pass the reference of any object in the parameter of the method. The following example shows the same.
FileName: EqualsExample4.java
public class EqualsExample4
{
// main method
public static void main(String argvs[])
{
// Strings
String str = "a";
String str1 = "123";
String str2 = "45.89";
String str3 = "false";
Character c = new Character('a');
Integer i = new Integer(123);
Float f = new Float(45.89);
Boolean b = new Boolean(false);
// reference of the Character object is passed
System.out.println(str.equals(c));
// reference of the Integer object is passed
System.out.println(str1.equals(i));
// reference of the Float object is passed
System.out.println(str2.equals(f));
// reference of the Boolean object is passed
System.out.println(str3.equals(b));
// the above print statements show a false value because
// we are comparing a String with different data types
// To achieve the true value, we have to convert
// the different data types into the string using the toString() method
System.out.println(str.equals(c.toString()));
System.out.println(str1.equals(i.toString()));
System.out.println(str2.equals(f.toString()));
System.out.println(str3.equals(b.toString()));
}
}
Output:
false
false
false
false
true
true
true
true
============================================================================
The Java String class equalsIgnoreCase() method compares the two given strings on the basis of the content of the string irrespective of the case (lower and upper) of the string. It is just like the equals() method but doesn't check the case sensitivity. If any character is not matched, it returns false, else returns true.
str : another string i.e., compared with this string.
It returns true if characters of both strings are equal, ignoring case otherwise false.
It is obvious from looking at the implementation that the equalsIgnoreCase() method is invoking the regionMatches() method. It makes the equalsIgnoreCase() method case-insensitive. The signature of the regionMatches() method is mentioned below.
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
The regionMatches() method parses five parameters. The first parameter ignoreCase is set to true in the above implementation. Thus, when the method is executed, it checks whether the ignoreCase flag is true or not. If yes, then one character each from both the strings is taken and then compared. If the comparison gives a false value, then both the character is converted to upper case and then checked if the comparison still gives a false value, then both the characters are converted to a lower case and then compared. If the comparison gives the true value, then both the strings have equal contents; otherwise, not. Code Snippet of the discussed comparison is mentioned below.
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.
FileName: EqualsIgnoreCaseExample.java
Test it Now
Output:
true
true
false
Let's see an example where we are testing string equality among the strings.
FileName: EqualsIgnoreCaseExample2.java
Output:
Mukesh kumar is present
============================================================================
The java string format() method returns the formatted string by given locale, format and arguments.
If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.
The format() method of java language is like sprintf() function in c language and printf() method of java language.
There are two type of string format() method:
locale : specifies the locale to be applied on the format() method.
format : format of the string.
args : arguments for the format string. It may be zero or more.
formatted string
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.
Test it Now
name is sonoo
value is 32.334340
value is 32.334340000000
Here, we are providing a table of format specifiers supported by the Java String.
%a floating point (except BigDecimal) : Returns Hex output of floating point number.
%b Any type : "true" if non-null, "false" if null .
%c character : Unicode character.
%d integer (incl. byte, short, int, long, bigint) : Decimal Integer.
%e floating point : decimal number in scientific notation
%f floating point : decimal number
%g floating point : decimal number, possibly in scientific notation depending on the precision and value.
%h any type : Hex String of value from hashCode() method.
%n none : Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) : Octal number.
% sany typeString value .
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) : %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint): Hex string.
This method supports various data types and formats them into a string type. Let us see an example.
Test it Now
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.
Test it Now
101
| 101|
|101 |
| 101|
|0000000101|
=============================================================================
The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes.
There are three variants of getBytes() method. The signature or syntax of string getBytes() method is given below:
charset / charsetName - The name of a charset the method supports.
Sequence of bytes.
UnsupportedEncodingException: It is thrown when the mentioned charset is not supported by the method.
The parameterless getBytes() method encodes the string using the default charset of the platform, which is UTF - 8. The following two examples show the same.
FileName: StringGetBytesExample.java
Test it Now
Output:
65
66
67
68
69
70
71
FileName: StringGetBytesExample2.java
The method returns a byte array that again can be passed to the String constructor to get String.
Test it Now
Output:
65
66
67
68
69
70
71
ABCDEFG
The following example shows the encoding into a different charset.
FileName: StringGetBytesExample3.java
Output:
The input String is :
Welcome to JavaTpoint.
After converted into UTF-16 the String is :
-2-10870101010809901110109010103201160111032074097011809708401120111010501100116046
After converted into UTF-16BE the String is :
0870101010809901110109010103201160111032074097011809708401120111010501100116046
After converted into ISO-8859-1 the String is :
871011089911110910132116111327497118978411211110511011646
After converted into UTF-16LE the String is :
8701010108099011101090101032011601110320740970118097084011201110105011001160460
ADAD
The following example shows when the charset is not supported by the getBytes() method, UnsupportedEncodingException is thrown.
FileName: StringGetBytesExample4.java
Output:
ADAD
/StringGetBytesExample4.java:11: error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
byte[] byteArr = str.getBytes("UTF-17");
^
1 error
============================================================================
The Java String class getChars() method copies the content of this string into a specified char array. There are four arguments passed in the getChars() method. The signature of the getChars() method is given below:
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() method is getting copied.
int dstEndIndex: It shows the position in the destination array from where the characters from the string will be pushed.
It doesn't return any value.
The method throws StringIndexOutOfBoundsException when any one or more than one of the following conditions holds true.
The signature or syntax of string getChars() method is given below:
FileName: StringGetCharsExample.java
Test it Now
Output:
javatpoint
The method throws an exception if index value exceeds array range. Let's see an example.
FileName: StringGetCharsExample2.java
Output:
java.lang.StringIndexOutOfBoundsException: offset 10, count 14, length 20
The getChars() method does not copy anything into the char array, provided the value of srcBeginIndex and srcEndIndex are the same. It is because the getChars() method copies from the srcBeginIndex index to srcEndIndex - 1 index. As srcBeginIndex is equal to srcEndIndex; therefore, srcEndIndex - 1 is less than srcBeginIndex. Therefore, the getChars() method copies nothing. The following example confirms the same.
FileName: StringGetCharsExample3.java
Output:
The getChars() method prints nothing as start and end indices are equal.
============================================================================
The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
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 from index.
3) int indexOf(String substring) : It returns the index position for the given substring.
4) int indexOf(String substring, int fromIndex) : It returns the index position for the given substring and from index.
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Index of the searched string or character.
Internal Implementation
FileName: IndexOfExample.java
Test it Now
Output:
2 8
5
3
We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example.
FileName: IndexOfExample5.java
Output:
In the String: Welcome to JavaTpoint
The 'o' character has come 3 times
The method takes substring as an argument and returns the index of the first character of the substring.
FileName: IndexOfExample2.java
Test it Now
Output:
index of substring 16
The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample3.java
ADAD
Test it Now
Output:
index of substring 16
index of substring -1
ADAD
The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex.
FileName: IndexOfExample4.java
Test it Now
Output:
index of char 17
=============================================================================
The Java String class intern() method returns the interned string. It returns the canonical representation of string.
It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.
The signature of the intern() method is given below:
interned string
When a string is created in Java, it occupies memory in the heap. Also, we know that the String class is immutable. Therefore, whenever we create a string using the new keyword, new memory is allocated in the heap for corresponding string, which is irrespective of the content of the array. Consider the following code snippet.
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.
FileName: InternExample.java
Test it Now
Output:
false
true
Let's see one more example to understand the string intern concept.
FileName: InternExample2.java
Test it Now
Output:
true
false
true
false
true
false
ADAD
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,
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.
ADAD
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.