It's not that simple: how to determine whether an integer is an even or an odd number in Java

Source: Internet
Author: User

Environment: JDK 1.7.

Package Hellojava; public class Hellojava {//Use remainder operation public boolean isEven01 (int num) {if (num% 2 = = 0) {return t        Rue        } else {return false;        }}//If there is no take-up operator, make a public boolean isEven02 (int num) {int tmp = NUM/2;        if (num-tmp*2 = = 0) {return true;        } else {return false;        }}///Change the idea of public boolean isEven03 (int num) {String numstr = new Integer (num). toString ();                 Char Lastchar = Numstr.charat (Numstr.length ()-1); Switch (Lastchar) {case ' 0 ': Case ' 2 ': Case ' 4 ': Case ' 6 ': Case ' 8 ' : Return true;             There's no need to break. Default:return false;        }} public static void Main (string[] args) {Hellojava HJ = new Hellojava ();        System.out.println (Hj.iseven01 (10));        System.out.println (HJ.ISEVEN02 (10)); SYstem.out.println (HJ.ISEVEN03 (10));        System.out.println (Hj.iseven01 (11));        System.out.println (HJ.ISEVEN02 (11));     System.out.println (HJ.ISEVEN03 (11)); } }

Execution Result:


truetruetruefalsefalsefalse

In addition, the minus 2 and the remainder of the negative integer should be noted:

package hellojava; public class HelloJava {         public static void main(String[] args) {                 System.out.println(-10/2);        System.out.println(-10%2);        System.out.println(-11/2);        System.out.println(-11%2);    } }

The results of the operation are as follows:


-50-5-1

It's not that simple: how to determine whether an integer is an even or an odd number in Java

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.