Page 336 - Computer_Science_F5
P. 336
Operator Description Example Output
*(Multiplication) Multiplies values A&B A*B 75
/(Division) Divides B by A B/A 3 Chapter Five: Object oriented programming with Java
% (Modulus) Divides left-hand operand by B%A 0
FOR ONLINE READING ONLY
right-hand operand and returns
remaainder
++ (Increment) This adds 1 to its operand A++ or 6
++A
– – (Decrement) This operator subtracts 1 from A- - or - 4
its operand -A
Arithmetic operators like +, -, *, and / in Java work similarly to other programming
languages and algebra. They apply to any numeric data type, including char. However,
note that when using the division operator (/) with integers, Java performs integer
division, discarding any remainder (e.g., 10/3 results in 3). To get the remainder, use
the modulus operator (%) (e.g., 10 % 3 equals 1).
In Java, the modulus operator % can be used with both integer and floating-point
types. Hence, 10.0 % 3.0 also equals 1. Workout the following Program Example 5.4
on modulus in any editor then compile and run the program in JDK using cmd.exe:
Program Example 5.4:
Java program to demonstrate the % operator
class Modulus {
public static void main(String args[]) {
int answer1, rem1;
double answer2, rem2;
answer1 = 10 / 3;
rem1 = 10 % 3;
answer2 = 10.0 / 3.0;
rem2 = 10.0 % 3.0;
System.out.println(“Answer and Remainder of 10 / 3: “ +
answer1 + “ “ + rem1);
System.out.println(“Answer and Remainder of 10.0 / 3.0: “ +
answer2 + “ “ + rem2);
}
}
327
Student’s Book Form Five
Computer Science Form 5.indd 327 23/07/2024 12:34

