Operators in Java

Operators in Java are used to perform operations with values, usually saved on variables. These values used in the operation are called operands and the operation performed with the operands is defined by the operator.

Java has different types of operators:

  • Arithmetic.
  • Comparison.
  • Logical.
  • Assignment.

Arithmetic operators

Java provides the following operators for performing arithmetic operations

OperatorOperation
+Sum: Add two operands
Subtraction: Subtract right operand from left one
*Multiplication: multiply both operands
/Division: Divide left operand by right one
%Module: Remainder of the division between two operands
++Increment: Increase operand value by one
Decrement: Decrease operand value by one
Operators in Java

Let’s see in practice how these operators work.

Exercise 1: Practicing with arithmetic operators

  1. Open the Java online compiler
  2. Introduce the following code:
public class HelloWorld{

public static void main(String []args){

    int num1=7,num2=11;
    double result;

    System.out.println ("Numbers: "+num1+" - "+num2);

    result = num1+num2;
    System.out.println ("Sum: "+result);

    result = num1-num2;
    System.out.println("Subtraction: "+result);

    result = num1/num2;
    System.out.println("Division: "+result);

    result = (double)num1/(double)num2;
    System.out.println("Division - casting double: "+result);

    result = num1%num2;
    System.out.println("Remain: "+result);

    result = num2%num1;
    System.out.println("Remain: "+result);

    int inc = num1++;
    System.out.println("Increasing the first number :"+inc);

    inc =++num1;
    System.out.println("Increasing the first number :"+inc);

    int dec = --num2;
    System.out.println("Decreasing the second number :"+dec);

    }
}

Line 3 & 4: Declaration and initialization of the two integer variables that we will use as operands. And the declaration of the double type variable that we will use to save the results of our operations.

    result = num1+num2;
    System.out.println ("Sum: "+result);

Line 6 & 7: Addition operation between the variables num1 and num2. The result is saved in the result variable and showed on the screen

    result = num1+num2;
    System.out.println ("Sum: "+result);

Line 10 & 11: Division of two operands of integer type. Since the division is not exact, the result loses precision.

    result = num1/num2;
    System.out.println("Division: "+result);

Line 12 & 13: Division of two integer type operands that have previously been cast to double type.

    result = (double)num1/(double)num2;
    System.out.println("Division - casting double: "+result);

Line 14 & 15: Modulus operator with operands num1 and num2. Since num1 <num2, the remainder of the division of both numbers is num1.

    result = num1%num2;
    System.out.println("Remain: "+result);

Line 18 & 19: increment operator, in its suffix mode. First, the data in num1 is stored in the variable inc and then it is incremented by 1.

And it showed on the screen the value of inc that is equal to the value of num1 before it is incremented.

    int inc = num1++;
    System.out.println("Increasing the first number :"+inc);

Line 20 & 21: increment operator, in its prefix mode. The data in num1, which has a value of 8, is first incremented and then stored in the variable inc.

    inc =++num1;
    System.out.println("Increasing the first number :"+inc);

Line 22 & 23: decrement operator, in its prefix mode, is applied to the variable num2 and the result is stored in the variable dec

    int dec = --num2;
    System.out.println("Decreasing the second number :"+dec);
  1. Run the program. You should get the following result:
Numbers: 7 - 11
Sum: 18.0
Subtraction: -4.0
Division: 0.0
Division - casting double: 0.6363636363636364
Remain: 7.0
Remain: 4.0
Increasing the first number :7
Increasing the first number :9
Decreasing the second number :10

Comparison Operators

They are used to compare two values:

OperatorDescription
==equal
!=Different
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
Comparison operators in Java

Let’s practice with these types of operators

Exercise 2: Practicing with comparison operators

  1. Open the Java online compiler
  2. Introduce the following code:
public class Operators{

public static void main(String []args){

    int num1,num2;
    num1 = 2; num2 = 3;

    if (num1 == num2){
        System.out.println("1.-Both numbers are equal");
    }else{
        System.out.println("1.-The numbers are different");
    }

    num1 = 3;
    if (num1 == num2){
        System.out.println("2.-Both numbers are equal");
    }else{
        System.out.println("2.-The numbers are different");
    }

    num1 = 7; num2 = 3;
    if (num1 > num2){
        System.out.println("3.-The first number is greater than the second");
    }else{
        System.out.println("3.-The second number is greater than the first");
    }
    }
}

Line 1: This time, I have changed the name of the class, from the classic “HelloWorld” to “Operators”.

public class Operators

Line 3: Declaration of the two integer variables that I will use with the comparison operators.

int num1,num2;

Line 4: Initialization of the two variables. Note: The “=” operator is an assignment operator, not a comparison operator.

    num1 = 2; num2 = 3;

Line 5: We compare both variables within an “if” statement, using the comparison operator “==”. Note that it is a comparison operator (two equal signs in a row). The result of the comparison operation will be true if both values ​​are equal and false if they are not.

    if (num1 == num2){

Line 6: It would be executed if the result of the comparison within the “if” statement is true. Showing the message on the screen

        System.out.println("1.-Both numbers are equal");

Line 8: It would be executed if the result of the comparison within the “if” statement is false. Showing the corresponding message on the screen.

        System.out.println("1.-The numbers are different");

Line 10: The value of the variable num1 is updated, it will now be worth 3. Both variables have the same value.

    num1 = 3;

Line 11 to line 15: “if” statement similar to the one starting on line 5

    if (num1 == num2){
        System.out.println("2.-Both numbers are equal");
    }else{
        System.out.println("2.-The numbers are different");
    }

Line 16: Change the value of both variables

    num1 = 7; num2 = 3;

Line 17 to line 21: A new “if” statement compares both variables, this time using the greater than operator: “>”.

    if (num1 > num2){
        System.out.println("3.-The first number is greater than the second");
    }else{
        System.out.println("3.-The second number is greater than the first");
    }

Although we do not check all the comparison operators in this practice, it is enough to get an idea of ​​how they work. You can check the rest of the operators and practice their operations.

  1. Run the program and you will get the following result:
1.-The numbers are different
2.-Both numbers are equal
3.-The first number is greater than the second

Logical operators

They are used to perform logical operations with variables

OperatorNameDescription
&ANDReturns true when both operands are true. The operands are evaluated before operating.
|ORReturns true if at least one of the two operands is true. The operands are evaluated before applying the operator.
^XORReturns true if only one of the operands is true.
&&Conditional ANDSame as the AND operator, but if the operator on the left is evaluated false, then false is returned without evaluating the operator on the right.
||Conditional ORSame as the OR operator, but if the operator on the left is evaluated as true, then true is returned, without evaluating the operator on the right.
!NOTIt is a unary operator, which works with only one operand.
If the operand is true, false is returned. And if the operand is false, it returns true.
Logic operators in Java

Let’s practice with these types of operators

Exercise 3: Practicing with logical operators

  1. Open the Java online compiler
  2. Introduce the following code:
public class LogicalOperators{

public static void main(String []args){

    boolean b1=true,b2=false;

    System.out.println ("b1= "+b1);
    System.out.println ("b2= "+b2);
    System.out.println ("!b2= "+!b2);
    System.out.println ("b1 & b2= "+(b1&b2));
    System.out.println ("b1 && b2= "+(b1&&b2));
    System.out.println ("b1 | b2= "+(b1|b2));
    System.out.println ("b1 || b2= "+(b1||b2));
    System.out.println ("b1 ^ b2= "+(b1^b2));
    }
}

Line 3: Declaration of two Boolean variables that will be the ones I will use to show how the different logical operators work.

    boolean b1=true,b2=false;

The rest of the lines all do practically the same thing: They draw an operation and its result on the screen.

  1. Run the program. You should get the following result:
b1= true
b2= false
!b2= true
b1 & b2= false
b1 && b2= false
b1 | b2= true
b1 || b2= true
b1 ^ b2= true

Assignment operators

These types of operators are used to assign values to variables:

OperatorExampleEqual to
=x = 5x = 5
+=x += 3x = x+3
-=x -=3x = x-3
*=x *= 3x = x*3
/=x /= 3x = x/3
%=x %= 3x = x%3
&=x &=3x = x&3
|=x |= 3x = x|3
^=x ^= 3x = x^3
<<=x <<= 3x = x << 3
>>=x >>= 3x = x >>= 3
assignment operators in Java

The first one in the table above is wildly common and we’ve already used it several times. It is the one we use when we initialize a variable to save a certain value in it.

The rest are not that common, but in any case, let’s see how they work.

Exercise 4: Practicing with assignment operators

  1. Open the Java online compiler
  2. Introduce the following code:
public class AssignmentOperators{

public static void main(String []args){

    int num = 2;

    System.out.println ("number= "+num);
    System.out.println("number += 2 -> increments number by 2:");
    System.out.print("\t");
    System.out.println (num+=2);

//Save again value 2 in variable num
    num = 2;
    System.out.println("number *= 3 -> multiplies number by 3:");
    System.out.print("\t");
    System.out.println (num*=3);
    }
}

Line 3: Declaration and initialization of a variable of integer type that I will use to perform the assignment operations

    int num = 2;

Line 4 to line 7: Instructions for painting different texts and values on the screen. This, we already know how it works.
With the last line, we draw the result of the operation “num + = 2” on the screen.

    System.out.println ("number= "+num);
    System.out.println("number += 2 -> increments number by 2:");
    System.out.print("\t");
    System.out.println (num+=2);

Line 12: And with this other instruction, we draw the result of the operation “num * = 3” on the screen.

    System.out.println (num*=3);

This practice provides a general idea of the use of assignment operators. You can check on your own the rest of the operators and practice how they work.

  1. Run the program. You should get the following result:
number= 2
number += 2 -> increments number by 2:
	4
number *= 3 -> multiplies number by 3:
	6

Exercises with operators

We will be working with operators on all the exercises that I will be proposing in the different posts. In addition, we are familiar with them and they are easy to understand and apply. For this reason, I do not see much sense in dedicating a post specifically to exercises on this topic. My understanding is that raising one here is enough.

Exercise 5

Please correct the errors in the following program to make it works properly.

public Class Multi {

public static void main(String args[]) {

    int a; b, c;
    a=1; b==1 , c=3;

    System.out.println(" b x c =" + b*c);
    System.out.println(" a x c ="  a*c);

    if (a=b){
        System.out.println ("a and b are equals");
    }
    }
}

A possible solution code would be:

public class Multi {

public static void main(String args[]) {

    int a, b, c;
    a=1; b=1 ; c=3;

    System.out.println(" b x c =" + b*c);
    System.out.println(" a x c =" +  a*c);

    if (a==b){
        System.out.println ("a and b are equals");
    }
    }
}

NOTE:

This post is part of the “Java” collection that reproduces the notes of the class that I teach on the subject at ESIC University. You can see the index of this collection here.