Arithmetic Operators

Java Arithmetic Operators:

In Java, arithmetic operators are used to work with numerical data types and do simple math tasks. These operators allow you to add, subtract, multiply, divide, and perform other arithmetic operations on variables and constants. They act as basic mathematical operations.

Example:

public class ArithmeticOperators { 
   public static void main(String[] args) { 
      int a = 10;
      int b = 20; 
      System.out.println(a + b); 
      System.out.println(a - b); 
      System.out.println(a * b); 
      System.out.println(a / b); 
      System.out.println(a % b); 
   }
}

Output:

30

-10

200

0

10

Here are the primary arithmetic operators in Java:

Addition (+): Adds two operands together.

Example:

int sum = 5 + 3; // sum will be 8

Subtraction (-):  You can subtract the right operand from the left operand with the symbol for minus (-).

Example:

int difference = 10 - 6; // difference will be 4

Multiplication (*): Multiplies two operands together.

Example:

int product = 3 * 4; // product will be 12

Division (/):   Takes the left operand and divides it by the right argument. The output will be an integer if both of the operands are integers.

Example:

int quotient1 = 10 / 3; // quotient1 will be 3 (integer division)
double quotient2 = 10.0 / 3; // quotient2 will be 3.3333333333333335

Modulus (%):  The modulus (%) function gives you the remainder when you divide the left operand by the right operand.

Example:

int remainder = 10 % 3; // remainder will be 1

Increment (++) and Decrement (–):

These are unary operators used to increase or decrease the value of a variable by 1, respectively.

Example:

int count = 5;
count++; // count is now 6
count--; // count is now 5 again
All operators example

It’s also important to note that arithmetic operations follow the standard rules of precedence. Parentheses can be used to change the order of evaluation, just like in standard mathematics. For example:

int result = (22 + 8) * 6; // result will be 180 (22 + 8 is evaluated first, then multiplied by 6)

Keep in mind that arithmetic operations are only valid for numeric data types, such as int, float, double, long, etc. Trying to perform arithmetic operations on non-numeric types will result in a compilation error.





Visited 1 times, 1 visit(s) today

Comments are closed.

Close