giovedì 28 marzo 2013

Q52

Given a code fragment:
             StringBuilder sb = new StringBuilder();
              String h1 = "HelloWorld";
             sb.append("Hello").append("World");
             if (h1 == sb.toString()) {
                    System.out.println("They match");
             }
             if (sb.equals(h1)) {
                    System.out.println("They really match");
             }
What is the result?
A.
They match
They really match
B.
They really match
C.
They match
D.
Nothing is printed to the screen
StringBuffer non sovrascrive il  metodo equals () di Object e quindi restituisce true solo quando un oggetto StringBuffer viene confrontato con se stesso.
public boolean equals(Object obj) {
    return (this == obj);
}
Per comparare i valori di uno StringBuffers bisogna fare:
if (sb.toString().equals(h1)) {
          System.out.println("They really really really match");
}

Nessun commento:

Posta un commento