Introduction to Operators and Expression in Java • 53
public static void main(String args[])
{
System.out.println(“\n BEHAVIOUR OF MOD OPERATOR\n”);
System.out.println(“17%5 :=” + (17 % 5));
System.out.println(“-17%5 :=” + (-17 % 5));
System.out.println(“17%5 :=” + (17 % 5));
System.out.println(“-17%-5 :=” + (17 % -5));
}
}
OUTPUT:
BEHAVIOUR OF MOD OPERATOR
17%5 :=2
-17%5 :=-2
17%5 :=2
-17%-5 :=2
Explanation: Using % operator if the numerator is negative, the answer will also be negative. This can be
verifi ed by the formula given in the program for − 17 and 5 .
– 17 % 5 5 –17 – (–17/5)*5
5 –17 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.