• Post Reply Bookmark Topic Watch Topic
  • New Topic

Boolean Output?  RSS feed

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class TestClass
{
public static void main(String args[ ] )
{
int i = 0 ;
boolean bool1 = true ;
boolean bool2 = false;
boolean bool = false;
bool = ( bool2 & method1(i++) ); //1
bool = ( bool2 && method1(i++) ); //2
bool = ( bool1 | method1(i++) ); //3
bool = ( bool1 || method1(i++) ); //4
System.out.println(i);
}
public static boolean method1(int i)
{
return i>0 ? true : false;
}
}

Can any one tell me the output? and the reason for that?
Sonir
 
Author
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello !
The best way would by to try it out. I guess the answer is "2".
Reason:
"i" will only change its value with the evaluation of "method1(i++)". This term is not evaluated in //2 and //4 due to short circuit evaluation of && (||) and the value of bool2 (bool1). It is evaluated in //1 and //3, 0+1+1=2. The statements in the method do not harm, 'cause && and || are evaluated left to right.
But as I said, try it out. It's the best way to understand what's going on. add a "System.out.println(i)" after each assignment to bool.
Greetings from Euroland,
Stefan
 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good question sonir...
i++, post increment ... so i sends its current values as the parameter to the method and then increments itself..
In the short circuit operations.. RHS never gets executed , so we save couple of computations resulting the value of i to be '2'
Is it helpful?
Ragu
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!