Pages

Saturday, May 25, 2024

Operators in Java

Java operators with examples:

1. Arithmetic Operators:

+ (Addition): Adds two operands.

int a = 5;

int b = 3;

int sum = a + b; // sum will be 8


- (Subtraction): Subtracts the second operand from the first.

int difference = a - b; // difference will be 2


* (Multiplication): Multiplies two operands.

int product = a * b; // product will be 15


/ (Division): Divides the first operand by the second. Be aware of integer division which truncates decimals.

int quotient = a / b; // quotient will be 1 (integer division)

double dQuotient = (double) a / b; // dQuotient will be 1.6666... (cast to double for decimal result)


% (Modulo): Returns the remainder after division.

int remainder = a % b; // remainder will be 2 (5 divided by 3 leaves a remainder of 2)


2. Assignment Operators:

= (Assignment): Assigns a value to a variable.

int x = 10;

Compound assignment operators (e.g., +=, -=, *=, /=): Combine assignment with the specified operation.

x += 5; // equivalent to x = x + 5; (x becomes 15)

x *= 2; // equivalent to x = x * 2; (x becomes 30)


3. Relational Operators:

== (Equal to): Checks if two operands are equal.

boolean isEqual = a == b; // isEqual will be false

!= (Not equal to): Checks if two operands are not equal.

boolean isNotEqual = a != b; // isNotEqual will be true

< (Less than): Checks if the first operand is less than the second.

boolean isLessThan = a < b;  // isLessThan will be false

> (Greater than): Checks if the first operand is greater than the second.

boolean isGreaterThan = a > b; // isGreaterThan will be true

<= (Less than or equal to): Checks if the first operand is less than or equal to the second.

boolean isLessOrEqualTo = x <= 30; // isLessOrEqualTo will be true (x is 30)

>= (Greater than or equal to): Checks if the first operand is greater than or equal to the second.

boolean isGreaterThanOrEqualTo = x >= 20; // isGreaterThanOrEqualTo will be true (x is 30)


4. Logical Operators:

&& (Logical AND): Returns true if both operands are true, false otherwise.

boolean isEven = (x % 2 == 0) && (x > 0); // isEven will be false (x is even but not greater than 0)

|| (Logical OR): Returns true if at least one operand is true, false otherwise.

boolean isPositive = (x > 0) || (x == 0); // isPositive will be true (x is positive)

! (Logical NOT): Inverts the logical state of the operand.

boolean isNegative = !isPositive; // isNegative will be false (x is positive)l

These are just a few examples. Java offers a variety of operators for different purposes.

No comments:

Post a Comment