java substring not working as expected - java

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 :)

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.

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 specified beginIndex and extends
to the character at index endIndex - 1.
Thus the length of the substring is endIndex-beginIndex.
The StringIndexOutOfBoundsException will throw in below cases
beginIndex < 0
endIndex > value.length
endIndex - beginIndex < 0

For your required output use-
System.out.println(test.substring(2,4));

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)

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

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));

Related

Substring of a string java

Below is a String and I want to get the bold id from it.
String s = "> Index1 is: 261 String is: href: https://www.clover.com/v3/merchants/4B8BF3Y5NJH7P/orders/K0AH5696MRG6J?access_token=4ffcfacefd3b2e9611a448da68fff91f, id: **K0AH5696MRG6J**, currency: USD, title: Greta , note: This is test ,";
int ind = s.indexOf("id:");
s = s.substring(ind,s.indexOf(","));
It gives an error index out of bound.
I know that error is there because in substring(int,int) the second parameter value is not correct.
I am trying to get the substring between id: and ,.
Any help
You are getting an IndexOutOfBoundsException because substring found that end index was less than the begin index.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Your initial indexOf call finds the id: properly, but the call to s.indexOf(",") finds the first , in the string, which happens to be before id:.
Use an overload of indexOf that takes a second argument - the index at which to starting looking.
s = s.substring(ind,s.indexOf(",", ind));
I suggest you use
s.indexOf(",", ind)
to get the comma which is after the id: rather than the first one in the String.
If you haven't read all the methods in String yet, I suggest you do as you will be using this class again, and again.
your "," index is before your "id:" index. You must search , after id
// Search id:
int ind = s.indexOf("id:");
// After that: search comma
int comma = s.indexOf(",", ind +1);
this explains this sort of problems:
How to use substring and indexOf for a String with repeating characters?

Why is this not a run time error

substring returns a string starting with the specified index number all the way to the end.
Can you tell me why the following is not a run time error?
String s = "Hello";
s.substring(5);
The length of the string is 5 but the last index is 4 so why do I not get an exception for range? I get one when I say s.substring(6);
Please help!
s.substring() doesn't actually throw a method if you call an index 1 above the last index. This is very helpful, because then you don't need to worry with forloops like this:
for(int i = 0; i < string.length - 1; i++) {
System.out.println(s.substring(i, i+1));
}
No need to have a special check for the very last index, it'll just work.
You can see the Java Docs for the more technical answer - s.substring() will only throw an error if the index is greater than the LENGTH of the string, not just the number of indices.
See this question for more info too.
From the documentation:
Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
5 is equal to the length of "Hello", so it's permitted.
The reason why it does not throw an exception is because in the two parameter version:
substring(int beginIndex, int endIndex)
endIndex is exclusive. When the single parameter version you're using specifies the length of the string, the behavior is consistent with the two parameter version, so its treated as exclusive. The result is an empty string.
The actual implementation of the single parameter version is:
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
For reference, the actual implementation of the two parameter version is:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count))
? this
: new String(offset + beginIndex, endIndex - beginIndex, value);
}
This is expected behaviour, API gives a similar example:
"emptiness".substring(9) returns "" (an empty string)

String index out of range: -2

For the following program am getting exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1911)
at Names.main(Names.java:33)
for line
System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
Do you see any problem in this line?
/* Names.java */
import java.io.*;
public class Names {
/** Performs various string operations on the name John Fitzgerald kennedy.
*
* #param arg is not used
*/
public static void main(String[] args) {
String first = "john";
String middle = "Fitzgerald";
String last = "Kennedy";
String initials;
String firstInit, middleInit, lastInit;
firstInit = first.substring(0, 1);
middleInit = middle.substring(0,1);
lastInit = last.substring(0,1);
initials = firstInit.concat(middleInit);
initials = initials.concat(lastInit);
System.out.println();
System.out.println(first+" "+middle+" "+last+" ");
System.out.println(initials);
System.out.println(last+", "+first+" "+middle);
System.out.println(last+", "+first+" "+middleInit+".");
System.out.println(first.toUpperCase()+" "+last.toUpperCase());
System.out.println(first+" equals john is "+first.equals("john"));
System.out.println(first+" equals john (ignoring case is) "+first.equalsIgnoreCase("john"));
System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
System.out.println("The index of \"gerald\" within "+middle+" is "+middle.indexOf("gerald"));
System.out.println("The index of \"gerald\" within "+last+" is "+last.indexOf("gerald"));
System.out.println();
}
}
This isn't going to work:
middle.substring(3, 1)
You can't have an end value larger than your start value for String#substring():
Throws IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Since you only want the character at index 3, use charAt() instead:
middle.charAt(3);
Or, using substring with a narrower range:
middle.substring(3, 4);
You have to pass (start, end) parameters to substring:
middle.substring(3, 4) // '4' since you just want one char
Remember that substring() won't return the char at index 4.
Note:
A simpler way to do this would be using charAt(index):
middle.charAt(3)
The method signature is
public String substring(int beginIndex, int endIndex)
So if you intend to take one character, you should use
middle.substring(3, 4);
From this documentation by oracle, it is clear that subString() method will throw IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
middle.substring(from index , to index) what your doing here middle.substring(3, 1) while using substring to index greater than from index
Study String Manipulation in Java

Why is substring() function in returning a value when it should be returning an overflow message

I am trying to solve a problem which goes like this:-
Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2.
left2("Hello") → "lloHe"
left2("java") → "vaja"
left2("Hi") → "Hi"
I have written two functions for this:-
public String left2(String str)
{
String str1 = str;
if(str.length()>2)
str1 = str.substring(2)+str.substring(0,2);
return str1;
}
public String left2(String str)
{
return str.substring(2)+str.substring(0,2);
}
Both of the functions are correct. I wanted to know that if the first parameter of substring() function is an index, then am I not getting an overflow error in the second function? I am asking this because Java doesn't end in a NULL character so I think there be an error in the second function.
That's because your Substring logic works only if the text length is greater than 2. See here:
if(str.length()>2)
str1 = str.substring(2)+str.substring(0,2);
This is the source code for substring method in java:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
From experience, documentation may lie, but code doesn't. StringIndexOutOfBoundsException is thrown only if
a. beginIndex is less than 0(that is, is negative) or
b. endIndex is greater than count or
c. beginIndex is greater than endIndex.
The reason the second function
return str.substring(2)+str.substring(0,2);
works is that you never tried passing a string that is shorter than two characters. If you did, you would have received an exception (demo).
The reason this works when you pass a string of two characters is that the index that you pass is allowed to be equal to the length of the string (in this case, 2). When you pass an index that equals the length of the string to substring that takes one parameter, you get an empty string. When you pass an index that equals the length of the string to two-parameter substring, it takes the string up to and including the last character.

substring index range

Code:
public class Test {
public static void main(String[] args) {
String str = "University";
System.out.println(str.substring(4, 7));
}
}
Output: ers
I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e is at index 4 but char i is at 7 so the output would be ersi.
0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
Javadoc link
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.
To make life easier for substring operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
↑ ↑
start end --> range of "E R S"
Quoting the docs:
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.
See the javadoc. It's an inclusive index for the first argument and exclusive for the second.
Like you I didn't find it came naturally. I normally still have to remind myself that
the length of the returned string is
lastIndex - firstIndex
that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception
so
"University".substring(6, 10)
returns the 4-character string "sity" even though there is no character at position 10.
public String substring(int beginIndex, int endIndex)
beginIndex—the begin index, inclusive.
endIndex—the end index, exclusive.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3, 8));
}
}
Output: "lo Wo"
From 3 to 7 index.
Also there is another kind of substring() method:
public String substring(int beginIndex)
beginIndex—the begin index, inclusive.
Returns a sub string starting from beginIndex to the end of the main String.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3));
}
}
Output: "lo World"
From 3 to the last index.
Yes, the index starts at zero (0). The two arguments are startIndex and endIndex, where per the documentation:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
See here for more information.
The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.
For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing.
I would understand substring(startIndex, length) to remember that.
public class SubstringExample
{
public static void main(String[] args)
{
String str="OOPs is a programming paradigm...";
System.out.println(" Length is: " + str.length());
System.out.println(" Substring is: " + str.substring(10, 30));
}
}
Output:
length is: 31
Substring is: programming paradigm

Categories