Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant Page 108
Posted: Sun Feb 09, 2020 11:18 am
Page 108 states that substring method of the String class the one with 2 parameters returns a NEW STRING and this not always true consider the following example.
This is returning the same object is just a String optimization.
As you can see in the returning is saying if the beginning is the position 0 and the endIndex is the same of the end of the string the same String is returned.
I think stating that a NEW STRING is returned is not true.

This same principle applies for the 1 parameter method.
this is also returning true.
Code: Select all
public class StringSubsString {
public static void main(String[] args) {
final String child = "JOHNSTEPHENORTIZRONDON";
final String substring = child.substring(0,child.length());
System.out.println(child==substring);/*PRINTS TRUE*/
}
}
Code: Select all
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);
}
Code: Select all
return ((beginIndex == 0) && (endIndex == value.length)) ? this

This same principle applies for the 1 parameter method.
this is also returning true.
Code: Select all
public class StringSubsString {
public static void main(String[] args) {
final String child = "JOHNSTEPHENORTIZRONDON";
final String substring = child.substring(0);
System.out.println(child==substring);/*PRINTS TRUE*/
}
}
Code: Select all
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);
}
Code: Select all
return (beginIndex == 0) ? this