The selection statement allows choosing the set of instructions for execution depending upon an expression’s truth value.
The if statement is used to test particular conditions. If the c condition evaluates to true, a course-of-action is followed, i.e, a statement or a set of statements is executed. There are four different types of If statements:
In Java, there are four different types of if statements:
The if statement is a single conditional statement that is only executed if the given condition is true.
Syntax:
if(condition)
{
//if true code executed
}
public class IfDemo1 {
public static void main(String[] args)
{
int age=20;
if(age > 18)
{
System.out.print("Not a minor");
}
System.out.print(" minor");
}
}
Not a minor
Similarly, if the age is 15 then,
minor
For condition testing, the if-else statement is used. If the condition is true, the if block is executed; if the condition is false, the else block is executed.
It comes in handy when we need to perform an operation based on a false result.
When the condition is false, the else block is executed.
Syntax:
if(condition)
{
//code for true
}
else
{
//code for false
}
public class IfDemo2 {
public static void main(String[] args)
{
int age=20;
if(age > 18)
{
System.out.print("Not a minor \nCondition true");
}
else{
System.out.print(" minor \nCondition false");
}
}
}
Not a minor
Condition true
Similarly, if the age is 15 then,
minor
Condition false
We shall see about the if-else ladder and nested if in the next tutorial.
Note: also read about the Type casting in Java
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…