• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Output of this code?!

 
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Everyone,

I am aspiring to do SCJP 1.4. I came across some of these qns which I found it basic yet, unfortunately, I am having some difficulty to handle them. Could someone pls help me in the output?

1) Output of this prog?

class boolean
{
static boolean b;

public static void main(String args[])
{
int x = 0;
if(b)
{
x=1;
}
else if(b=false)
{
x=2;
}
else if(b)
{
x=3;
}
else
{
x=4;
}
System.out.println("Value of x="+x);
}
}

My understanding since b is declared & not instantiated, the default value is false, so x=2. I think the answer is false but when I refered to the ans sheet, it was x=4.
Pls explain.....

Thanks
Best Regards
SK
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sk,

The trick is here


its b=false assignment and not comparison, the return value of assignment is the value assigned which is false.

Regards,
Raja
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Double post
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic