Java if and only if statement

Java Control Flow Statements: if. else and switch

This post provides description and code examples of the Java control flow statements.

Java if Statement

The syntax of the if statement is:

The if keyword is used to check if a condition is true or not. If it is true, then the specified code inside the curly braces are executed.

Note: The condition inside the parentheses must be a boolean expression. That is, the result of the expression must either evaluate to true or false.

We use the usual mathematical operators to evaluate a condition:

  • Less than — a < b
  • Less than or equal to — a
  • Greater than — a > b
  • Greater than or equal to — a >= b
  • Equal to — a == b
  • Not Equal to — a != b

We can either use one condition or multiple conditions, but the result should always be a boolean.

When using multiple conditions, we use the logical AND && and logical OR || operators.

Example using logical OR in if statement:

if(month == 'December' || month == 'January')

Example using logical AND in if statement:

if(month == 'December' && day == '25')

Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.

Java else Statement

If the result of the if statement evaluates to false and we want to action on the result, then we use the else statement.

The else statement is followed immediately after the closing braces of the if statement.

int temperature; if(temperature else

In the above example, if temperature is 0 or less than 0, the “Water in solid state” is printed to the console. The else statement will not be executed.

If however, the temperature is greater than 0, the “Water in liquid state” is printed to the console.

Short Hand if…else Statement

We can also use short hand notation for the if. else statement which is knows as the ternary operator.

Syntax for the ternary operator is:

variable = (condition) ? expressionTrue : expressionFalse; 

First, evaluate the condition in () . If the operation evaluates to true, then execute the expression between ? and : , else execute the condition after the : .

A way that helps me remember this is: (condition) ? true : false

Java else if Statement

We can use multiple if and else statements as long as a condition is not met.

The syntax for else if is:

if(condition1) < //execute some code only if condition1 evaluates to true >else if(condition2) < //execute some code if condition2 evaluates to true >else < //execute code is both conditions evaluate to false >
int temperature; if(temperature else if(temperature >= 100) < System.out.println("Water in gas state"); >else

Java switch Statement

Another way to control the flow of the program is via a switch statement. The switch statement is used when we have a number of options and in each case we execute different code.

It acts similar to multiple if. else statements.

The switch Syntax

The syntax of the switch statement is:

First an expression is evaluated. The outcome of the expression is compared against each case . if the outcome of the expression matches any of the case conditions, the associated block of code is executed.

The break keyword is used to exit the switch block. This is important because once a match is found, we don’t want to continue to evaluate other case conditions.

The default keyword is executed if no case match the value of the switch expression.

Both break and default are optional, but is recommended for good coding practice.

Example switch Statement

The code below uses the switch statement to see if the language is supported or not

String lang = "en"; switch (lang)

Summary

In this article, we covered the Java control flow statements which are if , else if and switch statements.

Источник

If, If..else Statement in Java with Examples

When we need to execute a set of statements based on a condition then we need to use control flow statements. For example, if a number is greater than zero then we want to print “Positive Number” but if it is less than zero then we want to print “Negative Number”. In this case we have two print statements in the program, but only one print statement executes at a time based on the input value. We will see how to write such type of conditions in the java program using control statements.

In this tutorial, we will see four types of control statements that you can use in java programs based on the requirement: In this tutorial we will cover following conditional statements:

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

If statement

If statement consists a condition, followed by statement or a set of statements as shown below:

if statement flow diagram

The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.

Example of if statement

public class IfStatementExample < public static void main(String args[])< int num=70; if( num < 100 )< /* This println statement will only execute, * if the above condition is true */ System.out.println("number is less than 100"); >> >

Nested if statement in Java

When there is an if statement inside another if statement then it is called the nested if statement.
The structure of nested if looks like this:

Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions( condition_1 and condition_2) are true.

Example of Nested if statement

public class NestedIfExample < public static void main(String args[])< int num=70; if( num < 100 )< System.out.println("number is less than 100"); if(num >50) < System.out.println("number is greater than 50"); >> > >
number is less than 100 number is greater than 50

If else statement in Java

This is how an if-else statement looks:

If else flow diagram

The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if the condition is false.

Example of if-else statement

public class IfElseExample < public static void main(String args[])< int num=120; if( num < 50 )< System.out.println("num is less than 50"); >else < System.out.println("num is greater than or equal 50"); >> >
num is greater than or equal 50

if-else-if Statement

if-else-if statement is used when we need to check multiple conditions. In this statement we have only one “if” and one “else”, however we can have multiple “else if”. It is also known as if else if ladder. This is how it looks:

if(condition_1) < /*if condition_1 is true execute this*/ statement(s); >else if(condition_2) < /* execute this if condition_1 is not met and * condition_2 is met */ statement(s); >else if(condition_3) < /* execute this if condition_1 & condition_2 are * not met and condition_3 is met */ statement(s); >. . . else < /* if none of the condition is true * then these statements gets executed */ statement(s); >

Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met, the corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the statements inside “else” gets executed.

Example of if-else-if

public class IfElseIfExample < public static void main(String args[])< int num=1234; if(num =1) < System.out.println("Its a two digit number"); >else if(num =100) < System.out.println("Its a three digit number"); >else if(num =1000) < System.out.println("Its a four digit number"); >else if(num =10000) < System.out.println("Its a five digit number"); >else < System.out.println("number is not between 1 & 99999"); >> >

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Ветвление в Java

Java-университет

Ветвление в Java - 1

В данной статье мы рассмотрим такое понятие как ветвление в компьютерных программах в общем и написанных на ЯП Java. Поговорим о таких управляющих конструкциях, как:

  • if-then (или же if )
  • if-then-else (или же if-else )
  • switch-case

Ветвление

if-then

Оператор if-then , или же просто if пожалуй самый распространенный оператор. Выражение “да там 1 if написать” уже стало крылатым. Оператор if имеет следующую конструкцию:

  • bool_condition — boolean выражение, результатом которого является true или false. Данное выражение называют условием.
  • statement — команда (может быть не одна), которую необходимо исполнить, в случае, если условие истинно ( bool_statement==true )
 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 процентов, подключите ваш смартфон к зарядному устройству"); >> 

В данной программе пользователю предлагается ввести количество процентов заряда батареи на его смартфоне. В случае, если осталось менее 10 процентов заряда, программа предупредит пользователя о необходимости зарядить смартфон. Это пример простейшей конструкции if . Стоит заметить, что если переменная `а` будет больше либо равна 10, то ничего не произойдет. Программа продолжит выполнять код, который следует за конструкцией if . Также заметим, что в данном случае, у конструкции if есть только одна последовательность действий для исполнения: напечатать текст, либо не делать ничего. Эта вариация ветвления с одной “ветвью”. Такое порой бывает необходимо. Например когда мы хотим обезопасить себя от неправильных значений. К примеру, мы не можем узнать количество букв в строке, если строка равна null . Примеры ниже:

 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 + "` lang-java line-numbers"> if (bool_condition) < statement1 >else
  • bool_statement — boolean выражение, результатом которого является true или false. Данное выражение называют условием.
  • statement1 — команда (может быть не одна), которую необходимо выполнить, если условие истинно ( bool_statement==true )
  • statement2 — команда (может быть не одна), которую необходимо выполнить, если условие ложно ( bool_statement==false )
 Если (bool_condition), то Иначе
 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"); >> 

Тот же пример об уровне заряда батареи на смартфоне. Только если в прошлый раз программа только лишь предупреждала о необходимости зарядить смартфон, то в этот раз у нас появляется дополнительное уведомление. Разберем этот if :

Если a < 10 истинно (уровень заряда батареи меньше 10), программа выведет на печать один текст. Иначе, если условие a < 10 не выполняется, то программа выведет уже совсем другой текст. Доработаем также и второй наш пример, в котором мы выводили на экран количество букв в строке. В прошлый раз программа не выводила ничего, если переданная строка была равна null . Исправим этом, превратив обычный if в 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!"); >> 

В методе printStringSize в конструкцию if мы добавили блок else . Теперь, если мы запустим программу, она выведет в консоль уже не 2 строки, а 4, хотя вводные (метод main ) остались такими же, как и в прошлый раз. Текст, который выведет программа:

 Ошибка! Переданная строка равна null! Кол-во символов в строке `Не представляю своей жизни без ветвлений. `=43 Ошибка! Переданная строка равна null! Кол-во символов в строке `Ифы это так захватывающе!`=25 

Допустимы ситуации, когда после else следуют не команды на исполнение, а еще один if . Тогда конструкция принимает следующий вид:

 If (bool_condition1) < statement1 >else if (bool_condition2) < statement2 >else if (bool_conditionN) < statementN >else
  • bool_condition1
  • bool_condition2
  • bool_conditionN
  • statement1
  • statement2
  • statementN
 Если (bool_condition1) то Иначе если (bool_condition2) то Иначе если (bool_conditionN) то Иначе

Последняя строка в данном случае опциональна. Можно обойтись и без последнего одинокого else . И тогда конструкция примет следующий вид:

 If (bool_condition1) < statement1 >else if (bool_condition2) < statement2 >else if (bool_conditionN)
 Если (bool_condition1) то Иначе если (bool_condition2) то Иначе если (bool_conditionN) то

Соответственно, в случае, если ни одно из условий не окажется истинным, то ни одна команда не будет исполнена. Перейдем к примерам. Вернемся к ситуации с уровнем заряда на смартфоне. Напишем программу, которая будет более детально информировать владельца об уровне заряда его девайса:

 public static void main(String[] args) < String alert5 = "Я скоро отключусь, но помни меня бодрым"; String alert10 = "Я так скучаю по напряжению в моих жилах"; String alert20 = "Пора вспоминать, где лежит зарядка"; String alert30 = "Псс, пришло время экономить"; String alert50 = "Хм, больше половины израсходовали"; String alert75 = "Всё в порядке, заряда больше половины"; String alert100 = "Я готов к приключениям, если что.."; String illegalValue = "Такс, кто-то ввел некорректное значение"; Scanner scanner = new Scanner(System.in); System.out.print("Сколько процентов заряда батареи осталось на вашем смартфоне?"); int a = scanner.nextInt(); if (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 > 

К примеру в данном случае, если пользователь введет 15, то программа выведет на экран: “Пора вспоминать, где лежит зарядка”. Несмотря на то, что 15 меньше и 30 и 50 и 75 и 100, вывод на экран будет только 1. Напишем еще одно приложение, которое будет печатать в консоль, какой сегодня день недели:

 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("Сегодня суббота"); >> 

Удобно конечно, но в глазах немного рябит от обилия однообразного текста. В ситуациях, когда у нас имеются большое количество вариантов лучше использовать оператор, речь о котором пойдет ниже.

switch-case

Альтернативой жирным if с большим количеством ветвей служит оператор switch-case . Данный оператор как бы говорит “Так, у нас есть вот такая вот переменная. Смотрите, в случае, если её значение равно `x`, то делаем то-то и то-то, если ее значение равно `y`, то делаем по-другому, а если ничему не равно из вышеперечисленного, просто делаем вот так… ” Данный оператор обладает следующей структурой.

  • byte and Byte
  • short and Short
  • int and Integer
  • char and Character
  • enum
  • String

Стоит обратить внимание: между `case valueX:` и `case valueY:` нет оператора break . Здесь, если argument будет равен value1 , выполнится statement1 . А если argument будет равен valueX либо valueY , выполнится statementXY . Разбавим тяжелую для восприятия теорию на легкую для восприятия практику. Перепишем пример с днями недели с использованием оператора 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; >> 

Теперь напишем программу, которая выводит информацию о том, является ли сегодняшний день будним днем или выходным, используя оператор 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; >> 

Немного поясним. В данной программе мы получаем enum DayOfWeek , который обозначает текущий день недели. Далее мы смотрим, равняется ли значение нашей переменной dayOfWeek значениям SUNDAY либо SATURDAY . В случае, если это так, программа выводит “Сегодня выходной”. Если же нет, то мы проверяем, равняется ли значение переменной dayOfWeek значению FRIDAY . В случае, если это так, программа выводит “Завтра выходной”. Если же и в этом случае нет, то вариантов у нас немного, любой оставшийся день является будним днем, поэтому по умолчанию, если сегодня НЕ пятница, НЕ суббота и НЕ воскресение программа выведет “Сегодня рабочий день”.

Заключение

Источник

Читайте также:  How to change type in python
Оцените статью