File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt related to output involving precedence of | and && 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 "doubt related to output involving precedence of | and &&" Watch "doubt related to output involving precedence of | and &&" New topic
Author

doubt related to output involving precedence of | and &&

Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Hi! every one,

I have a doubt related to precedence order in the following code snippet.


public class PrecedenceTrial {
public static void main(String...args)
{



if(fun1() && fun2() | fun3())
{
System.out.println("inside if block");
}


}


public static boolean fun1()
{
System.out.println("inside fun 1");
return true;
}




public static boolean fun2()
{
System.out.println("inside fun 2");
return true;
}


public static boolean fun3()
{
System.out.println("inside fun 3");
return false;
}



}

when i am executing the program i get

inside fun 1
inside fun 2
inside fun 3
inside if block
but i am not able justify this As | (Bitwise OR operator) is having higher precedence than && (logical AND operator) So, fun2() should be associated with | operator and fun2() and fun3() should be evaluated first as they are operands for | operator and && should be evaluated afterwards.
but i am not getting the result as per to my view.

Please clarify it and correct me wherever i am wrong.

Regards

Jolly
Mihai Fonoage
Ranch Hand

Joined: Feb 25, 2006
Posts: 39
Hi Jolly,

Please read this previous post.

Mihai Fonoage
winay Kumar
Ranch Hand

Joined: Aug 13, 2007
Posts: 34
Hi Jolly,

what you are saying is correct. '|' has higher precedence then '&&' and Associativity is left to right. That means the expression left to | will evaluate first.

In this example "if(fun1() && fun2() | fun3())" expression "fun1() && fun2()" is left to that | so it will evaluates first then fun3(). To evaluate this "fun1() && fun2()" first it will execute fun1(),if its true then it will execute fun2()

i hope this will clear your doubt
[ July 16, 2008: Message edited by: winay Kumar ]

Winay Kumar<br />SCJP 5.0
Jolly Tiwari
Ranch Hand

Joined: Mar 26, 2006
Posts: 77
Thanks Mihai, for sharing such a nice link .

Now i understood that evaluation must happen before applying precedence rules and in exceptional cases like operators && || and ?: ,right side
operands can be skipped for evaluation due to short circuit behaviour.


Regards

Jolly
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt related to output involving precedence of | and &&