• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

&& operator

 
ramya ray
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I could not understand as why the underlying code returns true and prints "hello".. Please help

class c {
public static void main(String args[]){
if(false && true || true){
System.out.pritnln("hello");
}
}
}

As if first exp. is false in && operator there is no point of looking at the rest of expression.Please correct if i m wrong.

I really need and appreciate youe support .
Thanks java ranchers in advance.

 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its operator precedence.

First it evaluates (false && true ) which returns false and then it evaluates (false || true ) which will return true and hence the o/p.
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I checked the following link before setting the user name.

http://www.javaranch.com/name.jsp

"You can even use initials for the first name if you like."
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I was missing the space between the initial and the last name. it is fixed now.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by M Krishnan:
I guess I was missing the space between the initial and the last name. it is fixed now.


Thanks
 
Adrian Engler
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In an expression x && y, y will not be evaluated when x is false. However, in x || y, y *is* evaluated if x is false (it would not be evaluated if x was true). As was already pointed out in this thread, x && y || z is the same as (x && y) || z.

In x && y || z, y is not evaluated if x is false, but z is evaluated, and if z is true, the result is true.





The output is:
false
true-2
hello

true-1 is not printed because, indeed, the expression to the right of && is not evaluated if the one to the left of && is false.
The expression to the right of || is evaluated, and so the result is (false || true), which is true.

(made private methods static - see next post)
[ September 18, 2006: Message edited by: Barry Gaunt ]
 
Adrian Engler
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, the methods falseMethod(), trueMethod1(), trueMethod2() in the example above would, of course, have to be declared static, otherwise, the code does not compile (because they are called from a static context).
 
ramya ray
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Adrian, It clears me a lot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic