"Macro definition" in Java

Source: Internet
Author: User
Tags dota

Macro definitions often appear in the C + + code, in the form of "#define * * *". There are also "macro variables" in Java, but another form.

Final is a keyword in Java that is used to modify classes, member variables, local variables, and methods to represent immutable. When final modifies a variable, the variable is already specified as an initial value, and the variable is determined at compile time, the final variable is essentially a "macro variable", and the compiler replaces all the variables in the program with the value of the variable.

As in the following section of code:

[Java] view plain copy print?   String s1= "I love DotA";   String s2= "I Love" + "DotA";   System.out.println (S1==S2);   String str1= "I Love";   String str2= "DotA";   String s3=str1+str2; System.out.println (S1==S3);
First output: True, second output: false

Because Java uses a constant pool to manage the direct amount of strings that have been used, such as executing string a= "Java", a string "Java" is cached in the system's string pool if the program executes string b= "Java" again; The system will cause B to point directly to the "Java" string in the string pool, so a==b will return true; that's why the first output true in the above code.

For S3, the value is obtained by the operation, STR1 and str2 are just two ordinary variables, the compiler does not perform a macro substitution, so the compiler cannot determine the S3 value at compile time, nor can the S3 point to the cache in the string pool, so the second output statement outputs false.

For the second to also output true, just let the str1 and STR2 variables be finalized, so that all the str1 and STR2 variables in the program are replaced by their values, and the S3 values can be determined before compiling.

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.