This week's giveaways are in the MongoDB and Jobs Discussion forums. We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line! See this thread and this one for details.
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
posted
0
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
posted
0
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
posted
0
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
posted
0
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
posted
0
yep, boolean uncapitalised is a keyword; Boolean capitalised is a wrapper class
in this case it is a keyword...a mistake on my part