Skip to content

Operators

The primary purpose of a program is to manipulate stored data. Out of the package, Java offers operators for basic data manipulation capabilities for primitive data types.

In this module, we will cover the following topics:

  • What are Operators
  • Assignment Operators
  • Arithmetic Operators
  • Unary Operators
  • Compound Assignment Operators
  • Logical Operators
  • Relational Operators
  • Ternary Operator



› What are Operators

Operators are special symbols that carry out operations ( manipulations ) on data values. It allows us to manipulate data stored in variables and use its result.

Code Sample
1
2
3
4
5
6
7
// data stored in variable
int a = 10;   
int b = 20;  

//   +    addition operator 
int sum = a + b;   
System.out.println(  sum );   // prints:  30 

Because of the addition operator at line 6, we were able to get new data(30) from two existing data ( 10 and 20 ).

Here is the full list of operators we will cover in this note:

Operators Symbol What it does
Assignment Operator = assigns data to a variable
Arithmetic Operator +, -, /, *, % basic math calculations
Compound Assignment Operator +=, -=, /=, *=, %= updates the content of a variable
Unary Operators ++, -- updates the content of a variable by 1
Relational Operators >, <, >=, <=, ==, != compares two numbers
Logical Operators &&,ll, ! manipulates boolean data
logical assignment operator (condition)? assigns the data value based on a condition

Note that the operators we will touch base work on the following primitive data types:

  • int
  • double
  • char
  • boolean



› Assignment Operator

Symbol: =

Assignment operators are used for assigning data values to variables. The assignment operator gives the data value on its right to the variable on its left.

assignment operator

Note right side of the assignment operator can be any of the following as long as it results in a single data value and data value and the variable data type must match.

  • data value
  • a non-empty variable
  • a method call that returns a data value

Please try this code sample on your test case method:

Code Sample
int num;       // empty integer varialbe named 'num'
num = 90;      // variable num contains 90 
num = 0;       // variable num contains 0
num = -80;     // variable num contains -80

int age = 29;  // creating integer variable named 'age'
num = age;     // variable num contains 29 from variable age

// prints 29 to the console
System.out.println(num);



› Arithmetic Operator

Arithmetic operators are used for performing basic mathematical calculations like addition, subtraction, and multiplication.

Symbols What it does
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus, Gets remainder

Please try this code sample on your test case method:

Code Sample
int num1 = 10;
int num2 = 20;

//   +  Addition 
int sum = num1 + num2;
System.out.println(sum);  //  30

//    -  Subtraction Operator
int sub = num1 - num2;
System.out.println(sub);  //  -10

//    *  Multiplication Operator
int multi = num1 * num2;
System.out.println(multi); // 200

//    /  Division Operator
int div = num2 / num1;
System.out.println(div);  // 2

// note that you cannot divide any number by zero, uncomment this 
int err = num2 / 0;  


int ret = num1 / 3;  

// you will get 3, not 3.33333 
// since it is integer data type division
System.out.println(ret); 

// use double data type if precision is priority
double x = 10.0;
double y = 3.0;
double ans = x / y;  
System.out.println(ans);  // 3.3333333335

//    %  Remainder Operator
// This operator will give us remainder of dividing two numbers
int rem = num1 % 3;
System.out.println(rem); // 1

Modulus Operator

The modulus operator (% ) is especially useful to do simple things like figuring out if a given number is even or odd and more complex tasks like detecting a cycle.

If you mod any integer number with 2, you will get either 0 or 1 as an answer, if the answer is:

  • 0  :  the number is Even number
  • 1  :  the number is Odd number



› Unary Operators

Also known as Increment & Decrement operator. It is used for updating the numerical variable's content by one. The update operation is either added by one or subtracted by one.

Symbols What it does
++ Update the numerical variable content by adding 1
-- Update the numerical variable content by subtracting 1

It has two different modes of usage known as prefix mode and postfix mode:

1
2
3
int number = 10;
System.out.println(number++); // displays 10
System.out.println(number);   // displays 11

The content of the integer variable will be first displayed to the console, and afterward, its content will be incremented by 1.

int number = 10;
System.out.println(++number); // displays 11

The value of the integer variable number will be incremented by one first, and then its content will be displayed to the console.

Please try this code sample on your test case method:

Code Sample
int myInt = 5;
++myInt;      // myInt becomes 6
myInt++;      // myInt becomes 7
--myInt;      // myInt becomes 6
myInt--;      // myInt becomes 5

System.out.println(myInt--); // print 5, then decremente myInt by 1
System.out.println(myInt );  // print 4
System.out.println(++myInt); // increment myInt by 1, then print 5

int x = 10;
int y = 20;

//         9  + 20
int ans = --x + y++;
System.out.println(y);    // 21
System.out.println(ans);  // 29



› Content Updater

Also known as a compound assignment operator, it simplifies the syntax of variable content updating code. We can use this for primitive data types and reference data types like String.

For numerical data types such as int, double, char:

Symbols What it does Example Equivalent to
+= update by addition x+=5 x = x + 5
-= update by subtraction x-=5 x = x - 5
*= update by multiplication x*=5 x = x * 5
/= update by division x/=5 x = x / 5
%= update by modulus x%=5 x = x % 5

For text data types such as String:

Symbols What it does Example Equivalent to
+= update by concatenation s+="hello" s = s + "hello"

Please try this code sample on your test case method:

Code Sample
// +=   : update by addition
// -=   : update by subtraction
// *=   : update by multiplication
// /=   : update by division
// %=   : update by modular

// --- Example
int number = 10;

// update by addition
number += 20;
System.out.println(number);  // prints: 30

// update by subtraction
number -= 15;
System.out.println(number);  // prints: 15

// update by multiplication
number *= 2;
System.out.println(number);  // prints: 30

// update by division
number /= 5; 
System.out.println(number);  // prints: 6

// update by modular
number %= 2;
System.out.println(number);  // prints: 0



› Relational Operators

It is used for comparing two numerical data types. The result of this operator is a boolean data value, true or false, depending on comparisons.

Symbols Description Example ( same results fordouble,char)
== equal to 5 == 3 🠚 false
4 == 4 🠚 true
!= not equal to 5 != 3 🠚 true
4 != 4 🠚 false
> greater than 5 > 3 🠚 true
4 > 4 🠚 false
4 > 24 🠚 false
>= greater than or equal to 5 >= 3 🠚 true
4 >= 4 🠚true
4 >= 24 🠚 false
< less than 5 < 3 🠚 false
4 < 4 🠚 false
4 < 24 🠚 true
<= less than or equal to 5 <= 3 🠚 false
4 <= 4 🠚 true
4 <= 24 🠚 true

Please try this code sample on your test case method:

Code Sample
int age = 29;
int limit = 30;
boolean result;

// equal to
result = age == limit;
System.out.println(result); // false

// not equal to
result = age != limit;
System.out.println(result); // true

// greater than
result = age > limit;
System.out.println(result); // false

// less than
result = age < limit;
System.out.println(result); // true

// greater than or equal to
result = age >= limit;
System.out.println(result); // false

// less than or equal to
result = age <= limit;
System.out.println(result);  // true



› Logical Operators

Used for processing logical expressions, which is the basis for decision-making in the program. Works on two boolean data values and produces another boolean data value as a result.

Syntax:

[Boolean Data]  [logical operators]  [Boolean Data]  🠚  [Boolean Data] 

Operator Symbol Description Example
ll true if either of the boolean value is true false ll true 🠚 true
&& true if all of the boolean value is true false && true 🠚 false
! inverts the value of a boolean value !true 🠚 false

Please try this code sample on your test case method:

Code Sample
// --- Types of boolean operators ---
//      ||     OR
//      &&     AND
//      !      NOT
// ----------------------------------

// AND operator are greedy
// it will only give us true back if both operands are true
System.out.println( true  && true   ); //true
System.out.println( true  && false  ); //false
System.out.println( false && true   ); //false
System.out.println( false && false  ); //false


// OR operator are flexible, 
// it will only give us false if both operands are false
System.out.println( true  || true  ); //true
System.out.println( true  || false ); //true
System.out.println( false || true  ); //true
System.out.println( false || false ); //false


// NOT operator just flips the boolean value
System.out.println( !true  ); //false
System.out.println( !false ); //true


// One Complete Example
boolean isCold    = true;
boolean isSnowing = false;
System.out.println(  !(isCold && isSnowing)  ); // true



› Ternary Operator

Also called conditional assignment operator, it is used for assigning data based on comparison.

symbol:   ( )? :

The conditional operator or ternary operator is shorthand for the if-then-else statement. Its syntax is as follows.

variable = (condition)? expression1 : expression2

  • If the condition is true,   then expression1 is assigned to the variable.
  • If the condition is false, then expression2 is assigned to the variable.
Code Sample
1
2
3
4
5
int februaryDays = 29;
String result;

result =  (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);  // displays:  Leap year