Java operators
Created By: chatGPT
In Java, operators are special symbols that perform operations on variables and values. They can be categorized into several types: Arithmetic, Relational, Logical, Bitwise, Assignment, and Unary operators.
Arithmetic operators are used to perform basic mathematical operations. Here are the common arithmetic operators:
int a = 10;
int b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus
Relational operators are used to compare two values and return a boolean result (true or false). The common relational operators are:
boolean isEqual = (a == b); // Equal to
boolean isNotEqual = (a != b); // Not equal to
boolean isGreater = (a > b); // Greater than
boolean isLess = (a < b); // Less than
boolean isGreaterOrEqual = (a >= b); // Greater than or equal to
boolean isLessOrEqual = (a <= b); // Less than or equal to
Logical operators are used to combine multiple boolean expressions. They include:
boolean x = true;
boolean y = false;
boolean andOperator = x && y; // Logical AND
boolean orOperator = x || y; // Logical OR
boolean notOperator = !x; // Logical NOT
Bitwise operators work on the bits and perform bit-by-bit operations. Here are some examples:
int bit1 = 5; // 0101 in binary
int bit2 = 3; // 0011 in binary
int andResult = bit1 & bit2; // Bitwise AND (1)
int orResult = bit1 | bit2; // Bitwise OR (7)
int xorResult = bit1 ^ bit2; // Bitwise XOR (6)
int complement = ~bit1; // Bitwise NOT (-6)
int leftShift = bit1 << 1; // Left Shift (10)
int rightShift = bit1 >> 1; // Right Shift (2)
Assignment operators are used to assign values to variables. Besides the simple assignment (=), there are compound assignments like:
int num = 10;
num += 5; // Equivalent to num = num + 5
num -= 3; // Equivalent to num = num - 3
num *= 2; // Equivalent to num = num * 2
num /= 4; // Equivalent to num = num / 4
num %= 3; // Equivalent to num = num % 3
Unary operators operate on a single operand. The main unary operators in Java include
int counter = 1;
counter++; // Post-increment: counter becomes 2
++counter; // Pre-increment: counter becomes 3
counter--; // Post-decrement: counter becomes 2
--counter; // Pre-decrement: counter becomes 1