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