You are on page 1of 4

If Statement:

Syntax:

if (some Boolean condition)

Some set of code.

 It is not mandatory to have an else for every if statement.


 We can write multiple if statements one below the other, but this not a good practice since we
need to check all the if conditions, the better practice is to use else if.
 For the if the block we can write one-line without having {} brackets.

If else Statement:
Syntax:

if (some Boolean condition)

Some set of code

else

Some set of code

 We cannot have else statement without if statement.


 Compiler doesn’t check the else statement if the condition is true.
 We can write one line for if and else blocks without having {} brackets
The above code shows compilation error, because we have a print statement between if-block
and else-block, so the compiler looks at the else block as a separate else block and looks for its
corresponding if statement which is not there.

In java we cannot write1,0 or any number inside the if condition, it shows error.

Example:

If (1)

Some code

Else if Statement:
Syntax:

Syntax:

if (Boolean condition 1)

Some set of code

else if (Boolean condition 2)

Some set of code

else

Some set of code

 We can have multiple else if blocks.


 We cannot have an if else statement without if statement.
 It is not mandatory to have an else statement, we can just have if and else if blocks also.
Note:

In OR (||) operator if condition 1 is true then it will not even check for the condition 2.

Similarly, In AND (&&) Operator, it will check the second condition only if the first condition is true, if the
first condition is false then it will not even check the second condition.

Example 1: Identify the type of triangle if the sides are given.

Example 2: Find the largest number if three numbers are given.


Scope of Variables:

 In terms of scope, the variable is valid with in the {} where the


variable is created.

You might also like