course content

Course Content

Introduction to Java

Conditional StatementsConditional Statements

A conditional statement is a statement that performs different actions depending on whether a Boolean condition evaluates to True or False.

A relational operator is two data values. The result is either True or False. Relational operator includes:

  • Not equal to c != d;
  • Is equal to c == d;
  • Less than c < d;
  • Greater than c > d;
  • Greater than or equal to c >= d;
  • Less than or equal to c <= d.

If-Else Statements

An if statement is a statement that allows you to test a condition and then take action based on the result of the test.

Syntax of the if-else statement:

If the condition is True, the commands in the if statement is executed. If the condition is False, the commands in the if statement is not executed. The if-else statement is similar to the if statement, but the else statement executes a set of commands if the condition is False.

When to use if, else-if, and else?

  • If statements are used when you want to execute a certain set of code only if a certain condition is true;
  • Else-if statements are used when you want to check multiple conditions and execute different code for each condition;
  • Else statements are used only if all other conditions are false when you want to execute a certain code set.

Example for if-else statement:

java

Main.java

Switch statements

A switch statement is a selection control mechanism used to allow a program to choose from several options. The switch statement is usually used when there are a small number of different choices to be made, and a set of simple values can represent the choices.

Syntax of the switch statement:

When the value of the expression matches one of several defined case values, the code associated with that case is executed;

If the value of the expression does not match any of the case values, the code associated with the default case is executed;

When the break statement is encountered inside a switch statement, it immediately exits the switch statement;

A switch statement can have a voluntary default case, which should show at the end of the switch block. The default case can execute code when no match is found.

Example for switch statement:

java

Main.java

question-icon

What is the output of the following code?

Select the correct answer

Section 1.

Chapter 7