Page 1 of 1

Possible error in ocp-815 enthuware.ocpjp.i.v11.2.3052

Posted: Mon Jan 13, 2020 10:26 pm
by ocpjp11user
Hi guys)
Here is the screen of quesion
test1-41.png
test1-41.png (39.2 KiB) Viewed 3208 times
The question is about third option `str.strip()!=""`.
From the explanation, we can see that if string consist of only whitespaces, strip will return empty string, but it maybe a different object.
But if we go to `strip` method we see

Code: Select all

   public String strip() {
        String ret = this.isLatin1() ? StringLatin1.strip(this.value) : StringUTF16.strip(this.value);
        return ret == null ? this : ret;
    }

If we go deeper we will see

Code: Select all

    public static String strip(byte[] value) {
        int left = indexOfNonWhitespace(value);
        if (left == value.length) {
            return "";
        } else {
            int right = lastIndexOfNonWhitespace(value);
            return left <= 0 && right >= value.length ? null : newString(value, left, right - left);
        }
    }
and

Code: Select all

    public static String strip(byte[] value) {
        int length = value.length >> 1;
        int left = indexOfNonWhitespace(value);
        if (left == length) {
            return "";
        } else {
            int right = lastIndexOfNonWhitespace(value);
            return left <= 0 && right >= length ? null : newString(value, left, right - left);
        }
    }

From above it's clear that both of them return empty string(if it's only whitespaces) as literal, not as new object, so that proves that third option also correct.

Pay attention that it's not true for `trim` method.

Code: Select all

public class App {
    public static void main(String[] args){
        System.out.println(isBlankStrip(" "));      // true
        System.out.println(isBlankTrim(" "));   // false
    }
    private static boolean isBlankStrip(String str){
        String empty = str.strip();
        return empty == "";
    }
    private static boolean isBlankTrim(String str){
        String empty = str.trim();
        return empty == "";
    }
}

Re: Possible error in ocp-815

Posted: Mon Jan 13, 2020 11:14 pm
by admin
Hi,
I understand your point but the explanation and the answer are correct for the following reason:

1. The official JavaDoc API description for strip does not make any promise regarding whether the returned string will be an interned version or not.
That is why the explanation also says, "that empty string may be different".

2. Between the code and the JavaDoc description, the JavaDoc description is what should be relied upon because that is the public contract that the API developers are going to be held against and not how they implemented that contract. They are free to change the implementation anytime without affecting the contract.

HTH,
Paul.