[Go to site: main page, start]

0% found this document useful (0 votes)
22 views11 pages

Java Operators Overview

Uploaded by

Navdeep Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views11 pages

Java Operators Overview

Uploaded by

Navdeep Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Operators

Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while * is also an operator used for
multiplication.

Operators in Java can be classified into 5 types:

Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators

1. Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and
data. For example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly, there are
various other arithmetic operators in Java.

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
[Link]("a + b = " + (a + b));

// subtraction operator
[Link]("a - b = " + (a - b));

// multiplication operator
[Link]("a * b = " + (a * b));

// division operator
[Link]("a / b = " + (a / b));

// modulo operator
[Link]("a % b = " + (a % b));
}
}

Output

a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2

In the above example, we have used +, -, and * operators to compute addition,


subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division operator.

If we use the division operator with two integers, then the resulting quotient will
also be an integer. And, if one of the operands is a floating-point number, we will
get the result will also be in floating-point.
In Java,

(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5

% Modulo Operator

The modulo operator % computes the remainder. When a = 7 is divided by b = 4,


the remainder is 3.

Note: The % operator is mainly used with integers.

2. Java Assignment Operators


Assignment operators are used in Java to assign values to variables. For
example,

int age;
age = 5;

Here, = is the assignment operator. It assigns the value on its right to the variable
on its left. That is, 5 is assigned to the variable age.

Let's see some more assignment operators available in Java.

Operator Example Equivalent to


= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

Example 2: Assignment Operators

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

// create variables
int a = 4;
int var;

// assign value using =


var = a;
[Link]("var using =: " + var);

// assign value using =+


var += a;
[Link]("var using +=: " + var);

// assign value using =*


var *= a;
[Link]("var using *=: " + var);
}
}

Output

var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators


Relational operators are used to check the relationship between two operands.
For example,

// check if a is less than b


a < b;
Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false.


Operator Description Example
== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
>= Greater Than or
Equal To 3 >= 5 returns false
<= Less Than or
Equal To 3 <= 5 returns true

Example 3: Relational Operators

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

// create variables
int a = 7, b = 11;

// value of a and b
[Link]("a is " + a + " and b is " + b);

// == operator
[Link](a == b); // false

// != operator
[Link](a != b); // true

// > operator
[Link](a > b); // false

// < operator
[Link](a < b); // true

// >= operator
[Link](a >= b); // false
// <= operator
[Link](a <= b); // true
}
}

Note: Relational operators are used in decision making and loops.

4. Java Logical Operators


Logical operators are used to check whether an expression is true or false. They
are used in decision making.

Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

|| (Logical expression1 || true ifeither expression1 or


OR) expression2 expression2 is true

! (Logical !expression true if expression is false and vice


NOT) versa

Example 4: Logical Operators

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

// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false

// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false
// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}

Working of Program
(5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.

(5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.

(5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.

(5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true.

(5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false.

!(5 == 3) returns true because 5 == 3 is false.

!(5 > 3) returns false because 5 > 3 is true.

5. Java Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.

Different types of unary operators are:

Operator Meaning

+ Unary plus: not necessary to use since numbers are positive without using
it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
! Logical complement operator: inverts the value of a boolean

Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively.


++ increases the value of the operand by 1, while -- decrease it by 1. For
example,

int num = 5;

// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.

Example 5: Increment and Decrement Operators


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

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
[Link]("Value of a: " + a);

// increment operator
result1 = ++a;
[Link]("After increment: " + result1);

[Link]("Value of b: " + b);

// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
Run Code
Output

Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11

In the above program, we have used the ++ and -- operator as prefixes (++a,
--b). We can also use these operators as postfix (a++, b++).

There is a slight difference when these operators are used as prefix versus when
they are used as a postfix.

To learn more about these operators, visit increment and decrement operators.

6. Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits. For
example,

Bitwise complement Operation of 35

35 = 00100011 (In Binary)

~ 00100011
________
11011100 = 220 (In decimal)
Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).

The various bitwise operators present in Java are:

Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
These operators are not generally used in Java. To learn more, visit Java Bitwise
and Bit Shift Operators.

Other operators
Besides these operators, there are other additional operators in Java.

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular
class. For example,

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

String str = "Programiz";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
[Link]("Is str an object of String? " + result);
}
}

Output

Is str an object of String? true


Here, str is an instance of the String class. Hence, the instanceof operator
returns true. To learn more, visit Java instanceof.

Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else
statement. For example,

variable = Expression ? expression1 : expression2


Here's how it works.

If the Expression is true, expression1 is assigned to the variable.


If the Expression is false, expression2 is assigned to the variable.

Let's see an example of a ternary operator.

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

int februaryDays = 29;


String result;

// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
[Link](result);
}
}

Output

Leap year
In the above example, we have used the ternary operator to check if the year is a
leap year or not. To learn more, visit the Java ternary operator.

Common questions

Powered by AI

In Java, operator precedence determines the order in which operators are evaluated in expressions with multiple operators. Arithmetic operators generally have higher precedence than logical operators, meaning arithmetic operations like addition or multiplication will be evaluated before logical evaluations unless parentheses are used to explicitly dictate precedence. For example, in the expression `a + b == c && d > e`, `a + b` is computed first due to higher precedence, followed by comparison, and then the logical AND operation .

Assignment operators in Java, such as +=, -=, *=, enable concise code by combining basic arithmetic operations with assignment. These operators update the variable directly without requiring separate operations, which streamlines code and reduces redundancy. For instance, `a += b` is shorthand for `a = a + b`, directly modifying `a`. This is particularly helpful in loops or iterations where compound updates to variables are frequent, enhancing code readability and efficiency .

The modulo operator (%) in Java computes the remainder of a division operation between two operands. It's significant for operations that require wrapping or cyclic behaviors, such as determining evenness or oddness (e.g., `number % 2`), and is often used in applications like clock arithmetic to keep time within bounds (e.g., `hours % 24` for a 24-hour format). It’s crucial in algorithms where remainder calculations help in distributing items evenly or in cyclic patterns, such as round-robin scheduling .

The bitwise NOT operator (~) in Java inverts the value of each bit in a binary representation of an integer, turning all 0s to 1s and all 1s to 0s. For example, if the integer 35 is represented as 00100011 in binary, applying the bitwise NOT operator will result in 11011100, which corresponds to -36 in decimal representation due to two's complement encoding .

Relational operators in Java, including ==, !=, >, <, >=, <=, are used to compare two operands and return a boolean value indicating whether the specified relationship holds. They form the backbone of decision-making structures such as `if-else` statements and loops by establishing conditions that control the flow of execution. They are essential for developing logic that relies on comparisons, enabling programs to adaptively respond to different data scenarios .

The instanceof operator in Java is used to verify whether an object is an instance of a specific class, enabling type-safe operations and casting. It's particularly useful in polymorphic code where it ensures that operations valid only for certain types are attempted, preventing ClassCastException. For instance, before downcasting base class references, you would check with instanceof to avoid runtime errors .

Logical operators in Java, such as && (logical AND), || (logical OR), and ! (logical NOT), are used to construct complex boolean expressions. They are fundamental in control flow constructs, such as `if` statements and loops, to define conditions that control the execution flow of a program. For instance, an `if` statement might use `&&` to check two conditions simultaneously and proceed only if both are true. Logical operators provide concise ways to represent multiple condition checks in decision-making logic .

In Java, arithmetic operators like +, -, *, and / perform arithmetic operations on variables. The division operator (/) behaves differently based on operand types: with integers, it performs integer division, discarding any remainder and returning an integer quotient (e.g., 9/2 results in 4). When at least one operand is a floating-point number, the division yields a floating-point result (e.g., 9.0/2 results in 4.5), respecting floating-point arithmetic rules .

The ternary operator in Java acts as a shorthand for the if-then-else statement, allowing a single line expression that evaluates a condition and assigns the result of one of two expressions based on that condition. For example, in determining if a year is a leap year: `int februaryDays = 29; String result = (februaryDays == 28) ? "Not a leap year" : "Leap year";`. Here, if `februaryDays` equals 28, 'Not a leap year' is assigned to `result`, otherwise 'Leap year' is assigned .

The prefix (++a, --a) and postfix (a++, a--) increment and decrement operators differ in when they apply their change to the operand. The prefix increment/decrement operator changes the operand before the expression in which they appear is evaluated, while the postfix version applies the change after the expression is evaluated. Prefix operators are often used in comparison loops for immediate changes, whereas postfix operators are typically used when the prior value is needed in the current context before the change .

You might also like