Java operators are symbols that perform operations on operands—constants or variables—enabling computation, comparision, and assignment. Expressions combine operands and operators folllowing Java syntax rules; for example, a + b is an arithmetic expression where + is the operator.
Arithmetic Operators
The core arithmetic operators are +, -, *, /, and %.
+,-,*: Behave identically to standard mathematics./: Performs division with type-sensitive behavior:- Integer division truncates fractional parts:
10 / 3yields3. - Floating-point operands preserve precision:
10.0 / 3yields3.3333333333333335.
- Integer division truncates fractional parts:
%: Computes the remainder after integer division (e.g.,10 % 3→1). Useful for parity checks:n % 2 == 1indicates oddness.
Numeric Digit Extraction Example
To decompose a three-digit integer in to its digits:
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit number: ");
int num = input.nextInt(); // e.g., 789
int units = num % 10; // 9
int tens = (num / 10) % 10; // 8
int hundreds = num / 100; // 7
System.out.printf("Units: %d, Tens: %d, Hundreds: %d%n", units, tens, hundreds);
Type Conversion in Java
Implicit (Widening) Conversion
Occurs automatically when assigning a smaller-type value to a larger-type variable. Java promotes types based on range hierarchy: byte < short < int < long < float < double. Additionally:
- Operands of type
byte,short, orcharare promoted tointbefore arithmetic. - In mixed-type expressions, all operands are promoted to the largest type present.
Explicit (Narrowing) Conversion
Required when assigning a larger-type value to a smaller-type variable. Uses cast syntax: (TargetType) value. May lose precision or overflow:
double pi = 3.14159;
int truncated = (int) pi; // yields 3
String Concatenation with +
When + involves at least one String, it performs concatenation—not addition—and evaluates left-to-right:
1 + "abc" + 1→"1abc1"1 + 2 + "def" + 3 + 4→"3def34"(since1+2computes first as integer addition)
Character Arithmetic
Characters participate in arithmetic via their Unicode (ASCII-compatible) code points:
char letter = 'A';
int code = letter + 0; // 65
System.out.println((char)(code + 32)); // 'a'
Increment/Decrement Operators
++ and -- modify operand values by 1. Placement determines evaluation timing:
++x: Increment before use (prefix).x++: Use current value, then increment (postfix).
Example:
int x = 5;
int y = ++x * 2; // x becomes 6, then y = 6 * 2 = 12
int z = x++ * 3; // z = 6 * 3 = 18, then x becomes 7
Assignment and Compound Operators
Standard assignment (=) stores the right-hand expression's result. Compound operators like += combine operation and assignment:
int count = 10;
count += 5; // equivalent to count = count + 5;
Note: Compound assignments include implicit narrowing casts—for example, byte b = 10; b += 20; compiles even though b = b + 20 would require explicit casting.
Relational and Logical Operators
Relational operators (==, !=, <, <=, >, >=) compare values and return boolean.
Logical operators combine boolean conditions:
&(AND): Evaluates both sides always.|(OR): Evaluates both sides always.^(XOR): Returnstrueonly if operands differ.!(NOT): Inverts a single boolean value.
Short-Circuit Evaluation
&& and || skip evaluating the right operand if the left operand determines the outcome:
isValidUser() && checkPassword():checkPassword()runs only if user validation passes.hasHouse() || hasCar():hasCar()is skipped ifhasHouse()returnstrue.
This improves efficiency and avoids side effects or exceptions in unreachable code paths.
Ternary Operator
A concise conditional expression: condition ? valueIfTrue : valueIfFalse. The result must be used (assigned or printed):
int a = 12, b = 8;
int max = (a > b) ? a : b; // assigns 12
System.out.println(max);
// Nested usage for three values
int c = 15;
int overallMax = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
Operator Precedence
While Java defines precise precedence levels, relying on parentheses enhances clarity and correctness. For instance, (x + y) * z makes intent unambiguous versus x + y * z.