package corejava;
import static java.lang.Math.*;
public class CoreJava {
public static void main(String[] args) {
String string="hello" ;
if ("ello"==string.substring(1)) {
System.out.println("true");
}
else{
System.out.println("false\n");
}
if ("hello"==string.substring(0)) {
System.out.println("从0截取true");
}
else
{
System.out.println("从0截取全部false");
}
}
}
结果:
我查看源码发现果然如此:从0截取,返回this;否则返回了一个new string();
所以源码很重要!!!
/**
* Returns a string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. <p>
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if
* {@code beginIndex} is negative or larger than the
* length of this {@code String} object.
*/
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}