FAQ

Java

JSP

Servlet


Advertisement



What is the "substring trap" in Java?

String.substring(int beginIndex, int endIndex) is a way of extracting a new string that is a substring of a String. The offsets are 0-based, i.e. the first character of the String is character 0. The name endIndex suggests that is the index where the Substring ends. Do not be confused and mislead by endIndex, the largest endIndex is one character past the end of the String.

According to String APIs document, "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".

For example,

class Program {
public static void main(String[] args) {
String s="substring trap";
System.out.println(s.substring(3,9));
}
}

The output is: string.


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |