Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string literal automatically interpreted as String object, but how?

Tags:

java

string

jvm

What are the mechanics behind Java automatically interpreting string literals as String objects, since there are no overloaded operators and there is no default support for low-level string buffers (not including the high level StringBuffer)? Is this a language or virtual machine context?

like image 677
TurtleToes Avatar asked Mar 24 '11 04:03

TurtleToes


2 Answers

It's a little of both.

The JVM has byte codes for loading string literals onto the runtime stack, and these opcodes are specified in the JVM spec to work by pushing an appropriately-constructed String object onto the stack whose contents are equal to some string literal specified in the class file. There is no specification for how this is done other than that the String object must be interned, meaning that the transformation is implementation-specific.

At the language level, the compiler can treat any String literal it sees as a complete String object for the purposes of type checking, and can then just write out the literal and the appropriate bytecodes into the class file.

like image 66
templatetypedef Avatar answered Oct 06 '22 00:10

templatetypedef


Java actually does have a few overloaded operators. For example, + can be applied to String objects as well as to int, float, and other numerical types. In each case, the return type is defined by the type of the expression on each side of the +. However, all overloaded operators are predefined in the language; programmers have no mechanism in the language to define any others. See the language specification for details.

like image 22
Ted Hopp Avatar answered Oct 06 '22 01:10

Ted Hopp