The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.
Some abbreviations that will be used in this learning:
1. Java Conditions and If Statements
You already know that Java supports the usual logical conditions from mathematics:
Java has the following conditional statements:
2. The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Q1. Sravan loves drinking tea. But he is out of sugar. Sravan is asking his neighbour Karthik?
if (do_you_have_suger) {
then => Borrow some suger
} else {
then => don't do anything
}
Q2. Eligibility criteria for voting.
Correct logic to check whether you are eligible to vote.
Note: Some students may ask why are we drawing diagrams. Just mention that it's easy to visualize.
Q3. Check person is senior citizen or not.
If age >= 65, then they can collect pension.
Q4. Check whether person is suffering from fever or not.
Q5. Which of the following is NOT a boolean expression?
Q6. Read a number and If person is eligible, print "eligible to vote".
public static void main() {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
if (age >= 18) {
System.out.print("Eligible to vote");
}
}
Q7. Which data type should be used to store temperature of a patient?
psv main() {
Scanner sc = new Scanner(System.in);
double temp = sc.nextDouble();
if (temp >= 98.6) {
System.out.print("Go to doctor!");
}
}
Q8. Predict the output:
int a = 10;
if (a >= 10) {
System.out.println("Yo");
}
System.out.println("Yo");
Q9. Predict the output:
int a = 18,b = 16;
if (a >= 18) {
System.out.println("a is major");
}
if (b >= 18) {
System.out.println("b is major");
}
System.out.println("Blab");
Q10. Predict the output:
int a = 50,b = 50;
if (a >= 50) {
System.out.println("a scored half");
a = a + 1;
}
if (b >= 50) {
System.out.println("b scored half");
b = b + 1;
}
System.out.print(a + b);
Q11. Predict the output:
if (5 > 4) {
System.out.println("First if");
}
if (10 >= 6) {
System.out.println("Second if");
}
Q12. Predict the output:
if (5 > 10) {
System.out.println("First if");
}
if (10 >= 16) {
System.out.println("Second if");
}
System.out.println("Oops!! Nothing will get printed..");
Q13. Predict the output:
if (true) {
System.out.println("1");
}
if (true) {
System.out.println("2");
}
if (true) {
System.out.println("3");
}
Check if someone has normal temperature: Normal temp = 98.0 to 98.9
Explain -> 98.0________98.9_
Scanner sc = new Scanner(System.in);
double temp = sc.nextDouble();
if (temp >= 98.0 && temp >= 98.9) {
System.out.println("Normal temperature");
}
2. The else Statement
Now, we want to do something or the other accordingly when the condition is true or false. Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// Statements to run, when above condition True
} else {
// Statements to run, when above condition False
}
if (condition) {
Statement 1
} else {
Statement 2
}
If Condition is True: Statement 1 will execute
If Condition is False: Statement 2 will execute
Statement 1
if (condition) {
Statement 2
} else {
Statement 3
}
Statement 4
If Condition is True: Statement 1, 2, 4 will execute
If Condition is False: Statement 1, 3, 4 will execute
Example 1: Read age of a person, check if person is at retirement age, or still have few years left to work. Retirement age is 65.
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
if (age > 65) {
System.out.println("Retired");
} else {
System.out.println("Few more years of service.");
}
Q1. Predict the output:
if (9 > 5) {
System.out.println("If block");
} else {
System.out.println("Else block");
}
Q2. Predict the output:
Predict the output:
if (false) {
System.out.println("Line 1");
} else {
System.out.println("Line 2");
}
Modulus Operator
Modulus operator (%) -> Gives remainder
System.out.println(17 % 4) -> Remainder = 1
System.out.println(24 % 2) -> Remainder = 0
System.out.println(97 % 2) -> Remainder = 1
System.out.println(82 % 2) -> Remainder = 0
Explain even and odd numbers.
Even numbers: Numbers which are divisible by 2.
Eg: 2, 4, 6, 8, 10, 12..
When we divide the number with 2, remainder = 0
Odd numbers: Numbers which are not divisible 2.
Eg: 1, 3, 5, 7, 9, 11..
When we divide the number with 2, remainder = 1
Example 1: Read a number and check if number is odd or even.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 2 == 0) {
System.out.println("Number is even");
} else {
System.out.println("Number is odd");
}
Example 2: Check if a number is divisible by 5.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 5 == 0) {
System.out.println("Number is divisible by 5");
} else {
System.out.println("Number is not divisible by 5");
}
Example 3: Check if a number is divisible by 2 or 3.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a % 2 == 0 || a % 3 == 0) {
System.out.println("Number is divisible by 2 or 3");
} else {
System.out.println("Number is not divisible by 2 and 3 both");
}
Question: Can we have if without an else block?
Question: Can we have else without an if block?
Question: Read 2 numbers and print max of 2 numbers.
Examples:
a = 5 , b = 10
Max of a and b = 10
a = 15 , b = 10
Max of a and b = 15
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
Question: Predict the output: For input: 45 45
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if (a > b) {
System.out.print(a);
} else {
System.out.print(b);
}
10 Question: Categorize Number
Given an integer n0, categorize it into positive, negative or zero.
Category:
n = 10: n > 0: print "positive number"
n = -27: n < 0: print "negative number"
n = 0: n == 0: print "zero"
public static void main() {
Scanner sc = new Scanner(System.in);
int a = scn.nextInt();
if (a > 0) {
System.out.println("positive number");
}
if (a < 0) {
System.out.println("negative number");
}
if (a == 0) {
System.out.println("zero");
}
}
Syntax:
if (cond_1) {
// Statements if cond_1 is true
} else if (cond_2) {
// Statements if cond_1 is false and cond_2 is true
} else {
// Statements if cond_1 is false and cond_2 is false
}
Note: "else" is optional.
3. The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Statement 1
if (cond_1) {
// block of code to be executed if condition1 is true
Statement 2
} else if (cond_2) {
// block of code to be executed if the condition1 is false and condition2 is true
Statement 3
} else {
// block of code to be executed if the condition1 is false and condition2 is false
Statement 4
}
Statement 5
Explain the above flow according to below table.
Conditions which are true | Statements executed |
---|---|
1 | 1 2 5 |
2 | 1 3 5 |
All false | 1 4 5 |
1 2 | 1 2 4 |
Note: If a condition is true, it will execute and will come out of If/Else block and execute remaining statements.
Note: We can have multiple "else if ()" blocks.
Back to Categorize number problem,
public static void main() {
Scanner sc = new Scanner(System.in);
int a = scn.nextInt();
if (a > 0) {
System.out.println("positive number");
} else if (a < 0) {
System.out.println("negative number");
} else {
System.out.println("zero");
}
}
Example: Is the below code correct or not?
int a = 10;
else if (a > 5) {
System.out.println("Number is more than 5");
} else {
System.out.println("Number is not more than 5");
}
Correct Answer: Compilation error.
We cannot write any else if ()
without if ()
block.
Question: What will be the output of the following:
if (true) {
System.out.println("1");
} else if (true) {
System.out.println("2");
} else if (true) {
System.out.println("3");
}
Question: Can there be an else if block without a if block
Question: Can there be an else if block without an else block
Question: What will be the output of the following code?
int a = 10,b = 10;
if (a >= 10 && b >= 10) {
System.out.print(a+b);
}
Question: What will be the output of the following code?
int a = 10;
int b = 10;
if ( ++ a >= 12 && ++ b >= 12 ) {
System.out.println("Hello");
}
System.out.println(a + b);
Question: What will be the output of the following code?
int a = 10;
int b = 10;
if ( ++ a >= 11 || ++ b >= 12 ) {
System.out.println("Hello");
}
System.out.println(a + b)
Question: What will be the output of the following code?
int a = 10;
int b = 10;
if ( ++ a >= 12 || ++ b >= 12 ) {
System.out.println("Hello");
}
System.out.println(a + b);
Question: What will be the output of the following code?
int N = 5;
if (N > 2)
System.out.println("Yayay");
else
System.out.println("Blahblah!!");
Question: What will be the output of the following code?
int N = 5;
if (N > 2)
System.out.println("Yayay");
System.out.println("Hmmmm");
else
System.out.println("Blahblah!!");
System.out.println("Blahblah!!");
Question: What will be the output of the following code?
int marks = 80;
if (marks > 70) {
System.out.print("Distinction ");
System.out.print("Congrats ");
} else if (marks > 35) {
System.out.print("Pass ");
} else
System.out.print("Fail ");
System.out.print("Good luck");
5. Categorize Triangles
Equilateral: When the length of the all the sides are equal.
Isosceles: When the length of any two sides are equal.
Scalene: When the length of all sides are different.
Let a
, b
, c
be the length of the three sides of a triangle. Given in each case they take some values, tell the category of the triangle. It is the given that the input values for a, b, c are positive integer values.
a = 20, b = 20, c = 20
-- Output = Equilaterial
a = 7, b = 12, c = 9
-- Output = Scalene
a = 5, b = 13, c = 5
-- Output = Isosceles
a = 12, b = 7, c = 7
-- Output = Isosceles
The equivalent code for implementing the above logic is as follows:
if (a == b && b == c) {
SOPln("Equilateral");
} else if (a == b || b == c || a == c) {
SOPln("Isosceles");
} else {
SOPln("Scalene");
}
6. Max of three: Given three numbers, print the maximum among them.
Note that a
, b
, c
can take any integer values.
Stress on the point that a
, b
, c
can also take equal values. The three test case demonstrates this point.
* a = 7, b = 20, c = 50 ==> max = 50
* a = 10, b = 9, c = 10 ==> max = 10
* a = 3, b = 3, c = 3 ==> max = 3
The equivalent code for implementing the above logic is as follows:
if (a >= b && a >= c) {
SOPln("a");
} else if (b >= c) {
SOPln("b");
} else {
SOPln("c");
}
7. Fizz-Buzz
Given a number,
* print "Fizz" if the number is divisible by 3.
* print "Buzz" if the number is divisible by 5.
* print "Fizz-Buzz" if the number is divisble by both 3 and 5.
For example,
No output
How to implement this?
The following code shows a wrong implementation of the above logic:
if (n % 3 == 0) {
SOPln("Fizz");
} else if (n % 5 == 0) {
SOPln("Buzz");
} else {
SOPln("Fizz-Buzz");
}
The above code prints "Fizz-Buzz" for n = 11, but this is wrong as n is neither divisble by 3 nor 5. So there should have no output for this number.
Another wrong implementation is as follows:
if (n % 3 == 0) {
SOPln("Fizz");
} else if (n % 5 == 0) {
SOPln("Buzz");
} else if (n % 3 == 0 && n % 5 == 0) {
SOPln("Fizz-Buzz");
}
The above code prints "Fizz" for n = 15, but this is wrong as n is divisble by 3 and 5 both. So the correct output should be "Fizz-Buzz".
So finally, the correct implementation of this logic is as follows:
if (n % 3 == 0 && n % 5 == 0) {
SOPln("Fizz-Buzz");
} else if (n % 3 == 0) {
SOPln("Fizz");
} else if (n % 5 == 0) {
SOPln("Buzz");
}
9. Nested If Else
Syntax:
Statement 1
if (cond1) {
Statement 2
if (cond2) {
Statement 3
} else {
Statement 4
}
Statement 5
} else {
Statement 6
if (cond3) {
Statement 7
} else {
Statement 8
}
Statement 9
}
Question: Predict the output of the following code?
int a = 10, b = 15;
if (a > 8) {
if (a < b || b == 9) {
System.out.println("Hi");
} else {
System.out.println("Bye");
}
} else {
System.out.println("Good Bye");
}
Question: Predict the output of the following code?
int a = 10, b = 15;
if (a > 8) {
if (a == b || b < a) {
System.out.println("Hi");
}
else {
System.out.println("Bye");
}
} else {
System.out.println("Got it");
}
Question: Predict the output of the following code?
if (true) {
if (true) {
if (false) {
System.out.println("Hey there");
}
}
else {
System.out.println("Hello");
}
} else {
System.out.println(10 / 0);
}
Explanation:
We are not getting an error because the inner if statement with the false condition is not executed due to the if condition being false. Therefore, the else block following it is also not executed. The program simply moves on to the next line, which is outside of any control structures and executes the statement System.out.println("Hello");
as expected.
The else block following the outer if statement is also not executed since the condition of the outer if statement is true, and the program again moves to the next line and executes the statement System.out.println("Hello");
Categorise the number Given a number, classify it as follows:
* +ve and even
* +ve and odd
* -ve and even
* -ve and odd
public static void main() {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
if (num > 0) {
if (num % 2 == 0) {
SOPln("Positive and even");
}
else {
SOPln("Positive and odd");
}
}
else {
if (num % 2 == 0) {
SOPln("Negative and even");
}
else {
SOPln("Negative and odd");
}
}
}
It defines the point till where you can use the variable. You can only use a variable till the closing bracket of the block in which it was created.
Example 1:
public static void main() {
int x;
x = 5;
int y;
y = 20
}
Scope of variable x
: Line 4 to 10
Scope of variable y
: Line 7 to 10
Example 2:
public static void main() {
int x = 10;
if (x == 10) {
int y = 5;
SOP(y);
}
int z = 9;
}
Scope of variable x
: Line 3 to 10
Scope of variable y
: Line 5 to 7
Scope of variable z
: Line 8 to 10
Example 3:
public static void main() {
int a = 10;
{
a = 20;
}
SOP(a);
}
Scope of variable a
: Line 2 to 8
Also the code will print 20 as the changes done in the variable values are not restricted to that block in which the change is done. But the life of the variable is restricted to the block in which it was created.
Example 4:
public static void main() {
int x = 10;
{
int y = 20;
SOP(x + " " + y);
}
{
SOP(x + " " + y); // This line will give error as y is not present in its scope
}
}
Example 5: Redefining variable error
public static void main() {
int a = 90;
{
int a = 7; // This line will give error as variable a is already defined in this scope
SOPln(a);
}
}
Question: Predict the output of the following code:
public static void main(String args[]) {
int x = 10;
{
int y = 20;
System.out.println(x + " " + y);
}
{
System.out.println(x + " " + y);
}
System.out.println(x + " " + y);
}
Question: Predict the output of the following code:
public static void main() {
int x = 10, y = 20;
{
SOP(x + " " + y);
}
{
x = 15;
SOPln(x + " " + y);
}
SOPln(x + " " + y);
}
Question: Predict the output of the following code:
if (true) {
int x = 10;
SOPln("Value of x is " + x);
x ++ ;
}
SOPln("Value of x is " + x);
Question: Predict the output of the following code:
int a = 0;
{
int b = 10;
SOPln("b = " + b);300
int c = a + b;
SOPln("c = " + c);
}
a = c + b;
SOPln("a = " + a);
Explanation: Error b and c are out of the scope
Question: Predict the output of the following code:
int a = 10, b = 5;
if (true) {
int c = a * b;
}
SOPln(c);
Explanation: Error the variable c is out of the scope
Thank you so much for reading. If you found it valuable, consider subscribing for more such content every week. If you have any questions or suggestions, please email me your comments or feel free to improve it.
I'm Rahul, a Indian Sr. Software Engineer (SDE II) and passionate content creator. Sharing my expertise in software development to assist learners.
More about meExplore Other Topics
Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types.
OOP in Java stands for Object-Oriented Programming. It's a programming paradigm that revolves around the concept of "objects," which can contain data, in the form of fields (attributes or properties), and code, in the form of procedures (methods or functions).