Mod division of two integers

user2268305 picture user2268305 · Apr 26, 2013 · Viewed 52.9k times · Source

I keep getting the error "The operator % is undefined for the argument type(s) Integer, Integer" I am not quite sure why this is happening. I thought that since modular division cannot return decimals that having integer values would be alright.

This is happening within a method in a program I am creating. The code is as follows:

    public void addToTable(Integer key, String value)
{
    Entry<Integer, String> node = new Entry<Integer, String>(key, value);
    if(table[key % tableSize] == null)
        table[key % tableSize] = node;
}

The method is unfinished but the error occurs at

    if(table[key % tableSize] == null)

and

    table[key % tableSize] = node;

any help or suggestions would be appreciated.

Answer

rgettman picture rgettman · Apr 26, 2013

I could get some sample Integer % Integer code to compile successfully in Java 1.5 and 1.6, but not in 1.4.

public static void main(String[] args)
{
   Integer x = 10;
   Integer y = 3;
   System.out.println(x % y);
}

This is the error in 1.4:

ModTest.java:7: operator % cannot be applied to java.lang.Integer,java.lang.Integer
       System.out.println(x % y);
                            ^

The most reasonable explanation is that because Java introduced autoboxing and autounboxing in 1.5, you must be using a Java compiler from before 1.5, say, 1.4.

Solutions:

  • Upgrade to Java 1.5/1.6/1.7.
  • If you must use 1.4, use Integer.intValue() to extract the int values, on which you can use the % operator.