The judgment of the Java face test odd even __j2se

Source: Internet
Author: User

Java interview question:

When deciding whether a number is odd or even, which way should you choose to judge? The code is as follows ()

A:

int val=//A digital

 if (val%2==0)

   System.out.println ("even");

else

  System.out.println ("odd");


B:

int val=//A digital

 if (val%2==1)

   System.out.println ("odd");

else

  System.out.println ("even");


A lot of people will think that these 2 ways are the same. Fact When an integer is greater than 0. The results are consistent in 2 ways. But when the integer is less than 0, the result is divided.

The way to choose A is -1%2 1 is not equal to 0 so he is right for odd numbers. But the way of choosing B and -1%2 is not equal to 1 so the result-1 is even.

So why is there such a mistake in the B way? The underlying algorithm for modulo operations is

A%b--------------------return A-(A/b) *

Then the -1%2 result is of course-1. So the judgment statement goes into else, causing the result of-even 1.

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.