This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes && vs & , || vs | Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "&& vs & , || vs |" Watch "&& vs & , || vs |" New topic
Author

&& vs & , || vs |

Rodolfo Mendoza
Greenhorn

Joined: Feb 27, 2008
Posts: 14
Hi guys,
I thought that the operators "|" and "&" are only used to manipulate the bits of an integer (byte ... long) but why the following code works?




I mean, I didn't use "||" and "&&", and It's works...
Someone give me the light..
Tim Weide
Ranch Hand

Joined: Feb 19, 2008
Posts: 37
&& and || are short-circuit operators; & and | aren't.
Sergio Calvo
Greenhorn

Joined: Feb 22, 2008
Posts: 8
"&&" and "||" guarantee you that they operate on the logic values of your variables, not on their bits representation.

"&" and "|" happen to be also logic operators but they operate on the bits level of your variables, no matter on their logical values.

Since true and false happen to represent bits values in Java, there's no problem in this particular case. But "&" and "|" are used for other kinds of low level bitwise operations (changing many 1's and many 0's here and there) required only in a few applications.
Rodolfo Mendoza
Greenhorn

Joined: Feb 27, 2008
Posts: 14
Thanks Sergio,
Now I know that its possible use the "|" and "&" with logic values of variables.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by Rodolfo Mendoza:
Thanks Sergio,
Now I know that its possible use the "|" and "&" with logic values of variables.


It's possible but in most cases you wouldn't want to.
Do you understand what "short circuit" means when talking about these operators?


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
 
GeeCON Prague 2014
 
subject: && vs & , || vs |