• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

What’s the distinction between the Boolean & Operator and also the && Operator?  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Can someone tell me the differences between Boolean & Operator and && Operator? I am a bit confused with the terms.
 
Saloon Keeper
Posts: 9707
192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The logical & operator and the logical && operator differ in that the && operator "short-circuits" when the expression on the left hand side evaluates to false. This means that when the expression on the left evaluates to false, the && operator determines that it doesn't matter what the value of the expression on the right is, because the final result will be false anyway, so it skips evaluation of the expression on the right.

Normally the result of evaluating the different operators for the same expressions will be the same, but in case the expression on the right hand side has side-effects (such as setting a field), you may not want to skip evaluating it.

See this topic for a good explanation: https://coderanch.com/t/604714/java/Short-Circuit-Short-Circuit-Logical
 
Marshal
Posts: 62819
203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and welcome to the Ranch

Always use && for booleans, remembering that you will often need () to match the precedences of a logical expression using ¬∧⊕∨⇒⇔
Beware of anything using side‑effects.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The & operator is applied to the operand when both the boolean and && operator is evaluated. Once an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator in Java is then applied to the first and second operands. If the first operand evaluates to false, the analysis of the second operand is skipped.
 
Campbell Ritchie
Marshal
Posts: 62819
203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rinu Gour wrote:. . . . The && operator in Java . . . .

The tutorial linked to there is full of errors, I am afraid. I hope you didn't write it yourself.
 
Sheriff
Posts: 12965
217
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rinu Gour wrote:The & operator is applied to the operand when both the boolean and && operator is evaluated. Once an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator in Java is then applied to the first and second operands. If the first operand evaluates to false, the analysis of the second operand is skipped.



No, that is an inaccurate description.
 
Bartender
Posts: 20310
110
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Rinu Gour wrote:The & operator is applied to the operand when both the boolean and && operator is evaluated. Once an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator in Java is then applied to the first and second operands. If the first operand evaluates to false, the analysis of the second operand is skipped.



No, that is an inaccurate description.



A more accurate description is that the sub-expression to the left of the && is evaluated and IF FALSE, the right-hand sub-expression is bypassed (short-circuited) and the operation returns false. IF AND ONLY IF the left-hand subexpression evaluates to true, THEN the right-hand subexpression will be evaluated and the operation will return true or false depending on which value the right-hand subxpression returned. This has side effects. If the right-hand subexpression includes one or more method calls, then the calls will not be made if the short-circuit is taken. Nor will prefix/postfix increments and decrements (such as i++) be performed.

The "&" operator technically has two meanings. One is the simple boolean operator, where both left and right sub-expressions are boolean expressions. In that case, the logical AND value for the results of the two sub-expressions will be returned as a logical value.

The other meaning of "&" is as a BITWISE operation, where the binary value on the left-hand side is AND'ed to the binary value on the right-hand side bit by bit. For example, 0110 & 1100 results in 0100.

Some might argue that the boolean & is simply the same thing as bitwise & for a pair of one-bit values, but that's assuming internal implementation details and Java is more abstract than that.
 
Ranch Hand
Posts: 127
5
MS IE Notepad Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:

Junilu Lacar wrote:

Rinu Gour wrote:The & operator is applied to the operand when both the boolean and && operator is evaluated. Once an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator in Java is then applied to the first and second operands. If the first operand evaluates to false, the analysis of the second operand is skipped.



No, that is an inaccurate description.



A more accurate description is that the sub-expression to the left of the && is evaluated and IF FALSE, the right-hand sub-expression is bypassed (short-circuited) and the operation returns false. IF AND ONLY IF the left-hand subexpression evaluates to true, THEN the right-hand subexpression will be evaluated and the operation will return true or false depending on which value the right-hand subxpression returned. This has side effects. If the right-hand subexpression includes one or more method calls, then the calls will not be made if the short-circuit is taken. Nor will prefix/postfix increments and decrements (such as i++) be performed.

The "&" operator technically has two meanings. One is the simple boolean operator, where both left and right sub-expressions are boolean expressions. In that case, the logical AND value for the results of the two sub-expressions will be returned as a logical value.

The other meaning of "&" is as a BITWISE operation, where the binary value on the left-hand side is AND'ed to the binary value on the right-hand side bit by bit. For example, 0110 & 1100 results in 0100.

Some might argue that the boolean & is simply the same thing as bitwise & for a pair of one-bit values, but that's assuming internal implementation details and Java is more abstract than that.



To be even more correct: There is no second meaning on '&' but only one: bitwise and - the reason why it leads to eval of both terms is simple as it's needed to calc the output - as booleans mostly repesented as at least byte or bigger type (most likely native datatype) wich limited to can hold only 0 and 1.

The effect here is: to calc the correct awnser both terms has to be eval down to two 1-bit numbers. There is no such thing as "'&' has the meaning of 'logical and'" as there is no 'logical and' in java - there're only & and &&.
 
Tim Holloway
Bartender
Posts: 20310
110
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Matt Wong wrote:
To be even more correct: There is no second meaning on '&' but only one: bitwise and - the reason why it leads to eval of both terms is simple as it's needed to calc the output - as booleans mostly repesented as at least byte or bigger type (most likely native datatype) wich limited to can hold only 0 and 1.



Tim Holloway wrote:
Some might argue that the boolean & is simply the same thing as bitwise & for a pair of one-bit values, but that's assuming internal implementation details and Java is more abstract than that.



Hello, Some!
 
Saloon Keeper
Posts: 5472
55
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:Some might argue that the boolean & is simply the same thing as bitwise & for a pair of one-bit values, but that's assuming internal implementation details and Java is more abstract than that.


Yes, Java doesn't state how a boolean value is represented internally.  It may be held in a byte, a short, or an int. I guess it could get weirder than that but logically, at some point, it has to boil down to what the hardware on a particular machine supports. Most likely it is determined by the value of the least significant bit in one of the aforementioned data types. Or it could be that all bits in the type are turned on or off to represent true or false. Could it be some random pattern of bits? Java doesn't say. But that wouldn't make too much sense when you're trying to implement it as efficiently as possible on a given CPU architecture. For efficiency's sake, it would make sense that whatever the storage format, that a BITWISE operation should work as expected on whatever the boolean representation is.
 
Tim Holloway
Bartender
Posts: 20310
110
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can get a lot weirder than that. For example, all booleans might be packed into a long array in memory and accessed via bit-level manipulations. IBM mainframes had special instructions to do just that. In some places, I've seen the logical characters "T" and "F", "Y" or "N" or "0" and "1" (and note I said character, not byte, word, int, or any other numeric or memory entity).

In some languages - "true" or "false" must be exactly 0001 and 0000. Some are 1111 and 0000. In C, "false" is defined for logical computation purposes as zero and true is anything else. But then in C, 0 is also the null pointer, even on machines whose lowest memory location isn't 0. And yes, I've worked with some of those!

But implementation details aren't the point. Java is not assembly language. A boolean in Java cannot be assigned an arithmetic value, only the special manifest constants false and true. To talk about "&" on booleans as being the same thing as "&" on binary entities is to make a false equivalence, which is the kind of thing that leads to sloppy thinking which can lead to sloppy design. And would likely get you beaten about the head and shoulders by any self-respecting mathematician to boot. Mathematics makes a very clear distinction between the different types of objects that its various branches address and there's no numbers in the branch known as Symbolic Logic. Much less internal representations favoring the hardware that manipulates math. Until recently the only hardware required for math was the human brain. Which is very definitely not numerically or digitally organized.
 
Saloon Keeper
Posts: 2137
80
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to what we've discussed so far, there is an interesting practical use of "&" operator:



output:


If you closely observe the above code, for any value of min,max, you will get a positive value thats less than or equal to "number". You'll also notice that numbers such as 1, 3, 7, 15, 31, etc.. will give you good distribution.

How's that useful you ask ? .... Thats how a hasmap optimally maps a hashcode to its internal array !!
(Note that there are other hidden details too such as a salt value, etc..)


 
Tim Holloway
Bartender
Posts: 20310
110
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

salvin francis wrote:Thats how a hasmap optimally maps a hashcode to its internal array !!


You mean java.util.Hashmap?

There is a concept known as a "perfect hash". A perfect hash exists when each and every hash slot is filled and there are no overflows. I think there's actually a complete subset of Computer Science dedicated to this discipline and probably something in Knuth as well. That often requires overriding the default Java hash algorithm when done with java.util.Map implementations.

For some sets of data, one can determine a perfect hash algorithm and map size. For more general sets, you have to settle for "good enough", and unless resources are really tight, you don't care. However as a general rule, relatively prime set sizes work best, and you don't want to allocate either too large or too small a map. Too large wastes memory, too small is likely to result in lots of hash overflows.

The "&" operator when used on binary objects is a quick way to detect whether a number is odd or even, among other tricks. However, don't get too clever. Compilers will detect most common "magic number" operations and optimize things like division by 2, 4, 8, 10, ... using shifts and logic. Likewise for multiplication and modulo functions.

Thinking in machine language when you're using a modern abstract programming language is perilous. Not only is the compiler perfectly capable of detecting straightforward code and optimising the heck out of it, you can actually confuse the optimiser if you get too clever, resulting in less efficient code than if you'd simply coded what you meant. Save the optimising for measured problems and always remember that the most powerful optimisations come from smarter algorithms. Making a loop a few nanoseconds faster by twiddling machine instructions is nothing if you can pick an algorithm that shaves off minutes.
 
salvin francis
Saloon Keeper
Posts: 2137
80
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:...You mean java.util.Hashmap?...


Yes, sorry for the typo.

Here's the code for getNode in java.util.HashMap:


n is the length of the array. Hence (n-1) & anyNumber will return values 0 to (n-1)
I'll not go into further details for brevity



 
Tim Holloway
Bartender
Posts: 20310
110
Android Eclipse IDE Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java.util.HashMap is predicated on the underlying map array being a power of 2 in size. So that particular implementation would NOT be properly initialized to a relatively prime number - unless the prime in question is 2!

There are lots of other bit tricks in that implementation. I recommend reading the excellently-documented OpenJDK source code: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/HashMap.java

Note that there are other implementations of HashMap that don't work bit-wise and while I haven't looked in depth, I think that this particular implementation will use one of them if it's appropriate.

In fact, I'd always used the relatively-prime map size, and since the external JavaDocs make no mention of binary size optimizations or preferred usage, I didn't even know that option was there. Assuming that the original Sun implementation even did that. The HashMap, after all, like all good classes is "black box" and can do any darned thing it pleases internally as long as it fulfills the external contracts.
 
Campbell Ritchie
Marshal
Posts: 62819
203
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

salvin francis wrote:. . . you will get a positive value . . .

[awkward pedantic mode]Not positive but non‑negative; 0 isn't a positive number[/mode]
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!