Java Arithmetic Operators: Examples and Usage

Rumman Ansari   Software Engineer   2024-11-17 04:03:31   8227  Share
Subject Syllabus DetailsSubject Details 1 Questions 2 Program
☰ TContent
☰Fullscreen

Table of Content:

Arithmetic Operators

These operators are used to perform basic mathematical operations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (Remainder) a % b
Arithmetic Operators
Figure: Arithmetic Operators


The following program is a simple example which demonstrates the arithmetic operators. Copy and paste the following Java program in ArithmeticOperations.java file, and compile and run this program

Arithmetic Operators

class ArithmeticOperations {

    public static void main (String[] args){

        int answer = 2 + 2;
        System.out.println(answer);

        answer = answer - 1;
        System.out.println(answer);

        answer = answer * 2;
        System.out.println(answer);

        answer = answer / 2;
        System.out.println(answer);

        answer = answer + 8;
        System.out.println(answer);


        answer = answer % 7;
        System.out.println(answer);
    }
}

Output

4
3
6
3
11
4
Press any key to continue . . .

Increment and Decrement Operator :

class IncrementDecrement {
	public static void main (String[] args){
	int a = 2 ;
	int b = 6 ;
	a++ ;
	System.out.println(a);
	b-- ;
	System.out.println(b);
  }
 }

Output

3
5
Press any key to continue . . .

Increment and Decrement Operator another example:

class IncrementDecrementExample {
	public static void main(String args[]){

	int x= 5;
	System.out.println(x++);
	System.out.println(++x);
	System.out.println(x--);
	System.out.println(--x);
	}
}
Output
5
7
7
5
Press any key to continue . . .

Increment and Decrement Operator another example:

class IncrementDecrementExample{

	public static void main(String args[]){
	int p=10;
	int q=10;
	System.out.println(p++ + ++p);//10+12=22
	System.out.println(q++ + q++);//10+11=21

	}
}
Output
22
21
Press any key to continue . . .

Use of Modulus Operator

class ModulusOperator {
  public static void main(String args[]) {
    int    R = 42;
    double S = 62.25;

    System.out.println("R mod 10 = " + R % 10);
    System.out.println("S mod 10 = " + S % 10);
  }
}
Output
R mod 10 = 2
S mod 10 = 2.25
Press any key to continue . . .


Joining or Concatenate two strings

class AssignmentConcatination {
    public static void main(String[] args){

      String firstName = "Rahim";
      String lastName  = "Ramboo";

      String fullName  = firstName + lastName;
      System.out.println(fullName);
    }
}

Output

RahimRamboo
Press any key to continue . . .


MCQ Available

There are 10 MCQs available for this topic.

10 MCQ