Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the percentage symbol (%) mean? [duplicate]

Tags:

java

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
like image 330
Mohamed Moamen Avatar asked Nov 15 '25 19:11

Mohamed Moamen


2 Answers

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
like image 154
T.J. Crowder Avatar answered Nov 18 '25 11:11

T.J. Crowder


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.

like image 44
GhostCat Avatar answered Nov 18 '25 09:11

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!