aspose file tools*
The moose likes Beginning Java and the fly likes Output of this code?! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Output of this code?!" Watch "Output of this code?!" New topic
Author

Output of this code?!

Shafian Kisna
Ranch Hand

Joined: Oct 25, 2005
Posts: 70
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

Joined: Mar 23, 2006
Posts: 14
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

Joined: Sep 16, 2005
Posts: 1780
I thought you'd get a syntax error for "class boolean"


There is no emoticon for what I am feeling!
Stephan Norwood
Greenhorn

Joined: Mar 23, 2006
Posts: 14
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

Joined: Sep 16, 2005
Posts: 1780
boolean is a keyword, not a built-in class. And isn't the SCJP all about trick questions, anyway
Stephan Norwood
Greenhorn

Joined: Mar 23, 2006
Posts: 14
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

Joined: Oct 25, 2005
Posts: 70
Hi Everyone,

Thanks for the comments and explanation.

It helped in my understanding...

Best Regards
KS
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Output of this code?!
 
Similar Threads
q from sun's epractice exam
Output of this code?!
IS if (b ) same as: if (b == true) ???
what's the integer value for boolean "true"?
If condition