Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

&& vs & , || vs |

 
Rodolfo Mendoza
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
&& and || are short-circuit operators; & and | aren't.
 
Sergio Calvo
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"&&" 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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sergio,
Now I know that its possible use the "|" and "&" with logic values of variables.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic