If-Else Statements in Java
if (condition){
# code to execute if the condition is True
}else
# code to execute if the condition is False
}
The if keyword is followed by a condition that is evaluated as True or False.
If the condition is True, the indented code block after the if statement is executed.
If the condition is False, the indented code block after the else statement (if present) is executed.
Example-1You are going to open a bank account. If your age is greater than 18 then you can open an account. Get your age by input and print “YES” if you can open an another account otherwise print “NO”.
OUTPUT:
Enter your age :
20
YES
This program asks the user for their age. It then uses an if statement to check if the age are greater than 18 . If the condition is True, the "YES" message is printed. Otherwise, the "NO" message is printed.
The condition can be any expression that evaluates to True or False. Common comparisons include == (equal to), != (not equal to), < (less than),> (greater than), <= (less than or equal to), and>= (greater than or equal to).
You can have multiple lines of code indented within the if and else blocks
If the condition is False, and there's no else block, no code is executed after the if statement.
Example-2:Admission to a professional course is subjected to the following –
i) Marks in Math’s >=60
ii) Marks in Physics >=50
iii) Marks in Chemistry >=40
iv) Total in all three subjects >=200
OR
Total in Math’s and physics >=150.Given the marks in the three subjects, write a program to process
the applications to the eligible candidates.
OUTPUT:
Math :
99
Physics :
70
Chemistry :
60
Eligible candidates.
Example-3: Take two integers indicating the x and y coordinate of a two-dimensional graph paper where the center point is x=0, y=0.Now print the quadrant of the given point. [If user gives input (4,5) you should print ‘First Quadrant’; If user gives input (-4,-5) you should print ‘Third Quadrant’]
OUTPUT:
Enter x :
3
Enter Y :
-1
Fourth Quadrant.
1. Write a program that asks the user for a number and checks if it's positive, negative, or zero.
2. Write a program that asks the user for the day of the week (as a number, e.g., 1 for Monday) and prints the corresponding day name.