Java Operators in Java: Complete Beginner Guide (With Examples)
Java Operators: Doing Math and Logic in Java
In our previous post, we learned about Java Variables and Data Types and how to store values like numbers, text, and true/false.
Now it’s time to learn how to work with those values. That’s where operators come in.
Operators are special symbols in Java that allow you to perform:
1) Arithmetic Operators
These operators are used for basic math.
Example
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));
}
}
2) Assignment Operators
Assignment operators are used to assign values to variables.
Example
public class AssignmentOperators {
public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println("After += : " + x);
x -= 3;
System.out.println("After -= : " + x);
x *= 2;
System.out.println("After *= : " + x);
x /= 4;
System.out.println("After /= : " + x);
}
}
3) Comparison (Relational) Operators
Comparison operators compare two values and return true or false.
4) Logical Operators
Logical operators are used to combine conditions.
5) Increment and Decrement Operators
These operators are used to increase or decrease values by 1.
6) Java Operators Example (All in One Program)
public class JavaOperatorsExample {
public static void main(String[] args) {
int a = 15;
int b = 4;
// Arithmetic
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
// Comparison
System.out.println("a > b : " + (a > b));
System.out.println("a == b : " + (a == b));
// Logical
boolean result = (a > b) && (b > 0);
System.out.println("Logical Result: " + result);
// Increment
a++;
System.out.println("After increment a = " + a);
}
}
Conclusion
Operators are one of the most important parts of Java because they allow you to:
- ✅ Perform calculations
- ✅ Compare values
- ✅ Write conditions
- ✅ Build logic for programs
In the next post, we will learn about Java Conditional Statements (if, else, switch) and how to make decisions in Java!
One of the best programming blog
ReplyDeleteExamples are making easy way to understanding🌟
ReplyDelete