Operation and Condition in Java
Operation and Condition in Java
in Java
• In Java, operators are symbols that perform
operations on variables and values. They are
essential for carrying out arithmetic, logical,
and relational tasks within programs.
In the example below, we use the + operator to
add together two values:
·Arithmetic operators
·Assignment operators
·Comparison operators
·Logical operators
·Bitwise operators
JAVA COMPARISON OPERATORS
Comparison operators are used to compare two
values (or variables). This is important in
programming, because it helps us to find
answers and make decisions. The return value of
a comparison is either true or false. These values
are known as Boolean values.
JAVA COMPARISON OPERATORS
Conditional Statements in Java
if (condition) {
// Code block to execute if condition is
true
}
Here is an example:
In this example, if the value of num is greater than 0, the message "The number is
positive." will be printed.
USING THE IF-ELSE STATEMENT
The if-else statement allows you to execute one block of code if the condition is true,
and another block if the condition is false. Its syntax is:
if (condition) {
// Code block to execute if condition is true
} else {
// Code block to execute if condition is false
}
Here is an example:
int num = -5;
if (num > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is non-positive.");
}
In this example, if the value of num is greater than 0, the message "The number is positive."
will be printed; otherwise, "The number is non-positive." will be printed.
USING THE IF-ELSE-IF LADDER
When you have multiple conditions to check, you can use an if-else-if ladder. It allows you to
check multiple conditions and execute different code blocks accordingly. Here's the syntax:
if (condition1) {
// Code block to execute if condition1 is true
} else if (condition2) {
// Code block to execute if condition2 is true
} else {
// Code block to execute if none of the conditions are true
}
Example:
int num = 0;
if (num > 0) {
System.out.println("The number is positive.");
} else if (num < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
In this example, if the value of num is greater than 0, "The number is positive." will be printed; if it's less
than 0, "The number is negative." will be printed; otherwise, "The number is zero." will be printed.
Skill Building Activity 2