Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is `+` implemented for Strings in the Java source code? [duplicate]

String is a special case in Java. It's a class, which I can examine in the source code, but it also has its own infix operator +, which seems to be syntactic sugar for StringBuilder.

For example,

"Hello " + yourName; 

could become

new StringBuilder().append("Hello ").append(yourName).toString(); 

There are no user-defined operators in Java, so where is + specified for String?

Could the same mechanism be used to make additional operators, such as for vectors?

like image 891
sdgfsdh Avatar asked Sep 22 '15 10:09

sdgfsdh


People also ask

How do you duplicate a string in Java?

To make a copy of a string, we can use the built-in new String() constructor in Java. Similarly, we can also copy it by assigning a string to the new variable, because strings are immutable objects in Java.

How is string implemented in Java?

String concatenation is implemented through the StringBuilder (or StringBuffer ) class and its append method. String conversions are implemented through the method toString , defined by Object and inherited by all classes in Java.

Can we assign one String to another String in Java?

As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.

What is a String in Java?

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.


1 Answers

+ is implemented in java compilers. The compiler replaces String + String with either compile time constants or StringBuilder code. Note that this applies to primitives too. i.e, int i=1+2 could get directly replaced to int i=3 during compilation itself.

like image 159
TheLostMind Avatar answered Oct 10 '22 20:10

TheLostMind