What will be the output of String.substring(String.length)? - java

public class Str {
public static void main(String[] args) {
String str = "abcde";
String s = str.substring(str.length());
System.out.println(s);
}
}
The index of character 'e' is 4, but I am trying to get the whole string of length 5. If I execute the code above, why it is not throwing the IndexOutOfBoundsException?

The JavaDoc for String.substring() states:
[throws] IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Since your beginIndex is equal to the length of the string it is a valid value and substring() returns an empty string.

The empty String ("" with length 0) is a valid String. So that is what is returned by your code.
In other words str.substring(str.length()-1); returns the string "e", and str.substring(str.length()); returns the empty string. Perfectly valid.

Assume you got a String:
Hello World
this is what the indicies look like:
H e l l o W o r l d
0 1 2 3 4 5 6 7 8 9 10
"Hello World" has length of 11 so str.length would be equal to 11 in this case
now there is no index 11 in there, in fact 11 is beyond the last index. thats why you receive a IndexOutOfBounds
Additionally str.substring(number) returns a substring STARTING from the specified number all the way to the end of the string.
so str.substring(4) in this case would return
o World
Just thought i should put that in here

Related

Why doesn't calling a substring using the length of the string as the beginning index throw an OutOfBoundsException?

When was testing some code, I noticed that the substring method wouldn't throw an exception if the index I used was equal to the length of the string. For example:
String s = "holy";
System.out.println(s.substring(4));
The output would return nothing, but it wouldn't throw an exception. But if I tried to call:
String s = "holy";
System.out.println(s.substring(5));
It would throw an IndexOutOfBoundsException. I read the Javadoc for the method and it says
if beginIndex is negative or larger than the length of this String object.
Anyone know why it allows for the beginning index to be equal to the string length?
Think about other invocations of substring:
"holy".substring(n)
can be visualized as copying the range of characters between n (inclusive) and the end of the string (exclusive).
For example:
"holy".substring(0)`
h o l y
O-------X (O = start, X = end)
0 1 2 3 4
That is, the start position is just before the character, and the end position is just after the character. The resulting length of the string is end - start, 4 in this case.
and
"holy".substring(1)
h o l y
O-----X // length = 4 - 1 = 3.
0 1 2 3 4
etc. Then:
"holy".substring(4)
can be visualized as
h o l y
O // O and X are at the same position
X // length = 4 - 4 = 0
0 1 2 3 4
It's fine that O and X are at the same position: it just means the result is a zero-length string, "".
But, increase the index to 5:
"holy".substring(5)
h o l y
X-O // O is after X
// length = 4 - 5 = -1 (?!)
0 1 2 3 4 5
A string of length -1 doesn't make sense, hence the exception.
There is basically one reason for this, in substring(int beginIndex, int endIndex), if beginIndex == endIndex then the result is an empty string. So given that property, and the fact that the maximum value of endIndex is the string length, then allowing string.substring(string.length(), string.length()) should be allowed and return an empty string as well. And this last can be simplified to string.substring(string.length()).
Allowing the length as a valid begin index also provides a number of nice properties:
"".substring(0) returns ""
Considering the pairs String start = string.substring(0, n) and String end = string.substring(n) results in the following:
n = 0: start = "", end = string
n = string.length(): start = string, end = ""
Disallowing this and throwing an exception would require all kinds of additional bounds checks in string manipulation code (and in substring itself for that matter).
public String substring(int startIndex) return the substring from the startIndex of your string. So in your example it will be position 4 (which is exists) and the substring will be "" (empty string).

String index out of range - java

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.

java charAt() method and surrogate

I am writing java code and want to know why the output of this code is x. I was expecting t since it is the 5th letter.
public class StringBufferDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("ttsttxctlltnt");
System.out.println(sb.charAt(5));
}
}
It's because in java a StringBuffer object is indexed starting at 0. 1st char at position 0, 2nd char at position 1, etc...
String ------ "t t s t t x c t l l"
ArrayIndex -- 0 1 2 3 4 5 6 7 8 9
The index starts from 0 and not 1. Hence in the string "ttsttxctlltnt", the character at position 5(0,1,2,3,4,5) i.e 'x' will be printed.
the index starts at 0 so the the character at 5 th posistion is x ... if u want t as the output then try the following
System.out.println(sb.charAt(4));

indexOf() of StringBuilder doesn't return anything

StringBuilder builder = new StringBuilder();
builder.setLength(10);
builder.append("d");
System.out.println(builder.length() + "\t" + builder.toString() + "\t" + builder.indexOf("d"));
Output:
11
Problem:
Why indexOf() doesn't return anything.
My Understanding:
As per my understanding, it should return 10, since StringBuilder is counting the "d" as part of its length in length().
But in case if "d" is not part of string hold by StringBuilder then, it should return -1 and length should be 10.
If you look at the docs of StringBuilder#setLength(int newLength)
If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.
That is why when you append "d" after setting the length, it is placed after the 10 null characters.
Q. Why indexOf() doesn't return anything.
It does return a value and that is 10, since the indexing is 0-based. This is the output of your code.
11 d 10 // the 10 represents the index of d
^-length ^-10 null chars followed by d
The reason you're not getting the output may be because of your console not supporting null characters. That is why, when it encounters the null character \u0000, it would just stop printing the values in the console. Try using eclipse which supports printing of Unicode characters.
Sample snapshot:

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