Arithmetic Operators
Addition, subtraction, multiplication, division and modulus operator
Learning Objectives
- Understanding the simple use of arithmetic operators
Source Code
|
Run Output
Code Understanding
int a=10; int b=4;
Integer variables a and b have been initialised here
int c=a+b; //addition operator
int d=a-b; //subtraction operator
int e=a*b; //multiplication operator
int f=a/b; //Division Operator
int g=a%b; //Modulus operator to get the remainder after division
System.out.println(“a = “+a+” b = “+b);
System.out.println(“a+b = “+c);
System.out.println(“a-b = “+d);
System.out.println(“a*b = “+e);
System.out.println(“a/b = “+f+” (Integer Division)”);
System.out.println(“a%b = “+g);
Operator based results are printed above.
Notes
- Unlike c/c++ the % operator works for floating point numbers also in java. Rounding difference can certainly be there. One can get good understanding of modulus in java at the following link.
http://mindprod.com/jgloss/modulus.html - A programmer has to watch for divide by zero error as this error may not be shown at compile time.
- Once must take care of precedence of operators while making composite statements with operators. The precedence rule document is linked at
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Common Errors
- One may often forget that in the integer form 10/4 would be 2 and not 2.5 as the fractional portion would be ignored while storing in integer form. If we use double or float form, 10/4 will have to be written as 10.0/4 and stored as double or float, then it would be 2.5.
Suggested Filename(s): ArithmeticOp.java
sunmitra| Created: 1-Mar-2018 | Updated: 1-Mar-2018|