I am confused as to how the Java String class default constructor converts the char array into String.
char c[]= {'H', 'E', 'L', 'L', 'O'};
String s= new String (c, 0,3);
System.out.println(s) ;
Gives output as - HEL
In this case, the last character is taken as endIndex - 1.
char c[]= {'H', 'E', 'L', 'L', 'O'};
String s= new String (c, 1,3);
System.out.println(s) ;
Gives output as - ELL
But, in this case, the last character is taken as endIndex only.
What's happening here?
The third parameter is count
not endIndex
, it specifies how many characters are copied from the input. From the docs:
public String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string. [emphasis mine]