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.
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24746)
- What is runtime polymorphism in Java?(18328)
- How to add BASIC Authentication into HttpURLConnection?(16088)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10446)