Java - When a String is not a literal but an Object?

java, language-agnostic, literals, object, primitive

Solution

I think you're confusing primitive and literal.

A type can be a primitive type, or an Object type (i.e. inheriting from Object).

A literal just means a representation of value 'literally' in the code. This could represent a primitive or an Object type.

So 'literal type' doesn't really make sense. A string is never a literal, it is always an Object. The literal is just one possible way of representing a string in code.

The treatment in other languages varies widely. For example in C# everything derives from Object, including types which are 'primitive' in Java.

Problem

Yet again I am revisiting Java after yet another setback in my brain (see my profile). Similar questions have been asked here, but none in the fashion I wish to present this question. I have always understood what a `String` is. i.e, an An object as is clearly expressed in the official API. However I have been reading this Java guide on data types. To me the concept is clear. Primitives are literals. i.e, they can not be instantiated and are assigned values as follows: ``` primtype prim =?; ``` The official guides on Java all seem to (correctly) identify a String as a literal, but leave out what the criteria are to be regarded as a literal. Given that `java.lang.String`it is indeed a `java.lang.Obect` (through extension), does this underlying difference between a `String` being an `Object` as apposed to a `literal` lie merely in how the variable is assigned the value - by mere assignment (literal) as apposed to construction (Object)? Please feel free to point me to more in-depth resources if you can to help clarify? I would also like to know if the criteria for literals are consistent across languages (if this implies that "weakly typed" languages only use literals?)

Original source