"Java doubts" Long integer calculation prevents overflow

Source: Internet
Author: User


The following code:

public class Example003 {public static void main (string[] args) {final long Micros_per_day = $ * * * + * 1000;FI nal Long MICROS_PER_DAY_L1 = 24 * * * * * * * 1000l;final Long millis_per_day = 60 * 60 * 1000; System.out.println ("NO L Print:" + micros_per_day/millis_per_day); Output 1system.out.println ("has L Print:" +micros_per_day_l1/millis_per_day); Output 2}}

Output Result:

NO l Print:5has L print:1000


Cause Analysis:

The results of output 1 and 2 are inconsistent because of the calculation overflow. Since all the multiplying factors in micros_per_day are int, when the two int is multiplied, the result is an int, so the micros_per_day evaluates to int, which is then assigned to the long type after the calculation is complete (overflow) micros_per_ Day,micros_per_day gets a partial value after overflow; MICROS_PER_DAY_L1 is calculated as a long type, and the result of the calculation is a long, which does not produce overflow. Therefore, in the operation of large numbers, must be aware of the overflow problem. Typically, a long is used to execute when calculating. That is, the standard numeric type is explicitly in the calculated factor.




This article from "Winger" blog, declined reprint!

"Java doubts" Long integer calculation prevents overflow

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.