Puzzle 13: Farm

Source: Internet
Author: User

Readers of George Orwell's Animal Farm may remember the old colonel's statement: "All animals are equal ." The following Java program tries to test this declaration. So what will it print out?

public class AnimalFarm{    public static void main(String[] args){        final String pig = "length: 10";        final String dog = "length: " + pig.length();        System.out. println("Animals are equal: "                            + pig == dog);    }}

The surface analysis of the program may think that it should print out the animal are equal: True. After all, pig and dog are both final string-type variables and they are initialized as character sequences "Length: 10 ". In other words, strings referenced by pig and dog are always equal to each other. However, the = Operator tests whether the two objects reference the same object. In this example, they are not referenced to the same object.

You may know that constants of the string type during compilation are memory-limited. In other words, if two constant expressions of the string type indicate the same character sequence, they are represented by the same object reference. If you use a constant expression to initialize pig and dog, they actually point to the same object, but dog is not initialized using a constant expression. Since the language has imposed restrictions on operations allowed in constant expressions, and method calls are not included, this program should print animal are equal: false, right?

Well, actually not. If you run the program, you will find that it prints only false, and there is nothing else. It does not print animal are equal :. How can it not print this string literal constant? After all, printing is correct! The solution to puzzle 11 contains a suggestion: The + operator, whether used as an addition or a string join operation, has a higher priority than the = Operator. Therefore, the parameters of the println method are calculated as follows:

System.out.println(("Animals are equal: " + pig) == dog);

Of course, the value of this Boolean expression is false, which is the output of the program.

There is a way to avoid this dilemma: when using string Concatenation Operators, they always enclose non-trivial operands in parentheses. More generally, when you are not sure whether you need parentheses, you should choose to enclose them securely. If you include the comparison section in the println statement as follows, it will generate the expected output animals are equal: false:

System.out.println("Animals are equal: " + (pig == dog));

It can be demonstrated that the program still has problems.

If possible, your code should not rely on the memory limitation mechanism of string constants. The memory limitation mechanism is designed to reduce the memory occupation of virtual machines. It is not designed as a tool that programmers can use. As shown in this puzzle, it is not always obvious which expression will generate a String constant.

Worse, if your code depends on the memory limitation mechanism to ensure that the operation is correct, you must carefully understand which fields and parameters must be memory-limited. The compiler will not check these constants for you, because memory-qualified and unrestricted strings are represented by the same type (string. These bugs caused by failed character string limitation in the memory are very difficult to detect.

When comparing object references, you should first use the equals method instead of the = Operator, unless you need to compare the object identifier rather than the object value. By applying this lesson to our program, we provide the following println Statement, which is what it should look like. Obviously, after the program is corrected in this way, it prints true:

System.out.println("Animals are equal: " + pig.equals(dog));

This puzzle has two lessons for Language designers.

1. The priority of string connection should not be the same as that of addition. This means that there is a problem with the overload + operator to execute string connections, as mentioned in puzzle 11.

2. Another reason is that for non-modifiable types such as string, the equivalence ratio of the referenced values is even more confusing. Maybe = The operator should execute value comparison when applied to non-modifiable types. To achieve this, a simple way is to use the = operator as the equals method and provide a separate method similar to system. identityhashcode to compare the referenced identifiers.

Puzzle 13: Farm

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.