在Java中,字符串用于存储字符序列,它们被视为对象。java.lang包中的String类表示一个字符串。
您可以通过使用new关键字(像任何其他对象一样)或通过为字面值赋值(像任何其他原始数据类型一样)来创建一个字符串。
String stringObject = new String("Hello how are you"); String stringLiteral = "Welcome to Tutorialspoint";
由于字符串存储了一个字符数组,就像数组一样,每个字符的位置都用索引表示(从0开始)。例如,如果我们创建了一个字符串为−
String str = "Hello";
其中的字符被定位为 −
如果您尝试访问字符串中索引大于其长度的字符,则会抛出 Stringindexoutofboundsexception 异常。
示例
Java 中的 String 类提供了各种方法来操作字符串。您可以使用该类的 charat() 方法找到特定索引处的字符。
该方法接受一个整数值,指定字符串的索引,并返回指定索引处的字符。
在以下 Java 程序中,我们创建了一个长度为17的字符串,并尝试打印索引为40的元素。
演示
public class Test { public static void main(String[] args) { String str = "Hello how are you"; System.out.println("Length of the String: "+str.length()); for(int i=0; i<str.length(); i++) { System.out.println(str.charat(i)); } //Accessing element at greater than the length of the String System.out.println(str.charat(40)); } }
输出
运行时异常 -
由于我们访问索引处大于其长度的元素,因此会抛出 Stringindexoutofboundsexception。
Length of the String: 17 H e l l o h o w a r e y o u Exception in thread "main" java.lang.Stringindexoutofboundsexception: String index out of range: 40 at java.base/java.lang.Stringlatin1.charat(UnkNown Source) at java.base/java.lang.String.charat(UnkNown Source) at Test.main(Test.java:9)
以上就是在Java中,Stringindexoutofboundsexception是什么意思?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。