I would like to know: which string returns substring(0, 0) , if the calling string consists of only one character?
String s1 = "W"; String s2 = s1.substring(0, 0); What is s2 equal to?
I would like to know: which string returns substring(0, 0) , if the calling string consists of only one character?
String s1 = "W"; String s2 = s1.substring(0, 0); What is s2 equal to?
You will get an empty string. What is not null , but just new String("") .
In such cases, always open the method documentation. And see its source code and logic of work. From source.
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); } value is a link to the array of characters that your string stores
The substring (n, m) method returns a substring starting from the n index (including) to the m index (not including). In our case, substring (0, 0) returns an empty string, as when initializing a new variable: String s2 = "";
This can be clearly demonstrated by the following code. When comparing s2 and "", equals returns true.
public static void main(String[] args) { String s1 = "W"; String s2 = s1.substring(0, 0); System.out.println(s2.equals(""));} true Source: https://ru.stackoverflow.com/questions/625741/
All Articles