Java string operator "+"

Source: Internet
Author: User
Tags versions

This operator has a special purpose in Java: Connect different strings. This has been shown in the previous example. Although not consistent with the traditional meaning of +, it is still very natural to do it with +. In C + +, this feature looks very good, so introduces an "operator overload" mechanism so that C + + programmers add special meaning to almost all operators. Unfortunately, with other restrictions in C + +, operator overloading becomes a very complex feature that programmers must consider carefully when designing their own classes. Although operator overloading is easier to implement in Java than C + +, this feature is still considered too complex to date. So Java programmers can't design their overload operators as C + + programmers do.
We have noticed some interesting phenomena when using "String +". If the expression begins with a string, all subsequent operations must be strings. As shown below:

int x = 0, y = 1, z = 2;
String sstring = "x, y, z";
SYSTEM.OUT.PRINTLN (sstring + x + y + z);

Here, the Java compiler converts x,y and z into their string forms, rather than adding them together first. However, if you use the following statement:

SYSTEM.OUT.PRINTLN (x + sstring);

Then earlier versions of Java will be prompted for errors (later versions can convert x to a string). Therefore, if you want to use the "plus" connection string (using earlier versions of Java), make sure that the first element is a string (or a series of characters with quotation marks that the compilation can recognize as a string).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.