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
Related
What does that mean? The length of the string is too long or there is error in my code?
public class Program {
public static String flipEndChars(String s) {
if(s.charAt(0) == s.charAt(s.length())){
return "Two's a pair.";
}
else if(s.length()<3){
return "incompatible";
}
else
return s.charAt(s.length()) + s.substring(1,s.length()) + s.charAt(0);
}
}
the issue is with this part :
s.charAt(s.length())
It's trying to access a character beyond the length of your string. The indexation is zero based, so the last character of a string is always at index s.length() - 1
String.charAt(int) returns the char at the specified index, where 0 is the first character, 1 is the second character, 2 is the third, and so on.
"hello".charAt(0) returns the character h.
String.length() returns the length of the string.
"hello".length() returns 5. So if you call "hello.charAt(5)", this will get the 6th character in the String "hello", which does not exist. This will throw an IndexOutOfBoundsException.
I hope this helps.
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));
I tried to get string from long string which is Firebase URL
"https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296"
Now if you notice there is under score before and after name Julien in above string. I am trying to get that name but i am getting
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Here is my piece of code
String s="https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
System.out.println(newName);
As said in my comment, when using substring, the first number has to be smaller than the second one.
In your case, you are calling substring with x + 1 and x. x + 1 > x thus substring fails, with x being s.indexOf("_").
I understand that you are trying to get the second indexOf of _.
Here is code that would in your case yield Julien:
String s = "...";
int start = s.indexOf("_") + 1;
int end = s.indexOf("_", start);
// name will hold the content of s between the first two `_`s, assuming they exist.
String name = s.substring(start, end);
If requirements are not clear on which 2 _ to select then here is Java 8 Stream way of doing it ..
public class Check {
public static void main(String[] args) {
String s = "https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
long count = s.chars().filter(ch -> ch == '_').count();
if (count == 2) {
System.out.println(s.substring(s.indexOf('_') + 1, s.lastIndexOf('_')));
} else {
System.out.println("More than 2 underscores");
}
}
}
Why your code didn't work?
Let assume s.indexOf("_") gets some positive number say 10 then below translates to ...
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
String newName=s.substring(11, 10);
This will give StringIndexOutOfBoundsException as endIndex < beginIndex for subString method.
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.
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