3

I ran into some code containing the % symbol inside the array argument.

What does it mean and how does it work?

Example:

String[] name = { "a", "b", "c", "d" };

System.out.println(name[4 % name.length]);
System.out.println(name[7 % name.length]);
System.out.println(name[50 % name.length]);

Output:

a
d
c
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Mohamed Moamen
  • 286
  • 1
  • 3
  • 13
  • That is the modulo operator. It calculates the remainder of an integer division – meowgoesthedog Aug 19 '17 at 11:58
  • 5
    @meowgoesthedog: [Remainder](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3), not modulo. It would handle negative numbers differently if it were modulo. – T.J. Crowder Aug 19 '17 at 12:00

2 Answers2

11

That's the remainder operator, it gives the remainder of integer division. For instance, 3 % 2 is 1 because the remainder of 3 / 2 is 1.

It's being used there to keep a value in range: If name.length is less than 4, 7, or 50, the result of % name.length on those values is a value that's in the range 0 to name.length - 1.

So that code picks entries from the array reliably, even when the numbers (4, 7, or 50) are out of range. 4 % 4 is 0, 7 % 4 is 3, 50 % 4 is 2. All of those are valid array indexes for name.

Complete example (live copy):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String[] name = { "a" , "b" , "c" , "d"};
        int n;
        n = 4 % name.length;
        System.out.println(" 4 % 4 is " + n + ": " + name[n]);
        n = 7 % name.length;
        System.out.println(" 7 % 4 is " + n + ": " + name[n]);
        n = 50 % name.length;
        System.out.println("50 % 4 is " + n + ": " + name[n]);
    }
}

Output:

 4 % 4 is 0: a
 7 % 4 is 3: d
50 % 4 is 2: c
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • So, it means that, it'll not throw any errors but result won't be as expected, right? – The Alpha Aug 19 '17 at 12:03
  • 3
    @TheAlpha: Depends on what the expected result is. :-) Using `%` to keep values in range is **very** common, and gives the expected result if you're expecting to keep it in range. You mostly see it with indexes where you want to loop around: `index = (index + 1) % size` – T.J. Crowder Aug 19 '17 at 12:06
  • @Mr.Blue: Glad that helped. BTW, the `()` around `4`, `7`, and `50` in the quoted don't do anything. In general, the grouping operator (`()`) around a *single value* serves no purpose. – T.J. Crowder Aug 19 '17 at 12:09
1

Simple: this is the modulo, or to be precise the remainder operator.

This has nothing to do with arrays per se. It is just a numerical computation on the value that gets used to compute the array index.

GhostCat
  • 137,827
  • 25
  • 176
  • 248