Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods on string literals (Java)

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());
like image 360
csguy Avatar asked May 07 '19 06:05

csguy


People also ask

How do you call a string method using string literal in Java?

By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”);

Can we call string class methods using string literals?

Yes, we can call string class methods using string literals.

How do you call a method in a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.


1 Answers

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.

like image 58
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet