# the use of && or & or || or |

• November 7th, 2009, 02:54 AM
chronoz13
the use of && or & or || or |
when using the && if the first operand is evaluated into false, then the whole operation is false,
while using the || if the first operand is evaluated into true, the the whole operation is true,
basically is the condition happened in this way, the second operand will never be evaluated.. ryt?

but how bout using a single character ? "&" or "|"

it will always evaluate every operands...

my question is

in what kind of situation this operators are mostly used?

a single "&" or a single "|".
• November 7th, 2009, 06:08 AM
Freaky Chris
Re: the use of && or & or || or |
Sinle & and | are bitwise operators not boolean operators, other bitwise operators are things such as >> << >>> <<< ~ ^

Bitwise operators work on bits within a value.

Chris
• November 7th, 2009, 09:53 AM
chronoz13
Re: the use of && or & or || or |
oh? i thought they are booleans ... so its for bitwise.....
• November 7th, 2009, 01:24 PM
helloworld922
Re: the use of && or & or || or |
For boolean values, they can be thought of as taking up only 1 bit (I think technically Java allocates a whole byte, but only 1 bit actually gets used/boolean value)

So, 1 & 1 = 1 => true && true = true
However, if we decide to work with the bits inside of say a byte:

Code :

``` 1111 1110 & 0100 0001 ---------------- 0100 0000```

And since the && isn't defined for bytes, there is no equivalence to this.

Another small minor detail is the way Java implements both of these operators.

Java will "optimize" any && or || type operators, and skip over any unecessary comparisons.

Code :

```String a = null;   if (a != null && a.equals("Hello"))```

Here, java will test the condition a != null. It will return false, and java, seeing that this is going to be and'ed to a.equals("Hello"), will just skip that comparison.

However, if we do this:
Code :

```String a = null; if (a != null & a.equals("Hello"))```

Java won't optimize this, and will try to evaluate a.equals("Hello"). Of course, this will fail, and Java will throw a nice friendly NullPointerException.
• November 7th, 2009, 02:23 PM
Json
Re: the use of && or & or || or |
I would say you never you use the single & or | in normal statements, they are normally used for bitwise operations like helloworld said.

I think you should prefer the shortcut operators in any situation unless there is a specific need to use something else.

// Json
• November 7th, 2009, 11:49 PM
chronoz13
Re: the use of && or & or || or |
thats the answer im looking for..... using these operators in certain situation.. like the book said.. "we will most likely never ecounter a situation where we cannot use the double ampersand (&&) and double vertical bars...

and i notice with my threads... i think that i should have a zip of what are bitwise operators.. operations.. or bitwise programs...