Java Operators
In this page:
What are Operators?
An operator is a special symbol that performs an operation on one or more values, called operands, producing a new value -- the + symbol, for example, is an operator that adds two numeric operands together.
Example: What are Operators?
public class Main {
public static void main(String[] args) {
int result = 5 + 3; // '+' is the operator, 5 and 3 are the operands
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Categories of Operators
Java groups operators into categories based on what kind of result they produce: arithmetic operators compute numbers, relational operators compare values and produce booleans, and logical operators combine boolean values.
Example: Categories of Operators
public class Main {
public static void main(String[] args) {
int sum = 5 + 3; // arithmetic -> number
boolean isBigger = 5 > 3; // relational -> boolean
boolean both = true && isBigger; // logical -> boolean
System.out.println(sum + " " + isBigger + " " + both);
}
}
Login to try C/C++/Java/PHP code in the editor
Operators and Operands
Every operator acts on operands -- most operators like + and * are binary and need two operands, while a few like ++ and unary - are unary and act on just a single operand.
Example: Operators and Operands
public class Main {
public static void main(String[] args) {
int a = 5, b = 3;
int sum = a + b; // binary - needs two operands
int negative = -a; // unary - needs just one operand
System.out.println(sum + " " + negative);
}
}
Login to try C/C++/Java/PHP code in the editor
Combining Operators in Expressions
Operators of different categories are frequently combined in a single expression, such as mixing arithmetic and relational operators to build a condition, or arithmetic and assignment operators to compute and store a result together.
Example: Combining Operators in Expressions
public class Main {
public static void main(String[] args) {
int total = 5;
total += 3; // arithmetic + assignment combined
boolean valid = total > 5 && total < 20; // relational + logical combined
System.out.println(total + " " + valid);
}
}
Login to try C/C++/Java/PHP code in the editor
Operator Precedence Preview
When an expression mixes multiple operators, Java evaluates them according to a fixed precedence order -- multiplication and division run before addition and subtraction by default, and parentheses can always override that default order.
Example: Operator Precedence Preview
public class Main {
public static void main(String[] args) {
int result = 2 + 3 * 4; // multiplication runs first: 2 + 12 = 14
int forced = (2 + 3) * 4; // parentheses override: 5 * 4 = 20
System.out.println(result + " " + forced);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: