Java, Check if integer is multiple of a number
153,851
Solution 1
Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:
if (j % 4 == 0) {
// j is an exact multiple of 4
}
Solution 2
If I understand correctly, you can use the module operator for this. For example, in Java (and a lot of other languages), you could do:
//j is a multiple of four if
j % 4 == 0
The module operator performs division and gives you the remainder.
Solution 3
Use modulo
whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use
if (j % 4 == 0)
Author by
Shaun
Updated on August 21, 2022Comments
-
Shaun almost 2 years
How do I check if a Java integer is a multiple of another number? For example, if
int j
is a multiple of 4. -
Akhil Dad about 10 yearscheck j!= 0 also as, if j==0 it will result in 0
-
paxdiablo over 8 years@AkhilDad,
0
is still a multiple of4
. -
Admin about 7 yearsIts "modulo", not "module"