- Тип данных boolean и логические операторы — введение в Java 005 #
- Логические операторы, которые поддерживаются Java #
- Булева алгебра #
- Дизъюнкция #
- Конъюнкция #
- Антиваленц #
- Отрицание #
- Дополнительные материалы #
- Домашнее задание #
- Java Booleans
- Boolean Values
- Example
- Boolean Expression
- Example
- Example
- Example
- Example
- Real Life Example
- Example
- Example
- Booleans in Java explained
- How Boolean works in Java
- How to use Boolean variable/expression in Java
- Example 1: Creating a Boolean variable
- Example 2: Getting the Boolean expression for decision
- Example 3: Making use of Boolean operators
- Conclusion
Тип данных boolean и логические операторы — введение в Java 005 #
Boolean в Java — это логический тип данных. Переменная типа boolean может принимать всего два значения — это правда или ложь — true & false. Эти два значения обозначаются в других языках и часто выдаются на экран как 1 и 0, но всё же не равны этим значениям: например, выражение boolean b = 0; приведёт к ошибке при компиляции программы. Но мы можем сравнить переменные или выполнить логическую операцию с типом данных boolean:
int a = 1, b = 2; boolean bool = a
Говоря о булевых или логических типах данных, нам придётся освежить свои воспоминания о булевой алгебре и возможных логических операциях.
Таблица истинности #
a | b | a & b | a I b | a ^ b | ! a |
---|---|---|---|---|---|
false | false | false | false | false | true |
false | true | false | true | true | true |
true | false | false | true | true | false |
true | true | true | true | false | false |
Давайте представим себе пример из жизни: мы ищем на сайте все статьи, которые мы опубликовали и комментировали. Должны быть два совпадения — это вариант a & b. Или мы ищем все статьи, в которых есть упоминание слов “алгебра” или “математика” — это a | b. А отыскать все статьи, которые написаны не нами, можно, применив логический оператор !a. Стать исключительно космонавтом или медиком — это a ^ b
Это так называемые булевы или логические операции. В интернете много материала по ключевым словам: таблица истинности, булева алгебра, теория множеств, конъюнкция, дизъюнкция.
С помощью таблицы с результатами логических операций можно перепроверить работу Java:
public class NewBoolean public static void main(String[] args) boolean a, b, c; a = true; b = false; c = a & b; System.out.println(c); // returns false because only one of the two required valuesis true int d = 1, f = 2; boolean bool = d f; int i = 10; int j = 9; System.out.println(i > j); // returns true, because 10 is higher than 9 System.out.println(10 == 15); // returns false, because 10 is not equal to 15 int x = 10; System.out.println(x == 10); // returns true, because the value of x is equal to 10 > >
Надо понимать, что значение вашего чекбокса (галочки) на сайте Facebook при регистрации — “с правилами ознакомлен и согласен” — и есть значение булевой переменной в программе.
Логические операторы, которые поддерживаются Java #
Логический операторы | Значение |
---|---|
== | Проверка на соответствие (допустим, что a равен b) |
!= | Не равно (если a не равно b, то) |
! | Отрицание, логическое не |
& | Логическое И, and |
| | Логическое или, or |
^ | Исключительное или, XOR |
&& | Укороченный & |
|| | Укороченный или |
Амперсанд — это название знака &.
Карет (англ. caret) — это название знака ^.
Пайп (pipeline), Вертикальная черта — это название знака |.
Мы ещё раз рассмотрим данные операторы позже. Пока мы должны понимать, что с арифметическими операторами всё немного сложнее, чем хотелось бы.
Булева алгебра #
Булева алгебра, ударение на первый слог. БУлева.
Принципиально основы булевой алгебры не должны были давать в школе. Программисты учат её в институте.
Давайте я попробую на пальцах рассказать основы и то, что нам понадобится на минимальном уровне.
Дизъюнкция #
Когда мама ИЛИ папа дают мне деньги на карманные расходы, то я бегу и покупаю себе мороженное.
Знакомая ситуация, деньги можно получить в трёх случах из четырёх. В одном случае же деньги может дать и мама, и папа, тогда и друга можно угостить мороженным.
Дизъюнкция - логическое сложение, логическое ИЛИ, включающее или, просто “или”(англ. OR; нем. ODER) В Java операторы "|" и "||"
boolean a = false, b = true, c; c = a | b;
Пример в технике; дублирование выключателя или кнопки, дверной звонок и звонок у калитки вызывают одну и туже реакцию - включается мелодия звонка.
В учебниках можно встретить обозначение “больше либо равно единице” - =>1.
Конъюнкция #
Конъюнкция - логическое “И”, логическое умножение, просто “И”, “AND”, "&".
В Java оператор "&" и "&&".
boolean a = false, b = true, c; c = a & b;
Если светит солнце “И” у меня выходной, то я иду купаться на озеро.
Пример из жизни. Ядерный чемоданчик могут активировать только два офицера одновременно. По отдельности чемодан остаётся неактивным.
Антиваленц #
“XOR”, эксклюзивное или, “EOR”, “EXOR”. В Java оператор "^".
boolean a = false, b = true, c; c = a ^ b;
Только на горных лыжах в Австрии или на лошадях у бабушки в деревне я забываю про свою работу.
Или ты садишься за математику или я расскажу всё отцу.
ИЛИ - ИЛИ. Исключительное или.
Лампочка в больнице может работать от городского электричества или от дизельного генератора в подвале. Но не от двух источников одновременно.
В учебниках можно встретить обозначение “равно единице” - =1.
Отрицание #
Negation. NOT. В Java оператор "!".
Давайте представим огромный станок по продольной распилке леса. В цеху есть две кнопки. Зелёная и красная. При включении зелёной пила должна работать. При нажатии на красную пила должна остановится.
Дополнительные материалы #
- Булева алгебра — самое важное
- Булева алгебра
- Теория множеств
- Очень неплохая статья
- simulator — симулятор логических выражений в электротехнике. Очень помог мне в своё время вспомнить булеву алгебру.
Домашнее задание #
- Что выдаст программа, если запросить значения a, b, c, d, e, f?
- Посчитайте сначала в уме и проговорите вслух, что делает каждая строчка.
boolean a = (7+8)*5 > 7+8*5; boolean b = (7+8)*4 != 7+4*5; boolean c = 3+4 > 9+1 & 16-5 > 3*4; boolean d = 16/2 < 6+2 | 4+5
System.out.println(a + "\n" + b + "\n" + c + "\n" + d + "\n" + e);
- Петя: “Я не ел. Маша тоже не ела.”
- Вася: “Маша действительно не ела. Это сделал Петя”
- Маша: “Вася врет. Это он съел.”
Выясните, кто ел варенье, если известно, что двое из них оба раза сказали правду, а третий один раз соврал, а один раз сказал правду.
Java Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
For this, Java has a boolean data type, which can store true or false values.
Boolean Values
A boolean type is declared with the boolean keyword and can only take the values true or false :
Example
boolean isJavaFun = true; boolean isFishTasty = false; System.out.println(isJavaFun); // Outputs true System.out.println(isFishTasty); // Outputs false
However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).
Boolean Expression
A Boolean expression returns a boolean value: true or false .
This is useful to build logic, and find answers.
For example, you can use a comparison operator, such as the greater than ( > ) operator, to find out if an expression (or a variable) is true or false:
Example
int x = 10; int y = 9; System.out.println(x > y); // returns true, because 10 is higher than 9
Example
System.out.println(10 > 9); // returns true, because 10 is higher than 9
In the examples below, we use the equal to ( == ) operator to evaluate an expression:
Example
int x = 10; System.out.println(x == 10); // returns true, because the value of x is equal to 10
Example
System.out.println(10 == 15); // returns false, because 10 is not equal to 15
Real Life Example
Let's think of a "real life example" where we need to find out if a person is old enough to vote.
In the example below, we use the >= comparison operator to find out if the age ( 25 ) is greater than OR equal to the voting age limit, which is set to 18 :
Example
int myAge = 25; int votingAge = 18; System.out.println(myAge >= votingAge);
Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above in an if. else statement, so we can perform different actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18 . Otherwise output "Not old enough to vote.":
int myAge = 25; int votingAge = 18; if (myAge >= votingAge) < System.out.println("Old enough to vote!"); >else
Booleans are the basis for all Java comparisons and conditions.
You will learn more about conditions ( if. else ) in the next chapter.
Booleans in Java explained
The datatypes in Java are categorized into two broader categories. One is primitive and the other is the non-primitive data type. Boolean belongs to the primitive data type of Java. Java Boolean variable takes either true or false value, and thus a Boolean variable or expression plays a vital role in decision making for programmers. This article provides an informative guide about Java Boolean and Java expression. The following are the learning outcomes of this guide:
- understanding the working of Boolean variable/expression
- examples that clarify the concept of Boolean in Java
How Boolean works in Java
As discussed earlier, a Boolean variable/expression helps in making a decision between various conditions. The syntax to create a Boolean variable is described below:
- the boolean is the keyword used to declare a Boolean variable in Java
- the variable-name is user-defined a
- lastly, it can store only true/false values, therefore the value may be true/false while declaring a Boolean variable.
The above syntax only considers Boolean variables. Whereas the Boolean expression returns the true or false value after going through the condition.
How to use Boolean variable/expression in Java
This section briefly presents few examples that demonstrate the usage of a Boolean variable and expression.
Example 1: Creating a Boolean variable
Following the syntax in the above section, you can create a Boolean variable. For instance, the following statements create two Boolean variables a and b respectively. Moreover, the value assigned to a is true and false value is stored in b variable.
For better understating, the above statements are used in the following Java code:
public static void main ( String [ ] args ) {
//initializing two boolean variables
System. out . println ( "The value of a : " + a ) ;
System. out . println ( "The value of b is: " + b ) ;
The above code is described as:
The code written above initializes two boolean variables and then prints them. The screenshot of the output is provided below:
Example 2: Getting the Boolean expression for decision
The primary purpose of the Boolean expression is to assist in making the decision. A Boolean expression returns a Boolean value (true/false). The Java code provided below shows several conditions are tested on two integers and returns the Boolean expression true or false (depending on the true/false of condition).
public static void main ( String [ ] args ) {
//initializes two variables
//checking various conditions
System. out . println ( a > b ) ;
System. out . println ( a == b ) ;
The output of the above code is displayed in the following image:
Example 3: Making use of Boolean operators
The Boolean operators help in comparing multiple conditions on Boolean variables. Several logical operators can be applied to Boolean variables and they are referred to as Boolean operators as well. The following code practices few Boolean operators on Boolean variables to get the result on the basis of decisions made by Boolean operators.
public static void main ( String [ ] args ) {
//initializes two boolean variables
boolean a = true , b = false ;
System. out . println ( a | b ) ;
//using NOT(!) and equals(==) operator
System. out . println ( ! ( a == b ) ) ;
The output of the code is provided below:
- initializes two Boolean variables
- applies OR (I) on a and b: The OR operator returns true if one of the a and b values is true.
- applies AND (&) operator on a and b: The AND operator returns false if one a and b is false.
- applies NOT (!) and equal (==) operators: As condition a==b is false, and alongside it NOT(reverses the output) operator is used, so the output will be true.
For further guidance, the following table represents how Boolean OR and AND behave against various Boolean values:
Boolean Value1 | Operator | Boolean Value2 | output |
---|---|---|---|
True | | (OR) | False | True |
False | | (OR) | True | True |
True | | (OR) | True | True |
False | | (OR) | False | False |
True | & (AND) | False | False |
False | & (AND) | True | False |
True | & (AND) | True | True |
False | & (AND) | False | False |
Conclusion
The Boolean variable in Java stores true or false values whereas a Boolean expression returns a true or false value. These terms are used in Java for decision-making and for checking the various conditions. This post provides the demonstration of Boolean variables and expressions in Java. You would have learned the initialization of Boolean variables. Moreover, we have also provided a few examples that show how Boolean variables and expressions can be useful for decision making.