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

Boolean declaration and initialization

 
Kaz Yosh
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from javacertificate.com
The answer is 1
At line 3, Boolean is declared and initialized.
Is this "correct" correct?

1. public class Wrapper {
2. public static void main(String[] args) {
3. Boolean b = new Boolean("correct");
4. try {
5. Byte by = new Byte("201");
6. Integer i = new Integer("123");
7. Double db = new Double(2.2d);
8. } catch (NumberFormatException nfe) {
9. System.out.println ("Bad number!");
10. }
11. }
12. }

1 NumberFormatException when executing line 5

2 NumberFormatException when executing line 7

3 No output is generated

4 Exception is thrown at line 3, incorrect boolean value

5 Compile time error
 
Meg Adal
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For Boolean with constructor

It creates Boolean object with value "true" if the String s is "true" (in lower/upper case)
So for
For all other string values it creates Boolean object with false value.
Boolean b = new Boolean("false"); // b.toString() is false
Boolean b = new Boolean("correct"); // b.toString() is false
Boolean b = new Boolean("right"); // b.toString() is false
I hope this will help you.
[ May 27, 2003: Message edited by: Megan Adal ]
 
Ryan Wilson
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kaz Yosh:
At line 3, Boolean is declared and initialized.
Is this "correct" correct?
Boolean b = new Boolean("correct");

This is correct. Boolean has a custructor that accepts a String. If the String is equal to "true" (ignores case) then the Boolean is set to true. Any other String will result in "false"
The following is from Sun
public Boolean(String s)Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false. Examples:
new Boolean("True") produces a Boolean object that represents true.
new Boolean("yes") produces a Boolean object that represents false.

Parameters:
s - the string to be converted to a Boolean.
 
Kaz Yosh
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I can say with confident that
NumberFormatException occurs on line 5.
thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic