Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

whate the difference between | and || or & and &&?

 
Ada Gu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i don't know what the difference between operator | and || or & and &&
how to use them in programming?
 
java raid
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The | and || are OR operators while & and && are AND operators. The || and && are considered short-circuit operators; giving it the potential to just execute the code on the left-hand side. The | and & will always execute both sides.
i.e.
String s1 = null;
//once it realizes that s1 is null it will not execute s1.equals
//this comes in handy in this situation becuase if you call .equals on a
//null object it will throw a NullPointerException
if(s1 == null || s1.equals(""))
//this throws a NullPointerException
if(s1 == null | s1.equals(""))

-enjoy
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"ada ada" and "java raid",
Welcome to the JavaRanch!
However...
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp.
We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please edit your profile and select a new name which meets the requirements.
Thanks.
Dave
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The || and && are short circuit operator, thats true. You use them
to evaluate some conditions, e.g.

The | and & operator you can use also to evaluate like this

gives 11 as result cause it compares the binary values
.....1010
.....0011
-----------
.....1011
The OR now checks for each position if there is a 1, if yes
result is 1 if no result is 0
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the Operators lesson of Sun's Java Tutorial. Relevant information is in the "Relational and Conditional Operators" and "Shift and Logical Operators" sections.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic