![]() |
VOOZH | about |
In Java, the charAt() method of the String class is used to extract the character from a string. It returns the character at the specified index in the String. The substring() method is used to extract some portion from the actual String and the actual string remains the same as it is. After that, the method returns a new string.
In this article, we will learn charAt() vs substring() methods in Java.
The charAt() method returns characters at the specific index in a String. The indexing starts from 0 i.e. the first character's index is 0 then 1 and so on. But the index of the last character is length() - 1.
char charAt(int index)Let us understand this method by implementing a simple example below. If we want to get the character at a specific position in a string:
p i
The substring() method is used to extract some portion from the actual String and the actual string remains the same. This method returns a new string. We can say this a subset of a String. There are two variants in subString() method:
String.substring(int index)
String.substring(int start index, int end Index)
Pawan Deep ep
s.substring(5) prints a substring starts from index 5 to the end of the string.s.substring(0,4) prints a substring starts from index 0 to index 4.s.substring(2,4) prints a substring starts from index 2 to index 4.charAt() method | substring() method |
|---|---|
It extracts a single character at a specified index. | It extracts some portion of a string based on indexes. |
Its return type is char. | Its return type is String. |
It returns only a single character. | It can return a sequence of characters i.e. , substring. |
Example: String str = "Deep"; | Example: String str = "Deep"; |