• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output of this code?!

 
Shafian Kisna
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • 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.....
 
Stephan Norwood
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shafian,

You are right;
If an instance variable is not initialized it gets a default value;
boolean primitives get false as their default value.

if(b=false) is not the same as if (b==false) which leads to x=2

In the first if statement b is assigned the value false before the if test is evaluated.
Since it is false,it skips this block (x=2) and goes on to check
the next if(b) which is false too,so it skips this block and then takes the default else which makes x=4.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought you'd get a syntax error for "class boolean"
 
Stephan Norwood
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right,you get an error message.
class boolean is a built-in java class (java.lang.object)

I didn't mention this,because it was not the question.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
boolean is a keyword, not a built-in class. And isn't the SCJP all about trick questions, anyway
 
Stephan Norwood
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yep, boolean uncapitalised is a keyword;
Boolean capitalised is a wrapper class

in this case it is a keyword...a mistake on my part
 
Shafian Kisna
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

Thanks for the comments and explanation.

It helped in my understanding...

Best Regards
KS
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic