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

SCJP Question

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int i = 10;
int j = 10;
boolean b = false;
if(b= i == j)
System.out.println("True");
else
System.out.println("False");

This prints "True"
But if() is suppose to contain only bollean expressions,
how does this work?
Explain!!
 
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello kanan,
the explanation to this output goes like this.
if(b= i == j)
remember
1) during assignment operation (i.e. '=' operation )first of all the RHS expression is calculated and the result is assigned to LHS.
so in ur case RHS expression is
i==j
which is true so now the if(...) becomes
if(b = true)
now true will be assigned to b
so finally if(...) will be considered
if(true)
so the expression inside if() has value true so the output is true.
hope this explain things.
do post any other doubt of urs.
regards
deekasha


 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Original Code:

int i = 10;
int j = 10;
boolean b = false;
if(b= i == j)
System.out.println("True");
else
System.out.println("False");
To make the if statement more clear, look at it this way:
if(b = (i==j))
Here, i==j returns true, which is assigned to b. Now, your if statement has its required boolean condition - b - which is true. Hence the result.
 
Kanan Jariwala
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks deeksha and gopinath, u'll explained that one fine
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic