Java Quiz 22

Test your knowledge of Boolean variable states ?

 

package quiz;

public class Quiz22 {
  
  static String str;
  
  public static boolean test1(){
    return new Boolean("1");
  }
  
  public static boolean test2(){
    return new Boolean(str);
  }

  public static void main(String[] args) {

    if(test1())
      System.out.print("1");
    if(!test2())
      System.out.print("2");
    if(test1() != test2())
      System.out.print("3");
  }

}

© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

4 comments

  1. Java Boolean Wrapper class is not design properly, which shouldn’t expose such constructor, if it was design after Enum, it would be just two enum values – TRUE, FALSE, and could just do == and !=, similar to boolean primitive did. It is up to developer to decide which String should be considering as “truthy” using Factor design.

  2. Derek Berner

    When == or != is checked on the Boolean, the boolean primitive is compared.

    This is incorrect. Boolean objects are not unboxed for == and !=. The reason “3” is not printed is because test1() and test2() return boolean primitives, so they are unboxed before the function returns.

    1. Thanks Derek !! This has been updated in the quiz.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: