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());
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”);
Yes, we can call string class methods using string literals.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With