Table of Contents
if Statement
An if statement checks a condition and executes a block of code only if that condition evaluates to true.Syntax:
Here,if(condition)
{
// code to execute if condition is true
}
- 'if' is a keyword in Java.
- The condition written inside brackets must return either true or false.
- If the condition is true, then only the code is written inside the block will execute.
- If the condition is false, then the block is skipped.
Example 1: Check Eligibility to Vote
Below is the Java program that checks whether a person is eligible to vote based on their age.
// Java program to check whether a person
// is eligible to vote based on their age
public class Main
{
public static void main(String[] args)
{
int age = 20;
if(age = 18)
{
System.out.println("Eligible to vote");
}
}
}
Output:
Explanation:Eligible to vote
- In the above code if age = 18 is true then block executes.
- Therefore, the message "Eligible to vote" is printed.
Example 2: Check Pass/ Fail Using Marks
Below is the Java program to determine whether a student has passed or failed based on their marks.
// Java program to determine whether a
// student has passed or failed based on
// their marks
public class Main
{
public static void main(String[] args)
{
int marks = 30;
if(marks = 40)
{
System.out.println("Pass");
}
else
{
System.out.println("Better luck next time");
}
}
}
Output:
Explanation:Better luck next time
- In the above code if the marks = 40 is true then only if block will execute.
- The if block does not execute here because the condition is false.
- So, the control goes to the else statement.
Conclusion
We can conclude that if statement in Java is a fundamental control statement used to make decisions in a program as we do in real life. It checks conditions and executes code accordingly. Understanding if statement is essential for building logical and interactive Java applications.Frequently Asked Questions
1. What is an if statement in Java?2. Can we use multiple conditions in an if statement?An if statement in Java is a conditional statement used to execute a block of code only when a specified condition is true.
3. What happens if the condition in an if statement is false?Yes, multiple conditions can be used with logical operators like && (AND) and || (OR).
4. Is it mandatory to use curly braces {} in an if statement?If the condition is false, the code inside the if block is skipped and the program continues executing the remaining statements.
5. What is the difference between if and if-else statement?No, curly braces are optional when there is only one statement inside the if block. However, using braces is recommended for better readability.
- if executes code only when the condition is true.
- if-else provides an alternative block that executes when the condition is false.
0 Comments