StringIndexOutOfBoundsException
Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs
The StringIndexOutOfBoundsException
is an exception that occurs when a String
method tries to use an index that is either negative or greater than the size of the String
.
Example
The following example creates a StringIndexOutOfBoundsException
:
public class ErrorExample {public static void main(String[] args) {String greeting = "Hello World";System.out.println(greeting.charAt(-1));}}
The output is something like this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)at java.base/java.lang.String.charAt(String.java:1512)at ErrorExample.main(ErrorExample.java:4)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours