Reputation: 115
I'm trying to use substring function in java, but it keeps throwing an error, I want to know why ? the code seems to be good logically speaking but why it is throwing this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
What I've read in the documentation substring takes 2 parameter
substring(whereIwantToStart,howManyCharactersToshow)
below is my code
String test = "160994";
System.out.println(test.substring(2,1)); //output should be 09 why error?
Can someone explain me what is wrong ? please I need explanation. Thanks :)
Upvotes: 0
Views: 4896
Reputation: 49
String test = "160994";
System.out.println(test.substring(2,1));
Substring means (beginIndex, endIndex) and endIndex Should be larger than beginIndex.and your value(09) should be stay between beninIndex(which is starting index) and endIndex(Which is last index).
and you have taken endIndex 1 so you are geting the Error because your beginIndex is larger than endIndex.
if you want to get Ans. 09 then you should have to put endIndex 4.
Line will be:-System.out.println(test.substring(2,4));
Upvotes: 0
Reputation: 641
public String substring(int startIndex, int endIndex)
: This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
Let's understand the startIndex and endIndex by the code given below.
String s="hello";
System.out.println(s.substring(0,2));
Output : he
Notice :
endIndex > startIndex
in your case : change between 1 and 2 place to
String test = "160994";
System.out.println(test.substring(2, 4)); //output should be 09
Output : 09
Upvotes: 0
Reputation: 3001
For your required output use-
System.out.println(test.substring(2,4));
Upvotes: 1
Reputation: 1727
This is the format for the substring in java
public String substring(int beginIndex, int endIndex)
you are specifying start from index 2 and end at index 1 , that's why it's throwing an exception index out of range.
To get the output as 09 you need
System.out.println(test.substring(2,4));
Appendix - Java Docs https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
Upvotes: 0
Reputation: 413
End index should be greater than the Start Index. To get output as '09', you should provide the end index as 4 test.substring(2,4);
Returns a new string that is a substring of this string. The
substring begins at the specifiedbeginIndex
and extends to the character at indexendIndex - 1
.Thus the length of the substring is
endIndex-beginIndex
.
The StringIndexOutOfBoundsException
will throw in below cases
Upvotes: 1
Reputation: 28269
See the doc:
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
You need "160994".substring(2, 4)
to get 09
.
Upvotes: 3