Calling methods on string literals (Java)

csguy :

I know that string literals are objects. According to

https://en.wikibooks.org/wiki/Java_Programming/Classes,_Objects_and_Types

When an object is created, a reference to the object is also created. The object can not be accessed directly in Java, only through this object reference. This object reference has a type assigned to it. We need this type when passing the object reference to a method as a parameter.

But are we violating this when we have literals access String methods?

For example:

System.out.println("Literal".toUpperCase());

Isn't this directly accessing the object? as opposed to accessing the object through the reference.

For example:

String x = "Literal"; 
System.out.println(x.toUpperCase());
Jon Skeet :

Isn't this directly accessing the object? as opposed to accessing the object through the reference.

No, you're still using a reference. The value of an expression which is a string literal is a string reference. It's still not an object that you access directly.

In your example, the value of x is still a reference, and your two snippets are equivalent except for the presence of the variable x.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36098&siteId=1