Site icon TestingDocs.com

Conditional Statements in Java

Introduction

In this post, we will discuss conditional statements in the Java programming language. Conditional structures allow us to take decisions in the code. Loops allow repeating a set of instructions many times.

A conditional statement is an expression that produces a true or false result. Conditional statements allow us to check a condition and execute certain parts of code depending on whether the condition is true or false. Java provides verities of ways to handle conditional statements and execute the code part based on the result.

We would discuss simple conditional statements.

If…else statement

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed if the same condition is false.

if (condition) {
block of code to be executed if the condition is true
}

switch statement

The switch statement can have a number of possible execution paths. Use the switch to specify many alternative blocks of code to be executed.

package com.testingdcos.examplescripts;

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

          int weekday = 3;
          switch (weekday) {
              case 1:  System.out.println("Sunday"); break;
              case 2:  System.out.println("Monday"); break;
              case 3:  System.out.println("Tuesday"); break;
              case 4:  System.out.println("Wednesday"); break;
              case 5:  System.out.println("Thursday"); break;
              case 6:  System.out.println("Friday"); break;
              case 7:  System.out.println("Saturday"); break;
              
              default: System.out.println("Not in week!! ");break;
          }
      }
  }

 

Loops

Java loop statements

https://www.testingdocs.com/java-loop-statements/


Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version