Sunday, December 4, 2022
HomeJavaUnderstanding Java Conditional Statement with Flowcharts

Understanding Java Conditional Statement with Flowcharts

Up until now, our programmes have been linear. In other words, there were no significant surprises or conditional behavior during the course of the programmes’ execution. But most of the time we wish to incorporate conditional logic into our applications. By this, we imply functionality that depends in some manner on the state of the variables used by the programme. Java conditional statement provides a decision-making feature in which when the given condition is true then a certain block of code is executed.

For instance, we need to utilize a conditional statement to branch the execution of a programme based on user input. This is the simplest possible conditional expression.

What is a conditional Statement?

“If” is the first word in a conditional statement, followed by parenthesis. When the conditional statement is reached, an expression enclosed in parentheses is evaluated. A boolean value represents the evaluation’s outcome. There was no evaluation done above. Instead, the conditional phrase expressly employed a boolean value.

A block that is defined inside the opening- and closing-curly brackets comes after the parenthesis. If the expression inside parentheses evaluates to true, the source code included within the block is run.

Also read, Simple explanation of Java Operators

Types of Conditional Statements

Java If Statement

If a condition is true, Java’s single if statement is utilized to run the programme. Additionally, it is known as a one-way selection statement. If a condition is used, an argument is passed, and if it is satisfied, the corresponding code is executed; otherwise, nothing happens.

java if condition statement

Syntax

if (expression) {
// code to run the program
}

Example

if (21 > 16) {
  System.out.println("21 is greater than 16");
}

In this example above checkout the two values which one is greater. As you can see 21 is greater than 16, if the statement is true it will print some text. 

public class Main
{
  public static void main (String[]args)
  {
    int x = 32;
    int y = 16;
    if (x > y){
        System.out.println ("x is greater than y");
    }
  }
}

In this example we have x and y variables, here we test whether x is greater than y (with the help of the > operator). Here, y is 16 and x is 32 and 32 is greater than 16, so it will print “x is greater than y”.

Also read, Learn about Java Datatypes and how we use them

Java If-else Statement

It is also referred to as if-then-else. In this case, in addition to the if-statement, the condition is also specified in the otherwise block. The most typical decision-making statement is this one. The condition of the “else statement” will be carried out if the if-given statement’s condition is false.

java if-else condition statement

Syntax

if (expression) {
// code to be executed
} else {
// code to be executed 
}

Example

In the example below, time (18) is lesser than 20, so the if statement is false, as it is false we move to the else statement,  which will print “Good evening”.

public class Main
{
  public static void main (String[]args)
  {
    int time = 20;
    if (time < 18)
      {
    System.out.println ("Good day.");
      }
    else
      {
    System.out.println ("Good evening."); // Good evening
      }
  }
}

Also read, I Turned My Startup Into Open-Source

Java else-if statement

When the initial condition fails, this ladder is used to set further criteria. With this, several criteria can be checked within a single program. A set of conditions are set out in the if-block that precedes the statement. Multiple else if statements follow it. This indicates that if the first “if condition” is unsuccessful, we can verify the circumstances outlined in the following “else-if conditions.”

Java else-if statement

Syntax

if (condition1) {
 // code to be executed 
} else if (condition2) { 
// code to be executed 
} else {
// write default code when the conditions are false
}

Example

In the example below, we initialized a variable called age with an integer or number. Then we attempted to categorize the age with the aid of the Java if-else-if ladder. One print statement exists for each category, and it only runs when the relevant condition is met or the assertion is true. One final default statement will be carried out if all the conditions are untrue.

import java.util.Scanner;
public class Main
{
  public static void main (String[]args)
  {
    System.out.println ("Enter the number: ");
    Scanner sc = new Scanner (System.in);
    int num = sc.nextInt ();
    if (num < 0){
        System.out.println ("Negative number");
    }else if (num > 0){
        System.out.println ("Positive number");
    }
    else{
        System.out.println ("Number is zero");
    }
  }
}

Output

Enter the number: 
6
Positive number

Also read, Understanding Java String methods with examples

Java switch statement

A multi-way branching expression is the switch statement. The Java switch statement runs one statement from a variety of criteria, to put it simply. This phrase resembles an if-else-if ladder. It offers a simple method for allocating execution to various sections of code depending on the expression’s value.

Some important rules to keep in mind before writing the switch statement:

  1. A large number of cases can be written to check the condition but you have to keep in mind that duplicate cases or values are not allowed.
  2. The value must be the same for the datatype as the variable mentioned in the switch.
  3. The value must be constant as variables are illegal/not allowed.
  4. The break statement must be used inside the switch for terminating the statement.
  5. The default statement can be placed anywhere in the switch block and is optional. Keeping a break statement after the default statement will prevent the execution of the following case statement in the event that it is not at the end.

Java switch statement

Syntax

// switch statement 
switch(expression)
{
   // case statements
   // the values must be of same type as the expression
   case value1 :
      // Statements
      break; //  (optional)
   
   case value2 :
      // Statements
      break; // (optional)
   // There can be multiple cases
   // here, default statement is used if non of the cases are true 
   // there is no need of the break in the default cases
   default : 
      // Statement
}

Example

import java.util.Scanner;
public class Main
{
  public static void main (String[]args)
  {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number from these options -> 1| 2 | 3");
       int button = sc.nextInt();
       switch (button) {
           case 1:
               System.out.println("Hello");
               break;
           case 2:
               System.out.println("Namaste");
               break;
           case 3:
               System.out.println("Bonjour");
               break;
           default:
               System.out.println("Invalid Button");
    }
  }
}

Also read, Understanding Java Math Class And its different methods

Final Words

In this tutorial, we’ve covered the different iterations of the Java if-construct, including the switch operator, if-else condition, and if-else-if ladder. Each of them includes a proper illustration, syntax explanation, and explanation of what it does and how it works.

A flowchart diagram and programming examples are used to describe each variant, which will aid in your comprehension of the subject. Aside from certain additional approaches for loops, while loops, and other types of decision-making that will be covered later, this is the most typical way to execute a conditional check or decision-making in Java.

Ali Hashir
Hi, I am a High School student, who is highly interested in tech, gadgets, and Gaming. With my knowledge and experience, I want to share my thoughts so that you can decide what better for you.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments