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?

  • 9
    why not just execute this code and not look? - Grundy
  • because the compiler swears, and I do not understand the logic of his discontent - Arc
  • Well, if the code is not compiled, then nothing will definitely return - default locale
  • the code is compiled, but with corrections, if you put the static modifier in front of the variables, then when outputting s2 via println, nothing is simply output (well, the empty string), why the static modifier is needed - Arc
  • 2
    and I do not swear :-) maybe you should at least give an error, which he displays? - Grundy

3 answers 3

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