Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Boolean Output?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 121
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sasparilla and fresh horses for all my men! You will see to it, won't you tiny ad?
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic