0

What is the difference & performance between (ObjectClass not extend from String)

ObjectClass myObject = new ....

Method 1

String iString = "" + myObject;

Method 2 - ObjectClass not extend from String, i know it will be "ClassCastException" but assuming it's extend from String, what better ?

String iString = (String)myObject; //will fail?

Method 3

String iString = String.valueOf(myObject);

Method 4

String iString = myObject.toString();
Thanh Le
  • 763
  • 4
  • 13
  • Does `ObjectClass` extend `String`? In all cases except for method #2 a new `String` object will be created. And method #2 should fail if `ObjectClass` cannot be casted to a `String`. – Tim Biegeleisen Jun 13 '16 at 04:18
  • `(String) obj` and `obj.toString()` are completely different operations. `myObject` would need to extend `String` for it to not throw a `ClassCastException`. – 4castle Jun 13 '16 at 04:21
  • 1
    1,3,4 basically all call `toString()` on your object. 2 will fail with a `ClassCastException`. All except 4 are "null-safe". – Thilo Jun 13 '16 at 04:25
  • @TimBiegeleisen: ObjectClass not extend from String, i know it will be "ClassCastException" but assuming it's extend from String, what better ? – Thanh Le Jun 13 '16 at 04:26
  • 1
    Nothing can extend from String, String is final. "What is better" is a silly question, even with another class/interface as an example. – Thilo Jun 13 '16 at 04:27
  • 1
    Just to answer your performance question. Method 1 is the slowest because it calls `toString` but also does unnecessary concatenation. Method 3 & 4 are nearly identical except that Method 3 does a null check before calling `toString`. – 4castle Jun 13 '16 at 04:31

0 Answers0