Java Conditional Statement: If Statement

If Statement

Java Conditional Statement : If Statement 

To understand what an If Statement is , let us first study what does the term Conditional Statement imply, in java conditional statement if statement –

Conditional Statement are feature of programming languages that are used to make decisions based on the conditions. Conditional statements execute sequentially when there is no condition around the statements. If we apply some condition for a set of statements within the scope, the execution flow may change based on the result evaluated by the condition. This process is called decision making.

The ‘ If- Statement ‘ is an example of such conditional statements.

Understanding the concept of If Statement

The If- Statement is one of the most basic decision making statement. This functionality is primarily used when the user requires the executions of a statement or a block of statements to be executed only if some given condition(s) is true. In other words we can say it checks a Boolean condition: true or false. For starters, let us look at how the control flows in an if- statement program:-

  • The control initially falls into the if block.
  • The flow then jumps to the specified ‘ Condition ‘.
  • Now, The condition is tested.
    1. If Condition yields true, execute the part of code within the block
    2. If Condition yields false, control falls out of the if- block and the statements after if are executed.

For better understanding, the working of this flowchart has been given in the following image.

If- statements

Prime Course Trailer

Related Banners

Syntax of If- Statement

public class Main
{
public static void main(String[] args) {

if (condition)
{
// statements
}
}
}

Now that we have seen the syntax of the if- statement, let us understand it further with the help of an example. 

Suppose Manav is earning some amount of money and you want to print his income only if it is greater that Rs. 1000.

For this, the code using if statement will be:

Run
class Main{
   public static void main(String[] args) {
        int income = 5000;
        // checks if income is greater than 1000

        if (income > 1000) 
        {
            System.out.println("Hey Prepster. Good going!");
        }

        System.out.println("Welcome to PrepInsta");
  }
}

Output: 

Hey Prepster, Good going!.
Welcome to PrepInsta

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Case 1: Condition is true
  1. Condition is checked.
  2. Returns true, statement inside if statement is executed.
  3. Flow control outside if statement. Next statement is also executed
if statement ex 1
Case 2: Condition is false
  1. Condition is checked.
  2. Returns false, statement inside if statement is skipped.
  3. Flow control outside if statement. Next statement is executed.