Java / Java Basics

Java Control Flow: If, Else, and Switch Statements

This tutorial will focus on how to control the flow of execution in a Java program using 'if', 'else', and 'switch' statements. You'll learn to write code that can make decisions …

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers fundamental concepts, including syntax, data types, and basic input/output operations.

Introduction

In this tutorial, we will explore how to control the flow of execution in a Java program using 'if', 'else', and 'switch' statements. These elements are crucial for developing dynamic programs that can execute different actions based on various conditions.

You will learn:
- How to use 'if', 'else', and 'switch' statements
- How to write efficient and effective conditional statements
- Best practices when dealing with control flow statements

Prerequisites:
- Basic knowledge of Java syntax and programming concepts
- A Java development environment set up on your machine

Step-by-Step Guide

If Statement

The 'if' statement is the simplest form of control flow statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise not.

if (condition) {
  // code to be executed if condition is true
}

Else Statement

An 'else' statement can be combined with an 'if' statement. An 'else' statement contains the block of code that will be executed if the associated 'if' statement's condition is false.

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

Switch Statement

A 'switch' statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

switch(expression) {
  case value1 :
    // code to be executed if expression equals value1
    break; // optional
  case value2 :
    // code to be executed if expression equals value2
    break; // optional
  // You can have any number of case statements.
  default : // Optional
    // code to be executed if expression doesn't match any case
}

Code Examples

If-Else Statement

int number = 10;
if (number > 0) {
  System.out.println("Number is positive.");
} else {
  System.out.println("Number is not positive.");
}

In this example, the program checks if the number is positive. If the number is greater than 0, it prints "Number is positive." If not, it prints "Number is not positive."

Switch Statement

int day = 2;
String dayString;
switch (day) {
  case 1:  dayString = "Monday";
           break;
  case 2:  dayString = "Tuesday";
           break;
  // ... // other days
  default: dayString = "Invalid day";
           break;
}
System.out.println(dayString); // Prints "Tuesday"

This example assigns a different string to the dayString variable depending on the value of the day variable.

Summary

In this tutorial, you have learned how to control the execution flow of your Java programs using 'if', 'else', and 'switch' statements. These control flow statements are a fundamental part of Java and many other programming languages.

Next, you might want to learn about loops in Java, which are another crucial part of controlling program flow.

Practice Exercises

  1. Write a Java program that takes a single digit number and prints the number in word using switch statement. (Difficulty: Easy)

  2. Write a Java program that takes a grade (A-F) and prints excellent, good, fair, poor based on the grade using if-else statements. (Difficulty: Medium)

  3. Write a Java program that simulates a basic calculator using switch statement. (Difficulty: Hard)

Solutions and explanations will be provided upon request. As a best practice, try to solve the problems by yourself before looking at the solutions. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help