For example I have one String="something" now if I will access the last index(str.length()) of this string it will give "String index out of range: -1". But If I access this through Substring it does not give any error.
String str="something" str.charAt(9); Run time Error || Str.substring(9); No error and it will not print anything.
Please Help
The String#substring
documentation mentions (emphasis mine) it clearly
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this
String
object .
Index will start from 0 and ends at length-1
.
In order to access the last character, you have to call the charAt function with length-1.
String str = "something";
str.charAt(str.length() - 1);
this will give g
as result.
Please check the documentation of both the methods you will get an idea. Both of your use cases are mentioned in the exception section. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int) https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.