Java Operators

Operators in Java

In Java, operators are fundamental building blocks that allow you to perform various operations on data, such as arithmetic calculations, comparisons, and logical evaluations. Let’s explore some of the essential operators in Java and understand how they work.

Arithmetic Operators:

Operator Description Example Output
+ Addition int result = 5 + 3; 8
Subtraction int result = 7 – 2; 5
* Multiplication int result = 4 * 6; 24
/ Division int result = 10 / 2; 5
% Modulus (Remainder) int result = 10 % 3; // 3 divide by 10 so remainder is 1 1
++ Increment by 1 int a = 5;
a++;
a becomes 6
Decrement by 1 int b = 7;
b–;
b becomes 6

Comparison Operators:

In cases where you want to define a variable i with a comparison operator then we will use them as follows
The comparison operator will give a condition and the output is true or false

Operator Description Example
== Equal to. If I =5 (i == 5)
!= Not equal to, if i not equal to 2 (i != 2);
> Greater than, if i is greater than 6 (i > 6);
< Less than, if i is less than 2 (i < 2);
>= If i is Greater than or equal to 2 (i >= 2);
<= If i is Less than or equal to 3 (i <= 3);

Logical Operators:

The logical operator will give a condition and the output is true or false

Operator Description Example
&& Logical AND. If the person is equal to Male and the age is equal to 21 person.equals(“male”) && age == 21
|| Logical OR. If the person is male or female person.equals(“male”)
! Logical NOT (Negation). If a person is not equal to a male !person.equals(“male”)

Assignment Operators:

These operators modify the value of variables directly.

Expression Description Code Example Output
int x = 5; Assigns the value 5 to variable x. int x = 5; x = 5
x += 3; Adds 3 to the current value of x. x += 3; x = 8(5+3)
x -= 2; Subtracts 2 from the current value of x. x -= 2; x = 6(8-2)
x *= 4; Multiplies the current value of x by 4. x *= 4; x = 24(6*4)
x /= 2; Divides the current value of x by 2. x /= 2; x = 12(24\2)
x %= 3; The current value of x is divided by 3 and the remainder is 0. x %= 3; x = 0(12)

Conditional Operator:

Structure:

condition ? trueResult : falseResult;

Condition Expression Explanation Example Result
Comparing Marks
True Condition ?
trueResult :
falseResult
If the condition is true, the result is trueResult. int5 > 3 ? “Yes” : “No” “Yes”
False condition ?
trueResult :
falseResult
If the condition is false, the result is falseResult. int5 < 3 ? "Yes" : "No" “No”
Comparing integers marksofenglish >
marksofscience ?
marksofenglish :
marksofscience
Compares two integers and returns a value if true it will take the first values other if false it will take the second value.. For example : marksofenglish = 10 ; marksofscience = 20; marksofenglish>marksofscience? marksofenglish : marksofscience //in the above expression marks of english is first value and marks of science is second value since 10 marksofenglish is not greater then marks of science it will store second value. in the expression marks of english is first value and marks of science is second value since 10 marksofenglish is not greater then marks of science it will store second value. 20
Checking null values x != null ? x.toString() : “null” Checks if a variable is null and returns its string value or “null”. string str = null; str != null ? str : “null” “null”
Even or odd number num % 2 == 0 ? “Even” : “Odd” Checks if a number is even or odd and returns the result. 7 % 2 == 0 ? “Even” : “Odd” “Odd”
Age check age >= 18 ? “Adult” : “Minor” Determines if a person is an adult or a minor based on age. int age = 20; age >= 18 ? “Adult” : “Minor” “Adult”
Assigning values Int value =privatecustomer ? 1 : 0; Assigns a value based on a Boolean condition. bool privatecustomer =false ; int value =privatecustomer ? 1 : 0; //if privatecustomer is true then int value is equal to 1. If privatecustomer is false then int value is 0 bool privatecustomer =false ; int value =privatecustomer ? 1 : 0; 0
Default value input != null ? input : “default” Uses the null-coalescing operator to provide a default value if input is null. String input = null; String result = input != null ? input : “default”; “default”

Example 1: Maximum of Two Numbers

public class Program {
   public static void maximum() {
     int marksofenglish = 10;
      int marksofscience = 20;
      int result = marksofenglish > marksofscience ? marksofenglish : marksofscience;
   System.out.println(result);
 }

    public static void main(String[] args) {
    maximum();
  }
}

Explanation:

public class Program {
public static void maximum() {
int marksofenglish = 10; // This declares an integer variable named marksofenglish and sets its value to 10.
int marksofscience = 20;
// This declares another integer variable named marksofscience and sets its value to 20.
int result = marksofenglish > marksofscience ? marksofenglish : marksofscience;
// This line uses a conditional (ternary) operator to find the larger of the two numbers.
// It checks if marksofenglish is greater than marksofscience. If true, result is set to marksofenglish.
// If false, result is set to marksofscience. In this case, marksofscience is larger, so the result will be 20.

System.out.println(result);
// This line prints the value of the result to the console. It will print “20”.
}
public static void main(String[] args) {
maximum();
// This line calls the maximum method, which then executes the code inside that method.
}
}

Example 2: Age Check

public class Program {
public static void ageCheck() {
int age = 20;
String status = age >= 18 ? “Adult” : “Minor”;
System.out.println(status);
}

public static void main(String[] args) {
ageCheck();
}
}

Explanation:

public class Program {
public static void ageCheck() {
int age = 20;
// This declares an integer variable named age and sets its value to 20.

String status = age >= 18 ? “Adult” : “Minor”;
// This line uses a conditional (ternary) operator to determine if the person is an adult or a minor based on the age value.
// It checks if age is greater than or equal to 18. If true, status is set to “Adult”. If false, status is set to “Minor”.
// In this case, the age is 20, so the status will be “Adult”.

System.out.println(status);
// This line prints the status to the console.
}
public static void main(String[] args) {
ageCheck();
// This line calls the ageCheck method.
}
}

Example 3: Boolean to Integer

public class Program {
public static void assignValues() {
boolean privateCustomer = false;
int value = privateCustomer ? 1 : 0;
System.out.println(value);
}

public static void main(String[] args) {
assignValues();
}}

Explanation:

public class Program {
public static void assignValues() {
boolean privateCustomer = false;
// This declares a boolean variable named privateCustomer and sets its value to false.

int value = privateCustomer ? 1 : 0;
// This line uses a conditional (ternary) operator. It checks if privateCustomer is true or false.
// If true, value is set to 1. If false, value is set to 0. In this case, privateCustomer is false, so the value will be 0.

System.out.println(value);
// This line prints the value to the console.
}

public static void main(String[] args) {
assignValues();
// This line calls the assignValues method.
}
}

Example 4: Null Check with Default Value

public class Program {
public static void assignValues() {
boolean privateCustomer = false;
int value = privateCustomer ? 1 : 0;
System.out.println(value);
}

public static void main(String[] args) {
assignValues();
}}

Explanation:

public class Program {
public static void assignDefault() {
String input = null;
// This declares a string variable named input and sets its value to null.

String result = input != null ? input : “default”;
// This line uses a conditional (ternary) operator. It checks if input is not null.
// If true, result gets the same value as input. If false, result gets the default value as “default”.
// In this case, input is null, so the result will be “default”.

System.out.println(result);
// This line prints the result to the console.
}
public static void main(String[] args) {
assignDefault();
// This line calls the assignDefault method.
}
}

Tasks:
1. Arithmetic Operators
Write a Java program to perform the following operations and print the results:
     Addition: 8 + 4
    Subtraction: 15 – 7
    Multiplication: 6 * 9
    Division: 20 / 4
    Modulus: 19 % 4
2. Create a variable num with a value of 10. Use the increment operator to increase its value by 1, then print the result. Next, use the decrement operator to decrease its value by 1, and print the result.
3. Comparison Operators
Write a Java program to compare two integers, a = 15 and b = 20. Use all the comparison operators (==, !=, >, <, >=, <=) and print the results of each comparison.
4. Logical Operators
Create two boolean variables, isStudent and isMember. Set isStudent to true and isMember to false. Write a Java program to evaluate and print the following logical expressions:
    isStudent && isMember
    isStudent || isMember
    !isStudent
    Assignment Operators
5. Start with an integer variable x initialized to 10. Use the assignment operators to perform the following operations and print the value of x after each step:
    Add 5 to x
    Subtract 3 from x
    Multiply x by 2
    Divide x by 4
    Calculate the modulus of x by 3
6. Conditional Operator
Write a Java program using the conditional operator to:
    Compare two integers a = 8 and b = 12, and print which one is greater.
    Check if a given number num = 7 is even or odd and print the result.
    Determine if a person with age = 16 is an adult or a minor and print the result.
    Assign a value to an integer variable value based on a boolean variable isValid.
    Create a string variable name that is null. Use the null-coalescing operator to assign a default value “Unknown” if name is null, and print the result.

Course Video

YouTube Reference :