Operator for boolean java

Operator for boolean java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java
Читайте также:  Вставить символ по коду html

Источник

Тип данных 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 values​is 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 оператор "!".

Давайте представим огромный станок по продольной распилке леса. В цеху есть две кнопки. Зелёная и красная. При включении зелёной пила должна работать. При нажатии на красную пила должна остановится.

Дополнительные материалы #

  1. Булева алгебра — самое важное
  2. Булева алгебра
  3. Теория множеств
  4. Очень неплохая статья
  5. simulator — симулятор логических выражений в электротехнике. Очень помог мне в своё время вспомнить булеву алгебру.

Домашнее задание #

  1. Что выдаст программа, если запросить значения a, b, c, d, e, f?
  2. Посчитайте сначала в уме и проговорите вслух, что делает каждая строчка.
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); 
  1. Петя: “Я не ел. Маша тоже не ела.”
  2. Вася: “Маша действительно не ела. Это сделал Петя”
  3. Маша: “Вася врет. Это он съел.”

Выясните, кто ел варенье, если известно, что двое из них оба раза сказали правду, а третий один раз соврал, а один раз сказал правду.

Источник

Boolean Operators in Java

Boolean operators in Java

With the advent of technology, computers have developed, which in turn brought the requirement for programming language. Many programming languages include both low-level language as well as high-level language. High-level languages are easier to use as they are easy to understand in comparison to low-level languages. Java is one such high-level language which is used widely as a backed language for programming purpose. There are lots of a concept that one needs to study and practice to understand basic concepts. In this topic, we will be discussing Boolean operators in Java.

Web development, programming languages, Software testing & others

What is Boolean Operator?

Boolean operators are simply a set of different operators that could be used to compare expressions. Boolean operators generally have two values, either false or true. Boolean operators compare the expression of the left-hand side and the right-hand side. In comparison, it simply returns a Boolean value.

Types of Boolean Operators in Java

There are various types of Boolean operators in Java. Following are the various types of Boolean operators in Java that are most widely used.

Types of Boolean Operators in Java

1. Logical AND Operator

This is a logical assignment that use the && operator to compare logical expression. It generally gives false if any of the multiple logic fails or gives true if all the expression produces true.

Example of AND operator

Now, execute the above code

Now, execute the above code

Now, execute the above code

Now, execute the above code

2. Logical OR Operator

This is a logical assignment which uses || operator to compare logical expression. It generally gives true if any of the expression becomes true and returns false if all the expression fails.

Example of OR operator

Now, execute the above code

Now, execute the above code

Now, execute the above code

Now, execute the above code

3. Equal to Operator

This operator is used to check if operand or expression on both sides of the operator are equal or not.

Example of Equal to operator

Now, execute the above code

Now, execute the above code

4. Not Equal to Operator

This operator is used to check if operand or expression on both sides of the operator are equal or not. It produces true if operands on both sides are not the same; else gives false.

Examples of not equal to operator

Now, execute the above code

Now, execute the above code

5. Ternary Operator

This operator is used to check if else conditions. It is generally shorthand for the if-else statement. If the expression is true, then if the part is executed otherwise, else block is executed. It uses two operands which are ?:

Example of Ternary Operator

Conclusion

Java is a programming language where there are lots of concepts that one needs to study. Boolean operators are one of those. These boolean operators basically execute the code to check whether the expression value is true or not. Based on the expression evaluation, it returns the value. A boolean operator is widely used in any programming language to various logical programming expressions.

This has been a guide to Boolean operators in Java. Here we discuss the basic concept and different types of Boolean operators in Java-like Logical AND, Logical OR, Equal to, Not equal to, Ternary Operator with respective examples. You can also go through our other suggested articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle - 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Оцените статью