Biginteger, which is prone to mistakes in Java programming

Source: Internet
Author: User

In Java, there are many things that are easy to ignore. Today, I saw a Java puzzle on the Internet. The Code is as follows:

 

BigInteger five  = new BigInteger("5");BigInteger four = new BigInteger("4");BigInteger total = BigInteger.ZERO;total.add(five);total.add(four);  System.out.println(total);

 

At first glance, I think this code should output 9. After all, 4 + 5 = 9. In fact, if you run this code (this Code cannot be directly run, you need to modify it), you will be surprised to find that this code is printed out of 0.

 

Analysis:

  1. Unchangeable types: String, bigdecimal, biginteger, and various wrapper types are immutable types.
  2. The variable string feature is described in another blog.
  3. For example, the add method of biginteger does not change the two operands, that is, the existing instance, but returns a new instance.

 

Conclusion:

When you call a method of an immutable object, if you change the method of the object, the existing instance does not change, but returns a new instance.

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.