[Introduction to Java] Conditional branching (if statement, if-else statement, else if statement, ternary operator, switch statement)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I am writing to learn about ** conditional branching **.

[Introduction to Java Table of Contents] -Variables and typesType conversion -Variable Scope -String operation -Array operationOperator ・ Conditional branch ← Now here ・ Repeat processing ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handlingAbout lambda expressionAbout Stream API

What is conditional branching?

It is to divide the processing to be executed depending on whether the conditions in the source code are satisfied. If 〇〇, process A, if △△, process B. It's like .

if statement

It is used when you have a conditional expression and perform processing according to the result of that condition. The result of the conditional expression is returned with boolean value (true, false), and when ** true, the processing in the if statement is executed. ** **

syntax


if(Conditional expression) { 
processing
};

For example, ** if the conditional expression is true. ** **

Example if if is true


int num = 10;
if (num < 20) {
  System.out.println("num value is less than 20");
}
System.out.println("Processing after if statement");

The execution result is as follows.

python


num value is less than 20
Processing after if statement

Since the conditional expression is judged and the result is true, the processing inside the if statement block is executed, and then the processing outside the if block is executed. It will be the flow.

** If the conditional expression is false. ** **

Example if if is false


int num = 10;
if (num < 5) {
  System.out.println("num value is less than 5");
}
System.out.println("Processing after if statement");

The execution result is as follows.

Execution result


Processing after if statement

Since the conditional expression is false, the processing inside the if statement block is not executed, and only the subsequent processing is executed.

It is also possible to describe an if statement inside an if statement. It's called ** nesting **. However, be careful as it will be difficult to read if you write too many.

if nesting


int num = 10;

if (num > 0) {
  System.out.println("num is a positive value");
  if (num % 2 == 0) {
    System.out.println("num is even");
  }
}

Precautions when comparing values

To compare if the values are the same, write ==. Note that if there is only one =, it will be an assignment operator instead of a relational operator.

The following will result in a compilation error.

Invalid code


int a = 20;
int b = 50;
if (a = b) { //The conditional expression does not hold, just by substituting b for a of int type.
  System.out.println("The values of a and b are the same");
}

Compare the values as follows.

Valid code


int a = 50;
int b = 50;
if (a == b) {
  System.out.println("The values of a and b are the same");
}

Execution result


The values of a and b are the same

There are some patterns that do not cause a compile error even if you make an assignment at the conditional expression.

Example of assignment in conditional expression


boolean bool1 = false;
boolean bool2 = true;
if(bool1 = bool2) { //As a result of substitution, boolean value is returned, so there is no problem as a conditional expression.
  System.out.println("bool1: " + bool1);
  System.out.println("bool2: " + bool2);
}

As a result of substituting true bool2 for false bool1, the conditional expression becomes true. Therefore, the processing in the if statement block is executed.

Execution result


bool1: true
bool2: true

if-else statement

You can describe and execute the process you want to perform not only when the conditional expression is true but also when it is false.

syntax


if(Conditional expression) { 
Process 1
} else {
Process 2
};

Process 1 is executed when the conditional expression is true, and process 2 is executed when the conditional expression is false.

For example, ** if the conditional expression is true. ** **

Example if if is true


String name1 = "Yanagita";
String name2 = "Yanagita";
if (name1 == name2) {
  System.out.println("name1 and name2 are the same");
} else {
  System.out.println("name1 and name2 are not the same");
}
System.out.println("if-Processing after the else statement");

The execution result is as follows.

Execution result


name1 and name2 are the same
if-Processing after the else statement

Since the conditional expression is true, the processing inside the if statement block is executed. Then, the inside of the else block is not executed, and the processing outside the if statement block is executed. It will be the flow.

** If the conditional expression is false. ** **

Example if if is false


String name1 = "Cristiano Ronaldo";
String name2 = "Lionel Messi";
if (name1 == name2) {
  System.out.println("name1 and name2 are the same");
} else {
  System.out.println("name1 and name2 are not the same");
}
System.out.println("if-Processing after the else statement");

The execution result is as follows.

Execution result


name1 and name2 are not the same
if-Processing after the else statement

Since the conditional expression is false, the processing inside the if statement block is not executed, and the processing of the else statement block is being executed. Then, the processing outside the if statement block is executed. It will be the flow.

Now you can implement the processing when the conditional expression is false.

else if statement

Until now, there was only one conditional expression, but you can use multiple conditional expressions by using the else if statement.

syntax


if(Conditional expression 1) { 
Process 1
} else if (Conditional expression 2) {
Process 2
} else {
Process 3
};

Process 1 is executed when conditional expression 1 is true, process 2 is executed when conditional expression 2 is true, and process 3 is executed when the first and second conditional expressions are false.

** The else if statement evaluates conditional expressions in order from the top, and if a certain condition is true, only the processing statement in that block is executed. ** **

For example, ** if the conditional expression if is true. ** **

Example if if is true


String color = "red";
if (color == "red") {
  System.out.println("color is red");
} else if (color == "yellow") {
  System.out.println("color is yellow");
} else {
  System.out.println("color is neither red nor yellow");
  System.out.println("color is" + color);
}
System.out.println("else if example");

The execution result is as follows.

Execution result


color is red
else if example

Since the first conditional expression is true, the processing inside the if statement block is executed. Then, the inside of the else if and else blocks is not executed, and the processing outside the if statement block is executed. It will be the flow.

Then ** if the conditional expression else if is true. ** **

else-Example if if is true


String color = "yellow";
if (color == "red") {
  System.out.println("color is red");
} else if (color == "yellow") {
  System.out.println("color is yellow");
} else {
  System.out.println("color is neither red nor yellow");
  System.out.println("color is" + color);
}
System.out.println("else if example");

The execution result is as follows.

Execution result


color is yellow
else if example

Since the first conditional expression is false, the processing inside the if statement block is not executed. And since the second conditional expression is true, the processing inside the else if statement block is executed. The inside of the else block is not executed, and the processing outside the if statement block is executed. It will be the flow.

** Finally, if all of the conditional expressions are false. ** **

Example where all conditional expressions are false


String color = "blue";
if (color == "red") {
  System.out.println("color is red");
} else if (color == "yellow") {
  System.out.println("color is yellow");
} else {
  System.out.println("color is neither red nor yellow");
  System.out.println("color is" + color);
}
System.out.println("else if example");

The execution result is as follows.

Execution result


color is neither red nor yellow
color is blue
else if example

Since the result of the first and second conditional expressions is false, the processing inside the else block is executed. Then, the processing outside the if statement block is executed. It will be the flow.

This makes it possible to divide the processing according to multiple condition judgments.

Ternary operator

An operator that executes an expression according to the result of a conditional expression.

syntax


Conditional expression?Equation 1:Equation 2;

If the conditional expression returns true, then expression 1 is executed, and if false, expression 2 is executed.

For example, ** if the conditional expression is true. ** **

Example of ternary operator


String name = "yamada";
String str = "The length of the name is";
str += name.length() >= 4 ?  "4 or more" : "3 or less";
System.out.println(str);

The execution result is as follows.

Execution result


Name length is 4 or more

The conditional expression is name.length ()> = 4. If true, 4 or more, and if false, 3 or less is combined with the string stored in str.

If the same process is described by an if-else statement, it will be as follows.

if-In the case of else


String name = "yamada";
String str = "The length of the name is";
if (name.length() >= 4) {
  str += "4 or more";
} else {
  str += "3 or less";
}
System.out.println(str);

The ternary operator is easier to write than the if-else statement.

switch statement

The evaluation result of the expression is compared with the constant, and if they match, the process is executed. This is a method for performing multi-branch processing.

syntax


switch (formula) {
case constant 1:
Process 1;
    break;
case constant 2:
Process 2;
    break;
  default:
Process 3;
}

If the result of the expression matches constant 1, process 1 is executed, and if it matches constant 2, process 2 is executed. If there is no match, the processing below default is executed. (The description of default is optional)

Switch statement example


String color = "blue";

switch (color) {
  case "red":
    System.out.println("color is red");
    break;
  case "yellow":
    System.out.println("color is yellow");
    break;
  case "blue":
    System.out.println("color is blue");
    break;
  default:
    System.out.println("color is" + color);
    break;
}

The execution result is as follows.

Execution result


color is blue

The result of the expression is the string "blue", which matches the third case. Therefore, the processing in it is executed.

Notes on switch statements

Expression data type

The value that can be described in the expression of the switch statement must be a value of one of the data types ** char, byte, short, int, its wrapper class, enum, and String **.

If any other type is specified, a compile error will occur.

Switch statement expression error


double d = 2.0;
switch (d) { // Cannot switch on a value of type double. Only convertible int values, strings or enum variables are permitted
  //abridgement
}

Result of expression

If the result of the expression is ** null **, assuming that the data type of the expression is adhered to, the compilation will succeed but an exception will be thrown at runtime.

Switch statement expression exception thrown


String ex = null;
switch (ex) {
  case "a":
    System.out.println("a");
    break;
  case "b":
    System.out.println("b");
    break;
  default:
    System.out.println("nothing");
    break;
}

Execution result


Exception in thread "main" java.lang.NullPointerException
        at Condition.main(Condition.java:102)

Use operators in ()

There is no problem even if you calculate in ().

Addition,

()Calculation example in


int a = 0;
switch (a + 1) {
  case 0:
    System.out.println("0");
    break;
  case 1:
    System.out.println("1");
    break;
  case 2:
    System.out.println("2");
    break;
}

Execution result


1

Decrement etc.

()Calculation example 2


int a = 0;
switch (--a) {
  case 0:
    System.out.println("0");
    break;
  case 1:
    System.out.println("1");
    break;
  default:
    System.out.println("There is no corresponding number");
    break;
}

Execution result


There is no corresponding number

However, declaring a variable in () will result in a compile error.

()Variable declaration with error


switch (int a = 0;) {
  case 0:
    System.out.println("0");
    break;
  case 1:
    System.out.println("1");
    break;
  case 2:
    System.out.println("2");
    break;
}

Value specified in case

(1) If the data type of the result of the expression and the data type specified in case do not match, a compile error will occur.

Error of the value specified in case


int num = 10;
switch (num) {
  case "0": // Type mismatch: cannot convert from String to int
    System.out.println("0");
    break;
  case "1": // Type mismatch: cannot convert from String to int
    System.out.println("1");
    break;
  case "2": // Type mismatch: cannot convert from String to int
    System.out.println("2");
    break;
}

(2) If it is not a literal or a constant, a compile error will occur.

Error 2 of the value specified in case


int num = 10;
int a = 1;
int b = 2;
switch (num) {
  case a: // case expressions must be constant expressions
    System.out.println("1");
    break;
  case b: // case expressions must be constant expressions
    System.out.println("2");
    break;
  default:
    System.out.println("nothing");
    break;
}

In this case, an error will occur because the variables a and b are specified in the case. Add the final qualifier to make it a constant, or specify a literal.

Error 2 correction ver of the value specified in case


int num = 10;
final int a = 1;

switch (num) {
  case a:
    System.out.println("1");
    break;
  case 2:
    System.out.println("2");
    break;
  default:
    System.out.println("nothing");
    break;
}

(3) If null is specified, a compile error will occur.

Error 3 of the value specified in case


String name = "Tanaka";

switch (name) {
  case "Yamada":
    System.out.println("Yamada");
    break;
  case null: // case expressions must be constant expressions
    System.out.println("null");
    break;
}

④ Presence or absence of break statement

The word ** break; ** is missing from the switch statement after the `process has been executed. `` If you forget it, you will be comparing it with the next case for the first time, so be careful.

When you forget to break


int num = 10;

switch (num) {
  case 0:
    System.out.println("0");
    break;
  case 10:
    System.out.println("10");
    // break;Forgot to write
  default:
    System.out.println("nothing");
    break;
}

After the process in case 10 is executed, the default process is also executed because there is no break statement.

Execution result


10
nothing

Be careful not to get an unintended execution result.

At the end

I learned how to branch the process according to the conditions as the process procedure of the program. Considering the readability of the source code, I would like to use it properly depending on the situation.

Reference site

** Branch of processing ** ** Java switch statement **

Recommended Posts

[Introduction to Java] Conditional branching (if statement, if-else statement, else if statement, ternary operator, switch statement)
Java study # 4 (conditional branching / if statement)
[Java] Conditional branching is an if statement, but there is also a conditional operator.
Java conditional branching: How to create and study switch statements
I want to simplify the conditional if-else statement in Java
Java, if statement / switch statement starting from beginner
[Java] "Setting" using Enum rather than conditional branching by if statement -Strategy Enum
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
[Java] Introduction to Java
Introduction to java
Conditional branching of the result of SQL statement to search only one in Java
Java switch statement
10 Corresponds to if statement
Introduction to java command
Java review ③ (control syntax [if / switch / while / for], conditional expression)
Java if and switch statements
[Java] Introduction to lambda expressions
[Java] Introduction to Stream API
java (conditional branching and repetition)
[Introduction to rock-paper-scissors games] Java