Operators - What is the Difference Between & and && in Java_ - Stack Overflow
Operators - What is the Difference Between & and && in Java_ - Stack Overflow
I always thought that && operator in Java is used for verifying whether both its boolean
operands are true , and the & operator is used to do Bit-wise operations on two integer
223 types.
Recently I came to know that & operator can also be used verify whether both its boolean
operands are true , the only difference being that it checks the RHS operand even if the LHS
operand is false.
Is the & operator in Java internally overloaded? Or is there some other concept behind this?
Share Improve this question edited Mar 26, 2019 at 14:14 asked Apr 6, 2011 at 9:46
Follow Community Bot Lavneesh
1 1
3 Possible duplicate of Why do we usually use `||` not `|`, what is the difference? – Blake Yarbrough Nov
4, 2015 at 16:23
Couldn't find info on this in the official sun/oracle documentation :( – AlikElzin-kilaka Sep 21, 2020 at
15:14
"short-circuiting" is the key term here. – AlikElzin-kilaka Sep 21, 2020 at 15:15
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate
(1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x !=
0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x >
1) .
EDIT:
exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the | .
exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB
and do the || .
Share Improve this answer Follow edited Apr 9, 2011 at 10:14 answered Apr 6, 2011 at 9:53
ITroubs
11.2k 4 29 25
16 What's the reason to write one & or | in if statement? It never will be faster than && and ||. Why do
we want to check second condition if we already can have answer? Can you provide and realistic
example, please? – Michu93 Jul 13, 2017 at 14:24
25 @Michu93: One example would be if the second condition is a function call which has a side effect
that you always need. Since side effects should usually be avoided, there will be only rare cases
where you need that, and I can't think of a realistic example at the moment. – Heinzi Aug 14, 2017 at
6:58
13 @Michu93 When implementing security-related code, especially cryptography, the use of these
operators prevents side-channel attacks based on time measurements (different execution times for
different results). Sometimes, "the constant time" comparison is more valuable than "faster"
comparison. – Petr Dvořák Oct 31, 2020 at 17:09
6 @PetrDvořák fantastic example. To add to this, I have seen this implemented in authentication/login
code (including Spring Security) where code execution for an invalid username should take as long
as code execution for an invalid password (ie, the former shouldn't short-curcuit). – java-addict301
Mar 15, 2022 at 16:41
Besides not being a lazy evaluator by evaluating both operands, I think the main
characteristics of bitwise operators compare each bytes of operands like in the following
68 example:
int a = 4 ;
int b = 7 ;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
Share Improve this answer Follow answered Aug 26, 2011 at 3:57
suat
4,289 3 32 52
5 The question is about logical boolean operations, not bitwise operations. – user207421 Sep 27, 2016
at 11:41
34 @EJP It helps still googlers like me, who read only the title. – Ad Infinitum Mar 22, 2017 at 9:39
boolean a, b;
Share Improve this answer Follow edited Apr 6, 2011 at 9:50 answered Apr 6, 2011 at 9:49
Andreas Dolk Torres
115k 19 182 272 5,400 4 27 26
Thank you Andreas for the edit, maybe this other question helps too:
stackoverflow.com/questions/4014535/vs-and-vs – Torres Apr 6, 2011 at 9:52
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double
16
ampersand ("&&") is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND"
operator while the double ampersand ("&&") is the "conditional logical AND" operator. That
is to say that the single ampersand always evaluates both arguments whereas the double
ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error should occur.
Try this.
11
String s = null ;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
Share Improve this answer Follow edited Apr 6, 2011 at 14:38 answered Apr 6, 2011 at 9:52
user85421 Prince John Wesley
29.6k 11 65 92 63.6k 12 89 95
& and && can be logical AND , when the & or && left and right expression result all is true,
the whole operation result can be true.
when use && as logical AND , if the left expression result is false, the right expression will not
execute.
if (str!= null && !str.equals( "" )){ // the right expression will not execute
If using & :
if (str!= null & !str.equals( "" )){ // the right expression will execute, and throw
the NullPointerException
int x = 0 ;
int y = 2 ;
if (x== 0 & ++y> 2 ){
System.out.print(“y=”+y); // print is: y=3
}
int x = 0 ;
int y = 2 ;
if (x== 0 && ++y> 2 ){
System.out.print(“y=”+y); // print is: y=2
}
The bitwise AND " &" operator produces 1 if and only if both of the bits in its
operands are 1. However, if both of the bits are 0 or both of the bits are different
then this operator produces 0. To be more precise bitwise AND " &" operator returns
1 if both of the two bits is 1 and it returns 0 if any of the bits is 0.
http://www.roseindia.net/java/master-java/java-bitwise-and.shtml
Share Improve this answer Follow edited Jul 25, 2023 at 22:13 answered Apr 11, 2017 at 6:30
Community Bot aircraft
1 1 26.8k 28 101 173
1 All respection for your rich explain @aircraft – java dev May 13, 2022 at 11:30
This is not correct on the wiki source. A bitwise and of for example 00000010 and 00000010 does not
produce the number 1, it produces the number 2. This can be casted to the boolean True, but this
answer states that it produces 1 which is plain incorrect. – Andreas Lundgren Jul 25, 2023 at 20:38
7 When both operands of a &, ^, or | operator are of type boolean or Boolean, then
the type of the bitwise operator expression is boolean. In all cases, the operands are
subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is
false.
For ^, the result value is true if the operand values are different; otherwise, the result
is false.
For |, the result value is false if both operand values are false; otherwise, the result is
true.
The "trick" is that & is an Integer Bitwise Operator as well as an Boolean Logical Operator. So
why not, seeing this as an example for operator overloading is reasonable.
Share Improve this answer Follow edited Jun 20, 2020 at 9:12 answered Apr 6, 2011 at 9:53
Community Bot Andreas Dolk
1 1 115k 19 182 272
‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the
logical relationship of its arguments.
5
For example: - Condition1 && Condition2
If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason
why this logical operator is also known as Short Circuit Operator because it does not evaluate
another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.
If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true
else it will be false.
‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are
one. Otherwise it produces zero (0).
For example:-
The value of c is 4.
Share Improve this answer Follow answered Nov 17, 2015 at 9:23
satish
1,641 1 12 4
&& and || are called short circuit operators. When they are used, for || - if the first operand
evaluates to true , then the rest of the operands are not evaluated. For && - if the first
3 operand evaluates to false , the rest of them don't get evaluated at all.
so if (a || (++x > 0)) in this example the variable x won't get incremented if a was true .
Share Improve this answer Follow answered Apr 29, 2016 at 11:49
ACV
10.5k 5 81 89
With booleans, there is no output difference between the two. You can swap && and & or ||
and | and it will never change the result of your expression.
3
The difference lies behind the scene where the information is being processed. When you
right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:
a != 0 --> false
expression returns false
Less steps, less processing, better coding, especially when doing many boolean expression or
complicated arguments.
Share Improve this answer Follow edited Sep 27, 2016 at 11:42 answered May 16, 2013 at 12:55
user207421 Ryan
310k 44 320 488 39 1
2 It will change the overall result of the expression if the operands have side-effects. – user207421 Sep
27, 2016 at 11:42
Besides && and || being short circuiting, also consider operator precedence when mixing the
two forms. I think it will not be immediately apparent to everybody that result1 and result2
3 contain different values.
boolean a = true ;
boolean b = false ;
boolean c = false ;
Share Improve this answer Follow edited Jan 29, 2018 at 13:33 answered Sep 26, 2017 at 12:06
mgr326639
912 2 11 25
& is a bitwise operator plus used for checking both conditions because sometimes we need to
evaluate both condition. But && logical operator go to 2nd condition when first condition
0 give true.
Share Improve this answer Follow answered Nov 10, 2016 at 9:42
Yasir Shabbir Choudhary
2,568 2 28 32
all answers are great , and it seems that no more answer is needed but I just wonted to
point out something about && operator called dependent condition
0
In expressions using operator &&, a condition—we’ll call this the dependent condition —may
require another condition to be true for the evaluation of the dependent condition to be
meaningful.
In this case, the dependent condition should be placed after the && operator to prevent
errors.
and another thing: && and || are called short-circuit evaluation because the second
argument is executed or evaluated only if the first argument does not suffice to
determine the value of the expression
Share Improve this answer Follow edited Mar 3, 2017 at 22:09 answered Feb 13, 2017 at 12:15
Basheer AL-MOMANI
15.2k 9 101 94
In respect of the AND and OR operators, Java has got two types of evaluation namely Short-
Circuit evaluation and full evaluation .
0
&& || Short-Circuit Evaluation
Short-Circuit evaluation enables you to not evaluate the right-hand side of AND and OR
expressions, when the overall result can be predicted from the left-side value.
int numberOne = 1 ;
int numberTwo = 2 ;
boolean result = false ;
System.out.println(numberOne); // prints 1
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
// left-side is true so the the overall result CAN NOT be predicted without
evaluating the right side.
// numberOne will be 2, numberTwo will be 2, result will be true
result = (numberTwo > numberOne) && (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints true
Although in some cases it is possible to predict the result, It is necessary to evaluate the right-
hand side.
int numberOne = 1 ;
int numberTwo = 2 ;
boolean result = false ;
// left-side is false so the the overall result will be false BUT the right side
MUST be evaluated too.
// numberOne will be 2, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) & (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
Notice:
1. Notice that for XOR ( ^ ) there is no short-circuit, because both sides are always required
to determine the overall result.
2. Notice that other possible names for Short-Circuit evaluation are minimal evaluation
and McCarthy evaluation .
3. It is not recommenced to mix boolean logic and actions in the same expression
4. & can also act as a Bitwise AND operator which is very academic and can be used in
cryptography. When both bits are 1, the result is 1, or either of the bits is not 1, the result
is 0. (Check the following code)
byte a = 5 ; // 00000101
byte b = 3 ; // 00000011
byte c = ( byte ) (a & b); // 00000001 (c is 1)
Share Improve this answer Follow answered Mar 31, 2021 at 9:10
Elyas 'Eloy' Hadizadeh
Tasbiti
3,617 8 46 58
Almost every point of comparison is very well covered in all the answers. I just want to add
one example. To demonstrate how the output changes based on which operator we use.
0 Consider the below example
int a = 10 ;
if (++a== 10 & ++a== 12 ) {
++a;
}
System.out.println(a); //12
In the above code, We are using bitwise & operator. So It will evaluate both the
arguments(left and right) irrespective of the individual result.
so a will increment 2 times within if condition . But as the condition will not become true, It
will not enter inside the if-loop and 3rd increment will not happen. So the final value of a
would become 12 in this case.
Now suppose, in the same above example If we use short-circuit && operator. then after
evaluating ++a==10 to false, It will not go to check the second argument. And Hence the final
value of a would-be 11.
int a = 10 ;
if (++a== 10 && ++a== 12 ) {
++a;
}
System.out.println(a); //11
Based on this, We can say that performance of bitwise & operator is relatively low compare to
the short-circuit && operator. As bitwise operator will go to evaluate both the arguments
irrespective of the result of the first argument. While && operator will stop evaluating the
second argument if the first argument's result is false.
One more difference between these two is, Bitwise & operator is applicable for boolean as
well as integral types. While short-circuit && operator is applicable only for the boolean type.
We can write
System.out.println( 4 & 5 ); // 4
System.out.println( 4 && 5 );