[英]Why doesn't this code throw an error in Java?
String s = "Hola";
System.out.println(s.substring(4));
4 is out of bounds, yet no error is thrown. 4超出范围,但未引发任何错误。
Why is that? 这是为什么?
Thanks in advance. 提前致谢。
Think of the argument to String.substring()
as the number of characters to skip . 将
String.substring()
的参数视为要跳过的字符数。 So skipping 4 characters in "Hola"
yields the empty string. 因此,在
"Hola"
跳过4个字符将产生空字符串。
"Hola".substring(0) => "Hola"
"Hola".substring(1) => "ola"
"Hola".substring(2) => "la"
"Hola".substring(3) => "a"
"Hola".substring(4) => ""
The lowest argument for which an exception will be thrown on a 4-character string is 5. 在4个字符的字符串上引发异常的最低参数是5。
The index of Strings starts at 0 and not 1. For example, in string "Hola", 字符串的索引从0开始而不是1。例如,在字符串“ Hola”中,
index 0 would be H 索引0为H
index 1 would be o 索引1为o
index 2 would be l 索引2将是l
index 3 would be a 索引3将是
Notice that there is no index 4. This is why you are getting an error. 请注意,这里没有索引4。这就是为什么会出现错误的原因。 instead, change it to
相反,将其更改为
System.out.println(s.substring(3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.