Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about boolean?

 
Albert Lee
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. String foo = �blue�;
2. Boolean[]bar = new Boolean [1];
3. if (bar[0]) {
4. foo = �green�;
5. }
What is the result?
A.foo has the value of ��
B.foo has the value of null
C.foo has the value of �blue�
D.foo has the value of �green�
E.an exception is thrown
F.the code will not compile
the answer is f.But I think it should be c.Please
help me?thanks in advance!
 
Roan Nicolas
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The correct answer is indeed F. This code will not compile since the conditional expression in the if statement must result in a boolean value. The expression bar[0] in your code however is a Wrapper class Boolean and not the primitive type boolean.
You can get the code to compile if you use the booleanValue() method of the Boolean Class which returns the primitive value in the wrapper object.
 
tony kanvas
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
Hi first if you try to compile your code it will give you (CE)incompatible type because you deal with wrapper class the problem with the way of the question i think
Remember this: Wrapper classes are immutable and final (you cant do any change)
folks Correct me if I am wrong
thanks
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wrapper classes (including String) are immutable, which means the value of the Object can not be changed. YET this doesn't mean that their references can't be changed as well. A reference to a wrapper class object is NOT final unless you declare it final. so:
String s = "Hi";
s = "bye";
is totally a valid snippit.
The answer is F because the Boolean wrapper class can't be used in an if statement, you need a boolean - with small b - value for the if expression, and that's the trick in the Q.
HTH
 
Adriano Dadario
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that you must inicialize the variable first.
Then the code is:

Remember! Only primitive variables are inicialize with default values. Objects are null
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic