Java

Operators in Java

Operators in Java

Java has a variety of basic operators that allow developers to perform various operations on their data. These include arithmetic, assignment, comparison, logical and bitwise operations which are all essential when writing programs in the language. The most commonly used arithmetic operator is an addition (+) which adds two values together while subtraction (-), multiplication (*) and division (/) can be used for multiplying and dividing respectively. Assignment operators such as equals (=) assign values to variables while other types like increment (++) or decrement (--) modify existing ones by either adding or subtracting one from its current value. 

int x = 5; 
int y = 2; 
int result = x + y; // result = 7 
result = x - y; // result = 3 
result = x * y; // result = 10 
result = x / y; // result = 2 
result = x % y; // result = 1 
x++; // x = x + 1; 
y--; // y = y - 1; 


Relational Operators: 

Relational operators are used to compare variables and values. The basic relational operators in Java include: 

>: greater than operator 
<: less than operator 
>=: greater than or equal to operator 
<=: less than or equal to operator 
==: equal to operator 
!=: not equal to operator 

int x = 5; 
int y = 2; 
boolean result = x > y; // result = true 
result = x < y; // result = false 
result = x >= y; // result = true 
result = x <= y; // result = false 
result = x == y; // result = false 
result = x != y; // result = true 


Logical Operators: 

The basic logical operators in Java include: 

● &&: logical and operator 
● ||: logical or operator 
● !: logical not operator 
boolean a = true; 
boolean b = false; 
boolean result = a && b; // result = false 
result = a || b; // result = true 
result = !a; // result = false 
Assignment Operators: 
Assignment operators are used to assign values to variables. The following are the assignment operators: 

● =: simple assignment operator 
● +=: addition assignment operator 
● -=: subtraction assignment operator 
● *=: multiplication assignment operator 
● /=: division assignment operator 
● %=: modulus assignment operator 


int x = 5; 
int y = 2; 
x = y; // x = 2 
x += y; // x = x + y; 
x -= y; // x = x - y; 
x *= y; // x = x * y; 
x /= y; // x = x / y; 
x %= y; // x = x % y; 
 

Top course recommendations for you

    Arduino vs Raspberry Pi
    2 hrs
    Beginner
    7.8K+ Learners
    4.64  (907)
    Joins in SQL
    2 hrs
    Beginner
    11K+ Learners
    4.4  (720)
    Design Thinking for Beginners
    1 hrs
    Beginner
    15.9K+ Learners
    4.38  (2045)
    Database Management System
    1 hrs
    Beginner
    43.6K+ Learners
    4.39  (6072)
    Become a Web Developer
    1 hrs
    Beginner
    18.3K+ Learners
    4.39  (358)
    .NET Fundamentals
    2 hrs
    Beginner
    24.8K+ Learners
    4.42  (2106)