JavaRush /Java Blog /Random EN /Branching in Java

Branching in Java

Published in the Random EN group
In this article we will look at the concept of branching in computer programs in general and those written in Java. Let's talk about control structures such as:
  • if-then(or if)
  • if-then-else(or if-else)
  • switch-case
Branching in Java - 1

Branching

Let's start with the basic concepts. Any program is a set of commands executed by a computer. Most often, commands are executed sequentially, one after another. Slightly less often (but still quite often) situations arise when you need to change the sequential flow of program commands. Sometimes, depending on certain conditions, it may be necessary to execute one block of commands instead of another. And when these conditions change, do the opposite. For example, there are a number of sites that are prohibited for persons under 18 years of age to visit. Usually, when visiting such a resource for the first time, the user is greeted with some form in which the user is warned about the age limit and asked to enter his date of birth. Then, depending on the data that the user entered, he will either be allowed to enter the resource or not. This functionality is provided by what is commonly called branching. Let's give another analogy. Let's imagine ourselves at the crossroads of seven roads. We are faced with a choice: turn left or right, or go straight. Our choice is based on certain conditions. We also do not have the opportunity to take several roads at the same time. Those. depending on some conditions, we will have to choose one road. The same principle applies to branching. Now let's try to give a definition of branching. Branching is an algorithmic construction in which, depending on the truth of some condition, one of several sequences of actions is performed. Branching is implemented (most likely) in absolutely all programming languages. The Java programming language has several so-called control constructs that allow you to implement branching in your program. There are 3 such constructions in the programming language:
  • Operatorif-then
  • Operatorif-then-else
  • Ternary operator? :
In this article we will look at the if-elseand operators switch-case.

if-then

Operator if-then, or simply ifperhaps the most common operator. The expression “yes, write 1 if” has already become popular. The operator ifhas the following structure:
if (bool_condition) {
	statement
}
In this design:
  • bool_conditionis a boolean expression that evaluates to true or false. This expression is called a condition.
  • statement— a command (there may be more than one) that must be executed if the condition is true ( bool_statement==true)
This construction can be read like this:

Если (bool_condition), то {statement}
Here are some examples:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Сколько процентов заряда батареи осталось на вашем смартфоне?");
    int a = scanner.nextInt();

    if (a < 10) {
        System.out.println("Осталось менее 10 процентов, подключите ваш смартфон к зарядному устройству");
    }
}
In this program, the user is asked to enter the percentage of battery charge on his smartphone. If less than 10 percent of the charge remains, the program will warn the user about the need to charge the smartphone. This is an example of the simplest design if. It is worth noting that if the variable `a` is greater than or equal to 10, then nothing will happen. The program will continue to execute the code that follows the if. Also note that in this case, the construct ifhas only one sequence of actions to execute: print the text, or do nothing. This is a variation of branching with one “branch”. This is sometimes necessary. For example, when we want to protect ourselves from incorrect values. For example, we cannot find out the number of letters in a string if the string is null. Examples below:
public static void main(String[] args) {
    String x = null;
    printStringSize(x);
    printStringSize("Не представляю своей жизни без ветвлений...");
    printStringSize(null);
    printStringSize("Ифы это так захватывающе!");
}

static void printStringSize(String string) {
    if (string != null) {
        System.out.println("Кол-во символов в строке `" + string + "`=" + string.length());
    }
}
As a result of executing the main method, the following will be output to the console:

Количество символов в строке `Не представляю своей жизни без ветвлений...`=43
Количество символов в строке `Ифы это так захватывающе!`=25
Thanks to checking that string != null, we were able to avoid errors in the program. And do nothing in cases where the variable stringwas equal to null.

if-then-else

If, under normal conditions, ifa program has a choice: “to do something or not to do anything,” then when if-elsechoosing a program it comes down to “doing either one thing or another.” The “do nothing” option disappears. There are two or more variants of execution (or number of branches) with this type of branching. Let's consider the case when there are two options. Then the control structure has the following form:
if (bool_condition) {
	statement1
} else {
	statement2
}
Here:
  • bool_statementis a boolean expression that evaluates to true or false. This expression is called a condition.
  • statement1— a command (there may be more than one) that must be executed if the condition is true ( bool_statement==true)
  • statement2— a command (there may be more than one) that must be executed if the condition is false ( bool_statement==false)
This construction can be read like this:

Если (bool_condition), то {statement1}
Иначе {statement2}
Here's an example:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Сколько процентов заряда батареи осталось на вашем смартфоне?");
    int a = scanner.nextInt();

    if (a < 10) {
        System.out.println("Осталось менее 10 процентов, подключите ваш смартфон к зарядному устройству");
    } else {
        System.out.println("Заряда вашей батареи достаточно для того, чтобы прочитать статью на Javarush");
    }
}
The same example about the battery level on a smartphone. Only if last time the program only warned about the need to charge the smartphone, this time we have an additional notification. Let's look at this one if:
if (a < 10) {
    System.out.println("Осталось менее 10 процентов, подключите ваш смартфон к зарядному устройству");
} else {
    System.out.println("Заряда вашей батареи достаточно для того, чтобы прочитать статью на Javarush");
}
If a < 10true (battery level less than 10), the program will print one text. Otherwise, if the condition a < 10is not met, the program will output completely different text. Let's also finalize our second example, in which we displayed the number of letters in a line. Last time the program did not output anything if the passed string was equal to null. Let's fix this by turning the normal one ifinto if-else:
public static void main(String[] args) {
    String x = null;
    printStringSize(x);
    printStringSize("Не представляю своей жизни без ветвлений...");
    printStringSize(null);
    printStringSize("Ифы это так захватывающе!");
}

static void printStringSize(String string) {
    if (string != null) {
        System.out.println("Кол-во символов в строке `" + string + "`=" + string.length());
    } else {
        System.out.println("Ошибка! Переданная строка равна null!");
    }
}
In the method , we added a block printStringSizeto the construction . Now, if we run the program, it will output to the console not 2 lines, but 4, although the input (method ) remains the same as last time. The text that the program will output: ifelsemain

Ошибка! Переданная строка равна null!
Кол-во символов в строке `Не представляю своей жизни без ветвлений...`=43
Ошибка! Переданная строка равна null!
Кол-во символов в строке `Ифы это так захватывающе!`=25
Situations are acceptable when elsethey are followed not by execution commands, but by another if. Then the construction takes the following form:
If (bool_condition1) {
	statement1
} else if (bool_condition2) {
	statement2
} else if (bool_conditionN) {
	statementN
} else {
	statementN+1
}
This design has several conditions:
  • bool_condition1
  • bool_condition2
  • bool_conditionN
The number of such conditions is not limited. Each condition has its own commands:
  • statement1
  • statement2
  • statementN
Each one statementcan contain 1 or more lines of code. The conditions are checked one by one. Once the first true condition is determined, a series of commands “tied” to the true condition will be executed. After executing these commands, the program will exit the block if, even if there were more checks ahead. The expression “statementN+1” will be executed if none of the conditions defined above are true. This construction can be read like this:

Если (bool_condition1) то {statement1}
Иначе если (bool_condition2) то {statement2}
Иначе если (bool_conditionN) то {statementN}
Иначе {statementN+1}
The last line in this case is optional. You can do without the last lonely one else. And then the design will take the following form:
If (bool_condition1) {
	statement1
} else if (bool_condition2) {
	statement2
} else if (bool_conditionN) {
	statementN
}
And it will read like this:

Если (bool_condition1) то {statement1}
Иначе если (bool_condition2) то {statement2}
Иначе если (bool_conditionN) то {statementN}
Accordingly, if none of the conditions are true, then not a single command will be executed. Let's move on to examples. Let's return to the situation with the charge level on the smartphone. Let's write a program that will inform the owner in more detail about the charge level of his device:
public static void main(String[] args) {
    String alert5 = "Я скоро отключусь, но помни меня бодрым";
    String alert10 = "Я так скучаю по напряжению в моих жилах";
    String alert20 = "Пора вспоминать, где лежит зарядка";
    String alert30 = "Псс, пришло время экономить";
    String alert50 = "Хм, больше половины израсходовали";
    String alert75 = "Всё в порядке, заряда больше половины";
    String alert100 = "Я готов к приключениям, если что..";
    String illegalValue = "Такс, кто-то ввел некорректное meaning";

    Scanner scanner = new Scanner(System.in);
    System.out.print("Сколько процентов заряда батареи осталось на вашем смартфоне?");
    int a = scanner.nextInt();

    if (a <= 0 || a > 100) {
        System.out.println(illegalValue);
    } else if (a < 5) {
        System.out.println(alert5);
    } else if (a < 10) {
        System.out.println(alert10);
    } else if (a < 20) {
        System.out.println(alert20);
    } else if (a < 30) {
        System.out.println(alert30);
    } else if (a < 50) {
        System.out.println(alert50);
    } else if (a < 75) {
        System.out.println(alert75);
    } else if (a <= 100) {
        System.out.println(alert100);
    }
}
For example, in this case, if the user enters 15, the program will display on the screen: “It’s time to remember where the charger is.” Despite the fact that 15 is less and 30 and 50 and 75 and 100, the output on the screen will be only 1. Let's write another application that will print to the console what day of the week it is:
public static void main(String[] args) {
    // Определим текущий день недели
    DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();

    if (dayOfWeek == DayOfWeek.SUNDAY) {
        System.out.println("Сегодня воскресенье");
    } else if (dayOfWeek == DayOfWeek.MONDAY) {
        System.out.println("Сегодня понедельник");
    } else if (dayOfWeek == DayOfWeek.TUESDAY) {
        System.out.println("Сегодня вторник");
    } else if (dayOfWeek == DayOfWeek.WEDNESDAY) {
        System.out.println("Сегодня среда");
    } else if (dayOfWeek == DayOfWeek.THURSDAY) {
        System.out.println("Сегодня четверг");
    } else if (dayOfWeek == DayOfWeek.FRIDAY) {
        System.out.println("Сегодня пятница");
    } else if (dayOfWeek == DayOfWeek.SATURDAY) {
        System.out.println("Сегодня суббота");
    }
}
It’s convenient, of course, but the abundance of monotonous text dazzles your eyes a little. In situations where we have a large number of options, it is better to use the operator, which will be discussed below.

switch-case

An alternative to bold ifwith a lot of branches is the operator switch-case. This operator seems to say “So, we have this variable. Look, if its value is equal to `x`, then we do this and that, if its value is equal to `y`, then we do it differently, and if it is not equal to any of the above, we just do it like this... ” This operator has the following structure.
switch (argument) {
	case value1:
		statement1;
		break;
	case value2:
		statement2;
		break;
	case valueN:
		statementN;
		break;
	default:
		default_statement;
		break;
}
Let's look at this structure in more detail. argument is a variable whose value we will compare with hypothetical different options. The variable must be final. It is also worth saying that the operator switchdoes not support any data type as an argument. Valid types are listed below:
  • byte and Byte
  • short and short
  • int and Integer
  • char and Character
  • enum
  • String
case value1 (value2, valueN)- these are values, specific constants with which we compare the value of a variable argument. Also, each case defines a set of commands that need to be executed. statement1, statement2, statementNare commands that will need to be executed if argumentit turns out to be equal to one of value. For example, if argumentit is equal to value2, then the program will execute statement2. defaultand default_statementare “default values”. If argumentit is not equal to any of the ones presented value, then the branch will be triggered defaultand the command will be executed default_statement. defaultand default_statementare optional attributes of the operator switch-case. break— you can notice that at the end of each case block there is a statement break. This operator is also optional and serves to differentiate the code of different cases. Sometimes it is necessary to perform the same actions in different cases: then these cases can be combined. In this case, the keyword breakis omitted, and the structure of the operator switch-casewill look like this:
switch (argument) {
	case value1:
		statement1;
		break;
	case valueX:
	case valueY:
		statementXY;
		break;
}
It's worth noting that there is no operator between `case valueX:` and `case valueY:` break. Here, if argumentit is equal to value1, it will be executed statement1. And if argument is equal valueXto either valueY, statementXY. Let’s dilute the difficult-to-understand theory into easy-to-understand practice. Let's rewrite the example with days of the week using the operator switch-case.
public static void main(String[] args) {
    // Определим текущий день недели
    DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();

    switch (dayOfWeek) {
        case SUNDAY:
            System.out.println("Сегодня воскресенье");
            break;
        case MONDAY:
            System.out.println("Сегодня понедельник");
            break;
        case TUESDAY:
            System.out.println("Сегодня вторник");
            break;
        case WEDNESDAY:
            System.out.println("Сегодня среда");
            break;
        case THURSDAY:
            System.out.println("Сегодня четверг");
            break;
        case FRIDAY:
            System.out.println("Сегодня пятница");
            break;
        case SATURDAY:
            System.out.println("Сегодня суббота");
            break;
    }
}
Now let's write a program that displays whether today is a weekday or a weekend using the operator switch-case.
public static void main(String[] args) {
    // Определим текущий день недели
    DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();

    switch (dayOfWeek) {
        case SUNDAY:
        case SATURDAY:
            System.out.println("Сегодня выходной");
            break;
        case FRIDAY:
            System.out.println("Завтра выходной");
            break;
        default:
            System.out.println("Сегодня рабочий день");
            break;

    }
}
Let me explain a little. In this program we get enum DayOfWeek, which denotes the current day of the week. Next, we look to see if the value of our variable is equal to dayOfWeekthe values ​​of SUNDAYeither SATURDAY. If this is the case, the program displays “Today is a day off.” If not, then we check whether the value of the variable is equal to dayOfWeekthe value of FRIDAY. If this is the case, the program displays “Tomorrow is a day off.” If in this case there is no, then we have few options, any remaining day is a weekday, so by default, if today is NOT Friday, NOT Saturday and NOT Sunday, the program will display “Today is a working day.”

Conclusion

So, in this article we looked at what branching is in a computer program. We also figured out what control structures are used to implement branching in Java. We discussed designs such as:
  • if-then
  • if-then-else
  • switch-case
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION