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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With