• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Unexpected output ??

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could anyone kindly let me know why does the following code prints 3 ?
class TestClass
{
public static void main(String args[])
{
boolean b = false;
int i = 1;
do
{
i++ ;
} while (b = !b);
System.out.println( i );
}
}
Thanks in advance.
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because of "(b = !b)" in the "while" statement.
Note its an assignment and not an check. After
the assignment, the value of b is used to determine whether to quit the loop or not? Make sense??
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

do-while loop executes its body atleast once irrespective of whether the condition returns true/false
i gets incremented to 2
goes thru the condition in while
b= !b
in this statement,! has higher precedence than =.
!b evaluates to !false ==> true
now b gets assigned the value true.
(b = (!false)) -> true
since the condition returns true,it enters the loop again,and increments i to 3.
Now,the condition is evaluated once again,
but returns false (because b = (!true) )therefore comes out of the loop and prints 3.
Chitra
 
Rao Rekha
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That makes complete sense. Thanks Jha and Chitra.
 
reply
    Bookmark Topic Watch Topic
  • New Topic