Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If statement

 
geeta rai
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is 'A' printed in the following code?
class test
{
static boolean b;
public static void main(String[] args)
{
System.out.println("The value of b is "+ b);

if (b = true) //1
{
System.out.print("A");
}
else if (b) //2
{
System.out.print("B");
}
else if (!b)
{
System.out.print("C");
}
else
{
System.out.print("D");
}
}
}
I think after assigment of b to true at the statement //1, the control should go to //2 and B should be printed.
 
shankar vembu
Ranch Hand
Posts: 309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by geeta rai:
I think after assigment of b to true at the statement //1, the control should go to //2 and B should be printed.

in the above code, ur assigning true to b, and therefore the line 1 evaluates to if(true) and so it enters in the section where A is printed.
regards.
[ November 22, 2003: Message edited by: shankar vembu ]
 
geeta rai
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks shankar, that was so simple
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic