Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java toString representations across Java virtual machine implementations?

Tags:

java

jvm

With most core libraries and Java classes, are 'toString' representations standard across all Java implementations. Or is this not specified in the Java spec.

For example, if I do, new HashMap()/toString , is the output from OpenJDK expected to be the same with IBM jrockit.

Should they be compatible? It may be an issue if you are porting code from one JVM to the other and expected the string representation to be the same.

like image 287
Berlin Brown Avatar asked Jan 09 '13 06:01

Berlin Brown


1 Answers

The output of toString() methods is (with few exceptions) unspecified, and therefore in theory could vary from one implementation of Java to the next.

However, most commercial Java implementations have class libraries that are derived from some version of the Sun / Oracle class libraries, be it the OpenJDK codebase or an earlier one. Given that Sun / Oracle are cautious about deliberately making changes that could break customer code, I would expect the respective toString() methods to be mostly compatible.

But there are some notable exceptions; e.g. java implementations based on the GNU Classpath libraries, the Apache Harvest libraries and ... Android. Note that these implementations don't pass the Java compliance tests (because Oracle refuses to licence the TDK under acceptable terms!!) so strictly speaking they can't be called Java(tm).

The bottom line is that dependence on undocumented toString() formats could lead to porting problems or problems when upgrading JVM versions. But in reality, the chance of problems depends critically on what you are porting from and to. If you stick to JVMs that use Oracle / Sun derived class libraries, the chance of problems is small.


So what should you do about this?

The most extreme position would be to avoid using toString methods (implicitly or explicitly), except in cases where the output format is specified. But I think that goes too far. (And it could be hard to enforce this policy ...)

A more realistic position would be to avoid using toString methods in cases where the precise output format matters. In other words:

  • Don't use toString() in object serialization schemes ... unless the format is specified.

  • If you use toString() in unit testing, be aware that you may need to fix non-portable unit tests as part of a porting effort.

like image 161
Stephen C Avatar answered Oct 21 '22 20:10

Stephen C