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?
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.
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.
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.
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.
+
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.
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