2

I find a very weird situation when writing Java code:

Integer x = myit.next();
if ((int)x % 2 == 0) {

In which myit is an Iterator and x is an Integer. I just want to test whether x is an even number or not. But x % 2 == 0 does not work since eclipse says % not defined on Integer. Then I try to convert x to int by explicitly converting. Again, it warns me that not able to convert in this way.

Any reason why it happened and what is the right way to test if x is even ?

UPDATE: ANYWAY,I test it that the following code works, which means all of you guys are right.

    Integer x = 12;
    boolean y = ( (x % 2) == 0 );
    boolean z = ( (x.intValue() % 2) == 0 );

I think the problem I have before may be the context of the code. It is late night, I would update later if I find why would that thing happen.

2
  • Your code works fine when I test using Java 8. Are you possibly using an earlier version of Java> Commented Sep 17, 2014 at 7:02
  • @CocoNess It is the first time I met such a dilemma. I use Java 7 in this code. I find other code that use integer.intValue() works but my code does not work. Commented Sep 17, 2014 at 8:17

4 Answers 4

5

Use :

if (x.intValue() % 2 == 0)

PS : if(x % 2==0) should also work because integer.intValue() should be called internally.

Byte code for :if(x % 2==0)

   11:  invokevirtual   #23; //Method java/lang/Integer.intValue:()I   --> line of interest
   14:  iconst_2
   15:  irem
Sign up to request clarification or add additional context in comments.

2 Comments

This is not necessary. You can use % with Integer.
@RuchiraGayanRanaweera - yes.. I was checking the byte code to reconfirm integer.intValue() was being called.
2
x % 2 == 0 does not work since eclipse says % not defined on Integer

This is not true. You can use % with Integer

take a look at this

Integer x = new Integer("6");
  if (x % 2 == 0) {
      System.out.println(x);
  }

Out put:

6

You should read about Integer in Java

Comments

1
public static void main(String[] args) {
        List<Integer> myList = new ArrayList<Integer>();
        myList.add(21);
        myList.add(22);
        myList.add(41);
        myList.add(2);

        Iterator<Integer> itr = myList.iterator();

        while (itr.hasNext()) {
            Integer x = itr.next();
            if (x % 2 == 0) {
                System.out.println("even");
            } else {
                System.out.println("odd");
            }
        }
    }

Output

odd
even
odd
even

Comments

0

Use this:

if(((int)x)%2==0){

Note: one more (

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.