0% found this document useful (0 votes)
129 views9 pages

Java Arithmetic and Logical Operators

The document provides an overview of Java operators, focusing on arithmetic, equality, relational, conditional, logical, and ternary operators. It explains the functionality and usage of each operator with code examples. Additionally, it highlights the importance of these operators in performing mathematical operations and making decisions in Java programming.

Uploaded by

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

Java Arithmetic and Logical Operators

The document provides an overview of Java operators, focusing on arithmetic, equality, relational, conditional, logical, and ternary operators. It explains the functionality and usage of each operator with code examples. Additionally, it highlights the importance of these operators in performing mathematical operations and making decisions in Java programming.

Uploaded by

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

Java Operators

Operators are symbols that perform operations on variables and values.

Introduction

Arithmetic operators in Java are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulus. These operators are fundamental
for manipulating numerical data and are frequently used in Java programming.

What are Arithmetic Operators?

Arithmetic operators are symbols used within expressions to perform basic mathematical
operations. They operate on numerical values (constants and variables) and return a single
numerical value.

Types of Arithmetic Operators in Java

Java provides the following arithmetic operators:

1. Addition (+)

2. Subtraction (-)

3. Multiplication (*)

4. Division (/)

5. Modulus (%)

6. Increment (++)

7. Decrement (--)

1. Addition (+)

The addition operator adds two operands.

Example:

public class AdditionExample {


public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
[Link]("Sum: " + sum); // Output: Sum: 30
}
}

2. Subtraction (-)

The subtraction operator subtracts the second operand from the first.

Example:

public class SubtractionExample {


public static void main(String[] args) {
int a = 20;
int b = 10;
int difference = a - b;
[Link]("Difference: " + difference); // Output:
Difference: 10
}
}

3. Multiplication (*)

The multiplication operator multiplies two operands.

Example:

public class MultiplicationExample {


public static void main(String[] args) {
int a = 10;
int b = 20;
int product = a * b;
[Link]("Product: " + product); // Output: Product: 200
}
}

4. Division (/)

The division operator divides the first operand by the second. Note that
division by zero will throw an ArithmeticException.

Example:

public class DivisionExample {


public static void main(String[] args) {
int a = 20;
int b = 10;
int quotient = a / b;
[Link]("Quotient: " + quotient); // Output: Quotient: 2
}
}

5. Modulus (%)

The modulus operator returns the remainder when the first operand is
divided by the second.

Example:

public class ModulusExample {


public static void main(String[] args) {
int a = 20;
int b = 3;
int remainder = a % b;
[Link]("Remainder: " + remainder); // Output: Remainder: 2
}
}

6. Increment (++)

The increment operator increases the value of an operand by 1. It can be


used as a prefix (++a) or a suffix (a++).

Example:

public class IncrementExample {


public static void main(String[] args) {
int a = 10;
++a; // Prefix increment
[Link]("Prefix Increment: " + a); // Output: Prefix
Increment: 11

a = 10;
a++; // Suffix increment
[Link]("Suffix Increment: " + a); // Output: Suffix
Increment: 11
}
}

7. Decrement (--)

The decrement operator decreases the value of an operand by 1. It can be


used as a prefix (--a) or a suffix (a--).
Example:

public class DecrementExample {


public static void main(String[] args) {
int a = 10;
--a; // Prefix decrement
[Link]("Prefix Decrement: " + a); // Output: Prefix
Decrement: 9

a = 10;
a--; // Suffix decrement
[Link]("Suffix Decrement: " + a); // Output: Suffix
Decrement: 9
}
}

Equality, Relational, and Conditional Operators in Java

1. The Equality and Relational Operators

The equality and relational operators determine if one operand is greater than, less than, equal
to, or not equal to another operand. The majority of these operators will probably look familiar
to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive
values are equal.

The following program, ComparisonDemo, tests the comparison operators:

class ComparisonDemo {

public static void main(String[] args) {


int value1 = 1;

int value2 = 2;

if (value1 == value2)

[Link]("value1 == value2");

if (value1 != value2)

[Link]("value1 != value2");

if (value1 > value2)

[Link]("value1 > value2");

if (value1 < value2)

[Link]("value1 < value2");

if (value1 <= value2)

[Link]("value1 <= value2");

2. The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.

&& Conditional-AND

|| Conditional-OR

Example:

class ConditionalDemo1 {

public static void main(String[] args) {

int value1 = 1;
int value2 = 2;

if ((value1 == 1) && (value2 == 2))

[Link]("value1 is 1 AND value2 is 2");

if ((value1 == 1) || (value2 == 1))

[Link]("value1 is 1 OR value2 is 1");

Logical Operators in Java

Logical Operators in Java check whether the expression is true or false. It is generally used for
making any decisions in Java programming. Not only that but Jump statements in Java are also
used for checking whether the expression is true or false. It is generally used for making any
decisions in Java programming.

Operators Example Meaning

&& [ logical AND ] expression1 && expression2 (true) only if both of the expressions are true

|| [ logical OR ] expression1 || expression2 (true) if one of the expressions in true

! [ logical NOT ] !expression (true) if the expression is false and vice-versa

Logical Operators in Java Example

class Main

public static void main(String[] args)

{
// && operator

[Link]((6 > 3) && (8 > 6)); // true

[Link]((6 > 3) && (8 < 6)); // false

// || operator

[Link]((6 < 3) || (8 > 6)); // true

[Link]((6 > 3) || (8 < 6)); // true

[Link]((6 < 3) || (8 < 6)); // false

// ! operator

[Link](!(6 == 3)); // true

[Link](!(6 > 3)); // false

Ternary Operators in Java


The only conditional operator that accepts three operands is the ternary operator in Java. Java
programmers frequently use it as a one-line alternative to the if-then-else expression. The
ternary operator can be used in place of if-else statements, and it can even be used to create
switch statements with nested ternary operators. The conditional operator uses less space and
aids in writing if-else statements as quickly as possible even if it adheres to the same algorithm
as an if-else statement
Syntax:

expression1 ? expression2 : expression3


(condition) ? (return if true) : (return if false);

Here, expression1 can be any expression that evaluates to a boolean value.


If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.

public class TernaryOperatorExample {

public static void main(String[] args) {

int num1 = 10;

int num2 = 20;


// Using the ternary operator to find the maximum of two numbers

int max = (num1 > num2) ? num1 : num2;

[Link]("The maximum number is: " + max);

Ex-WAP using ternary operator to check if a number


is even or odd:
int number = 10;
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link](result); // Prints "Even"

The ternary operator can also be used to assign values to variables. The following example
shows how to use the ternary operator to assign the value "true" to the variable isAdult if the
user's age is greater than or equal to 18, and the value "false" otherwise: Java

int age = 20;

boolean isAdult = (age >= 18) ? true : false;

[Link](isAdult); // Prints "true"

Common questions

Powered by AI

Arithmetic operators can combine with relational operators to evaluate complex expressions by performing calculations and using the results in conditional checks simultaneously. For instance, one might calculate an average (using arithmetic operators) and then compare it using relational operators to determine a qualifying condition or threshold. This method streamlines operations by avoiding intermediate variables and directly integrating calculations into decision constructs .

The universal pattern in using conditional and logical operators involves structuring expressions that combine relational checks into concise decision-making logic. This pattern improves programming efficiency by reducing code redundancy, minimizing branching through short-circuiting, and streamlining decision-making processes in logical flow controls, leading to more readable and maintainable code, optimizing both the verification process and execution speed .

Java developers can use nested ternary operators to evaluate multiple conditions compactly within a single expression. This technique allows for optimization by combining multiple branches of if-else logic into clearer, compact syntax. However, caution is necessary to maintain readability, as excessive nesting can lead to complex, less maintainable code. Appropriate application can simplify otherwise verbose conditionals efficiently .

In Java, increment (++) and decrement (--) operators adjust a variable’s value by 1. The prefix version (++a, --a) changes the variable’s value before it’s used in an expression, whereas the suffix version (a++, a--) uses the variable’s current value in an expression before the increment/decrement occurs, affecting subsequent operations .

The modulus operator (%) returns the remainder of a division operation, useful for determining divisibility, implementing cyclical counters, or handling tasks requiring rotation over a fixed range. It's particularly beneficial in scenarios like checking even or odd numbers or redistributing items evenly, as it provides direct access to residual values after division .

Logical operators (&&, ||, !) evaluate boolean expressions, crucial for decision-making in programs by combining multiple conditions. The short-circuiting behavior means for &&, evaluation stops if the first operand is false, and for ||, it stops if the first operand is true, preventing unnecessary calculations or error-prone operations .

Equality operators (==, !=) in Java check if two operands are equal or not, whereas relational operators (> ,<, >=, <=) compare numerical values to determine their relation. The primary use of these operators is in control structures to make decisions based on value comparisons, allowing fine-tuned control flow based on data conditions .

Arithmetic operators in Java perform operations like addition, subtraction, multiplication, division, and modulus on numerical values, returning a single numerical result. These operators are crucial for data manipulation and mathematical calculations in Java. They allow developers to write efficient code to perform arithmetic operations on variables and constants .

The division operator in Java can cause ArithmeticException when dividing by zero. Developers must ensure the denominator is not zero before performing division operations. Checking the value of the divisor or using try-catch blocks to handle exceptions can prevent runtime errors .

Java's ternary operator is beneficial in scenarios requiring concise syntax for simple conditional assignments or operations. It allows small conditional checks to be written inline, reducing code length and improving readability for straightforward operations, such as variable assignment based on a condition. For example, checking if a number is even or odd or assigning a value based on age can be more concise with the ternary operator compared to if-else statements .

You might also like