Difference Between & and && in Java
In this section, we will discuss the two most important operators & and && in Java and also see the key differences between logical and bitwise operators along with its uses.

& Operator
The single AND operator (&) is known as the Bitwise AND operator. It operates on a single bit. It takes two operands. A bit in the result is 1 if and only if both of the corresponding bits in the operands are 1. The result of the operator may be any number. For example:
&& Operator
The double AND operators (&&) are known as logical AND operators. It is usually used in loops and conditional statements. It is usually used in Boolean expressions. The result of && is always 0 or 1.
Difference Between & and &&
The key difference between && and & operators is that && supports short-circuit evaluations while & operator does not.
Another difference is that && will evaluate the expression exp1, and immediately return a false value if exp1 is false. While & operator always evaluates both expressions (exp1 and exp2) before retiring an answer.
| S.N. | Basis | & Operator | && Operator |
|---|---|---|---|
| 1 | Operator | It is a bitwise AND operator. | It is a logical AND operator. |
| 2 | Evaluation | It evaluates both the left and right side of the given expression. | It only evaluates the left sides of the given expression. |
| 3 | Operates on | It operates on Boolean data types as well as on bits. | It operates only on Boolean datatype. |
| 4 | Uses | Used to check logical condition and also used to mask off certain bits such as parity bits. | Used only to check the logical conditions. |
| 5 | Example | z = x & y | if (y > 1 && y > x) |
Let’s understand bitwise and logical and operator through a Java program.
LogicalAndExample.java
Output:
true false
BitwiseAndExample.java
Logical AND (&&)
The logical AND ( && ) (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .
More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.
Try it
Syntax
Description
If a value can be converted to true , the value is so-called truthy. If a value can be converted to false , the value is so-called falsy.
Examples of expressions that can be converted to false are:
- false ;
- null ;
- NaN ;
- 0 ;
- empty string ( «» or » or « );
- undefined .
The AND operator preserves non-Boolean values and returns them as they are:
= "" && "foo"; // result is assigned "" (empty string) result = 2 && 0; // result is assigned 0 result = "foo" && 4; // result is assigned 4
Even though the && operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.
Short-circuit evaluation
The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.
Consider the pseudocode below.
(some falsy expression) && expr
The expr part is never evaluated because the first operand (some falsy expression) is evaluated as falsy. If expr is a function, the function is never called. See the example below:
function A() console.log("called A"); return false; > function B() console.log("called B"); return true; > console.log(A() && B()); // Logs "called A" to the console due to the call for function A, // && evaluates to false (function A returns false), then false is logged to the console; // the AND operator short-circuits here and ignores function B
Operator precedence
The AND operator has a higher precedence than the OR operator, meaning the && operator is executed before the || operator (see operator precedence).
true || false && false; // true true && (false || false); // false (2 === 3) || (4 0) && (1 === 1); // false
Examples
Using AND
The following code shows examples of the && (logical AND) operator.
= true && true; // t && t returns true a2 = true && false; // t && f returns false a3 = false && true; // f && t returns false a4 = false && 3 === 4; // f && f returns false a5 = "Cat" && "Dog"; // t && t returns "Dog" a6 = false && "Cat"; // f && t returns false a7 = "Cat" && false; // t && f returns false a8 = "" && false; // f && f returns "" a9 = false && ""; // f && f returns false
Conversion rules for booleans
Converting AND to OR
The following operation involving booleans:
&& bCondition2
is always equal to:
!(!bCondition1 || !bCondition2)
Converting OR to AND
The following operation involving booleans:
|| bCondition2
is always equal to:
!(!bCondition1 && !bCondition2)
Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.
The following composite operation involving booleans:
|| (bCondition2 && bCondition3)
is always equal to:
|| bCondition2 && bCondition3
Specifications
| Specification |
|---|
| ECMAScript Language Specification # prod-LogicalANDExpression |
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Sep 25, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Как создать калькулятор на Java — полное руководство с кодом
В этом руководстве мы расскажем, как создать калькулятор на Java для Android. Если вы новичок в программировании и никогда раньше не создавали приложения, ознакомьтесь с нашим предыдущим руководством по написанию первого приложения для Android:

Предполагается, что у вас есть хотя бы минимальный базовый опыт создания Android – приложений .
Полный исходный код калькулятора, описанного ниже, доступен для использования и изменения на github.
Создание проекта
Первое, что нужно сделать — это создать в Android Studio новый проект: Start a new Android Studio project или File — New — New Project :

Для этого руководства мы выбрали в панели « Add an Activity to Mobile » опцию « EmptyActivity », для « MainActivity » мы оставили имя по умолчанию – « Activity ». На этом этапе структура должна выглядеть, как показано на рисунке ниже. У вас есть MainActivity внутри пакета проекта и файл activity_main.xml в папке layout :

Включение привязки данных в проекте
Перед тем, как создать приложение для Андроид с нуля, нужно уяснить, что использование привязки данных помогает напрямую обращаться к виджетам ( Buttons , EditText и TextView ), а не находить их с помощью методов findViewById() . Чтобы включить привязку данных, добавить следующую строку кода в файл build.gradle .
android < . dataBinding.enabled = true .

Разработка макета калькулятора
Для включения привязки данных в файле activity_main.xml требуется еще одно изменение. Оберните сгенерированный корневой тег ( RelativeLayout ) в layout , таким образом сделав его новым корневым тегом.
Как научиться создавать приложения для Андроид? Читайте наше руководство дальше.
Тег layout - это предупреждает систему построения приложения, что этот файл макета будет использовать привязку данных. Затем система генерирует для этого файла макета класс Binding . Поскольку целевой XML-файл называется activity_main.xml , система построения приложения создаст класс ActivityMainBinding , который можно использовать в приложении, как и любой другой класс Java . Имя класса составляется из имени файла макета, в котором каждое слово через подчеркивание будет начинаться с заглавной буквы, а сами подчеркивания убираются, и к имени добавляется слово « Binding ».
Теперь перейдите к файлу MainActivity.java . Создайте закрытый экземпляр ActivityMainBinding внутри вашего класса, а в методе onCreate() удалите строку setContentView () и вместо нее добавьте DataBindingUtil.setContentView() , как показано ниже.
public class MainActivity extends AppCompatActivity < private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_main); >>
Общие принципы создания виджетов макета
В приложении калькулятора есть четыре основных элемента:
RelativeLayout - определяет, как другие элементы будут укладываться или отображаться на экране. RelativeLayout используется для позиционирования дочерних элементов по отношению друг к другу или к самим себе.
TextView - элемент используется для отображения текста. Пользователи не должны взаимодействовать с этим элементом. С помощью TextView отображается результат вычислений.
EditText - похож на элемент TextView, с той лишь разницей, что пользователи могут взаимодействовать с ним и редактировать текст. Но поскольку калькулятор допускает только фиксированный набор вводимых данных, мы устанавливаем для него статус « не редактируемый ». Когда пользователь нажимает на цифры, мы выводим их в EditText .
Button - реагирует на клики пользователя. При создании простого приложения для Андроид мы используем кнопки для цифр и операторов действий в калькуляторе.
Создание макета калькулятора

Код макета калькулятора объемный. Это связано с тем, что мы должны явно определять и тщательно позиционировать каждую из кнопок интерфейса. Ниже представлен фрагмент сокращенной версии файла макета activity_main :
Внутренние компоненты калькулятора
Перед тем, как создать приложение на телефон Android , отметим, что valueOne и valueTwo содержат цифры, которые будут использоваться. Обе переменные имеют тип double , поэтому могут содержать числа с десятичными знаками и без них. Мы устанавливаем для valueOne специальное значение NaN ( не число ) - подробнее это будет пояснено ниже.
private double valueOne = Double.NaN; private double valueTwo;
Этот простой калькулятор сможет выполнять только операции сложения, вычитания, умножения и деления. Поэтому мы определяем четыре статических символа для представления этих операций и переменную CURRENT_ACTION , содержащую следующую операцию, которую мы намереваемся выполнить.
private static final char ADDITION = '+'; private static final char SUBTRACTION = '-'; private static final char MULTIPLICATION = '*'; private static final char DIVISION = '/'; private char CURRENT_ACTION;
Затем мы используем класс DecimalFormat для форматирования результата. Конструктор десятичного формата позволяет отображать до десяти знаков после запятой.
decimalFormat = new DecimalFormat("#.##########");
Обработка нажатий на цифры
В нашем создаваемом простом приложении для Андроид всякий раз, когда пользователь нажимает на цифру или точку, нам нужно добавить эту цифру в editText . Пример кода ниже иллюстрирует, как это делается для цифры ноль ( 0 ).
binding.buttonZero.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < binding.editText.setText(binding.editText.getText() + "0"); >>);
Обработка кликов по кнопкам операторов

Обработка нажатия кнопок операторов ( действий ) выполняется по-другому. Сначала нужно выполнить все ожидающие в очереди вычисления. Поэтому мы определяем метод computeCalculation . В computeCalculation , если valueOne является допустимым числом, мы считываем valueTwo из editText и выполняем текущие операции в очереди. Если же valueOne является NaN , для valueOne присваивается цифра в editText .
private void computeCalculation() < if(!Double.isNaN(valueOne)) < valueTwo = Double.parseDouble(binding.editText.getText().toString()); binding.editText.setText(null); if(CURRENT_ACTION == ADDITION) valueOne = this.valueOne + valueTwo; else if(CURRENT_ACTION == SUBTRACTION) valueOne = this.valueOne - valueTwo; else if(CURRENT_ACTION == MULTIPLICATION) valueOne = this.valueOne * valueTwo; else if(CURRENT_ACTION == DIVISION) valueOne = this.valueOne / valueTwo; >else < try < valueOne = Double.parseDouble(binding.editText.getText().toString()); >catch (Exception e)<> > >
Продолжаем создавать копию приложения на Андроид . Для каждого оператора мы сначала вызываем computeCalculation() , а затем устанавливаем для выбранного оператора CURRENT_ACTION . Для оператора равно (=) мы вызываем computeCalculation() , а затем очищаем содержимое valueOne и CURRENT_ACTION .
Заключение
Если вы запустите и протестируете данное приложение, то увидите некоторые моменты, которые можно улучшить: 1) возможность нажимать на кнопку оператора, когда editText очищен ( т. е. без необходимости ввода первой цифры ), 2) возможность продолжать вычисления после нажатия кнопки « Равно ».
Полный код примера доступен на github.
консольный калькулятор на java
сразу выдавал ответ а не требовал запуска программы листинг моего калькулятора.
import java.util.Scanner; public class calculator < private static Scanner read; public static void main (String[] args)< read = new Scanner(System.in); double first; double second; String operator; System.out.print(">> "); first = read.nextDouble(); operator = read.next(); second = read.nextDouble(); if (operator.equals("*")) < System.out.println("= " + (first * second)); >if (operator.equals("/")) < System.out.println("= " + (first / second)); >if (operator.equals("+")) < System.out.println("= " + (first + second)); >if (operator.equals("-")) < System.out.println(" "; String str2 = ""; String operator = ""; char charTmp = ' '; int count = 0; int countFirsDigit = 0; int countSecondDigit= 0; double x = 0; double y = 0; while (count < ch.length - 1)< char c = ch[countFirsDigit]; if(Character.isDigit(c))/проверка является ли символ числом String strTmp = Character.toString(c);//преобразование char в String str1 = str1.concat(strTmp);//склеивание последовательности символов x = Double.parseDouble(str1);//преобразование строки чисел в double countFirsDigit++;//счетчик первого числа count++;//общий счетчик countSecondDigit++;//счетчик второго числа >else < countSecondDigit++; count = countSecondDigit; charTmp = c;//определяем оператор operator = Character.toString(charTmp); char c2 = ch[countSecondDigit]; if(Character.isDigit(c2))< String strTmp = Character.toString(c2); str2 = str2.concat(strTmp); y = Double.parseDouble(str2); >> > if (operator.equals("*")) < System.out.println("= " + (x * y)); >if (operator.equals("/")) < System.out.println("= " + (x / y)); >if (operator.equals("+")) < System.out.println("= " + (x + y)); >if (operator.equals("-")) < System.out.println(" mt24 mb12">javaкалькулятор
