0

I don't understand the % comment.length bit of the following code:

comment.charAt(i % comment.length())

Does the part between the brackets convert to an integer with the value that represents i in relation to the comment length?

For instance, if:

comment = "test"
i = 2

what would comment.charAt(i % comment.length()) be?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Kees Koenen
  • 772
  • 2
  • 11
  • 27

2 Answers2

6

% is the modulo operator, thus for your example i % comment.length() would resolve to 2 % 4 = 2. This would return the third character (at index 2).

The modulo operation seems to be a safeguard for cases where i >= comment.length().

Consider the following case: i = 11 and comment = "test". If you just use comment.chatAt(i) you'd get an exception since there are only 4 characters. The modulo operation would wrap that around and result in 11 % 4 = 3 and return the fourth character (index 3) in that case.

Thomas
  • 87,414
  • 12
  • 119
  • 157
2

% is the modulo operator: it gives you the remainder of an integer division

10 % 3 = 1

as 10 / 3 = 3 with a remainder of 1

Your statement just ensures that the function argument will be less then the string length.

But I would rather check this in another way. It is pretty counterintuitive to ask for character at position 11 in a string long 10 characters and get the character at position 1 instead of a warning or error message.

Matteo
  • 14,696
  • 9
  • 68
  • 106