This tutorial is designed to guide you on how to work with operators and expressions in Java. An operator in Java is a special symbol that is used to perform operations. There are many types of operators like Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators, and so on.
By the end of this tutorial, you will have a strong understanding of the different types of operators and how to use them to construct expressions in Java.
A basic understanding of Java programming language is required. Knowledge of Java data types would also be beneficial.
Arithmetic operators are used to perform arithmetic operations like addition, subtraction, multiplication, division, etc.
int a = 10, b = 20;
System.out.println("a + b = " + (a + b)); // Addition
System.out.println("a - b = " + (a - b)); // Subtraction
System.out.println("a * b = " + (a * b)); // Multiplication
System.out.println("b / a = " + (b / a)); // Division
System.out.println("b % a = " + (b % a)); // Modulus
Relational operators are used to compare two variables. They return a boolean result after the comparison.
int a = 10, b = 20;
System.out.println("a == b : " + (a == b)); // Equal to
System.out.println("a != b : " + (a != b)); // Not equal to
System.out.println("a > b : " + (a > b)); // Greater than
System.out.println("a < b : " + (a < b)); // Less than
System.out.println("b >= a : " + (b >= a)); // Greater than or equal to
System.out.println("a <= b : " + (a <= b)); // Less than or equal to
Example 1: Using arithmetic operators to calculate the area and perimeter of a rectangle.
int length = 10, width = 5;
// Calculate area
int area = length * width;
System.out.println("Area = " + area); // Outputs: Area = 50
// Calculate perimeter
int perimeter = 2 * (length + width);
System.out.println("Perimeter = " + perimeter); // Outputs: Perimeter = 30
Example 2: Using relational operators to compare two numbers.
int num1 = 10, num2 = 20;
// Compare the numbers
boolean result = num1 > num2;
System.out.println("num1 is greater than num2: " + result); // Outputs: num1 is greater than num2: false
In this tutorial, we learned about the different types of operators in Java and how to use them in expressions. We covered arithmetic operators to perform mathematical operations and relational operators to compare variables.
Exercise 1: Write a program to calculate the area of a triangle using arithmetic operators.
Exercise 2: Write a program to compare three numbers and determine the largest one using relational operators.
Solutions will be provided upon request.
Try using other types of operators like bitwise, logical, and assignment operators in your programs to get a better understanding of how they work. Practice is key when it comes to programming. The more you code, the better you'll become. Happy Coding!