Java - How do if statements know the values of a Boolean object? - java

How do if statements recognize the Boolean object as a boolean? such as:
Boolean b = new Boolean(true);
if(b){
System.out.println("true!");
} else {
System.out.println("false!");
}
This would print true, but how is Boolean recognized?

It is called autoboxing and works for primitive types in Java, look here for a brief SO explanation or here for the official documentation. Java automatically converts the object representation Boolean into the corresponding primitive type boolean and back. The first is called unboxing and the latter boxing.

Related

incomparable types boolean and nulltype

When I compile my code this way, I get the mentioned error:
public class SymTree{
public static boolean isSym(BT bt)
{
return(IsMirror(bt.left, bt.right));
}
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr==null) (((ERROR HERE)))
return true;
.....
However when I compile like this
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr)&&(lr==null))
return true;
.......
I get no error. The error is uncomparable types with nulltype and boolean, however non of my compared objects are boolean- they are both objects from a BT(Binary Tree) class, which has been defined elsewhere.
Thank you!
Examine (lr==rr==null). lr==rr is a boolean. It is primitive and can not be compared to null.
The reason it's giving you that error is because when you write this:
if (lr==rr==null)
The compiler interprets it similar to one of the following:
if ((lr==rr) == null)
if (lr == (rr==null))
Basically, you're comparing a boolean condition (either lr==rr or rr==null) to a nullable type, which doesn't make sense since booleans are value types and can never be null.
It is because in if(lr==rr==null), lr==rr is a boolean comparison which you are comparing with a null by doing ==null.
For Example, if suppose lr is equal to rr then lr==rr will return true next you are comparing whether true==null. Here you get error because boolean and null are not comparable.

Correct way of initializing a Boolean

How a Boolean instance has to be initialized?
Is it
Boolean b = null;
or
Boolean b = new Boolean(null);
Which one is the correct coding practice?
The first one is correct if you want a null Boolean.
Personally I don't like having null values and prefer to use boolean, which cannot be null and is false by default.
In order to understand what the second statement does you need to understand about Java primitive wrappers. A Boolean is simply an object wrapper around a boolean; when you declare directly:
Boolean b = false;
There is some autoboxing going on and this is essentially equivalent to writing
Boolean b = Boolean.FALSE;
If you declare a new Boolean then you create a new and separate Boolean object rather than allowing the compiler to (possibly) reuse the existing reference.
It rarely (if ever) makes sense to use the constructor of the primitive wrapper types.
There is absolutely no need to create a new object for Boolean.
This is what javadoc says
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.
â—‹Boolean b = new Boolean(null); use Boolean(String) ctor and set b internal boolean value to false and is different to set b reference to null.
Boolean b = null;
System.out(b.boolValue()); throws a NullPointerException
but
Boolean b = new Boolean(null);
System.out(b.boolValue()); will print `false`
If you need only two-state value (a boolean) use a primitive boolean; if you need a three-state object (null, true, false) use Boolean object and set object reference - as in first example - to null
Both are correct declaration
Boolean b = null;
This is constant creation and it will go to constant pool memory. You need to use == operator to compare two boolean constants.
Boolean b = new Boolean(null);
This is object creation and it will go to Heap memory.You need to use .equals() method to compare two boolean objects.

Implement Comparator for primitive boolean type?

I need some classes implements Comparator, and for one I want to compare primitive boolean (not Boolean) values.
IF it was a Boolean, I would just return boolA.compareTo(boolB); which would return 0, -1 or 1. But how can I do this with primitives?
You can look up how it is implemented for the java.lang.Boolean, since that class, naturally, uses a primitive boolean as well:
public int compareTo(Boolean b) {
return (b.value == value ? 0 : (value ? 1 : -1));
}
As of Java 7 you can simply use the built-in static method Boolean.compare(a, b).
Since Java 7, the logic that Marko Topolnik showed in his answer has moved into another method to expose a way to compare primitive boolean.
Javadoc for Boolean.compare(boolean x, boolean y):
public static int compare(boolean x, boolean y)
Compares two boolean values. The value returned is identical to
what would be returned by:
Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
An even better approach and correct use of Boolean-Adapter class
public int compare(boolean lhs, boolean rhs) {
return Boolean.compare(lhs, rhs);
}
EDIT:
Hint: This sorts the "false" values first. If you want to invert the sorting use:
(-1 * Boolean.compare(lhs, rhs))
You can use java's autoboxing feature to alleviate this problem. You can read about autoboxing here: Java autoboxing
You can compare two primitive boolean values b1 and b2 in following way.
(Boolean.valueOf(b1).equals(Boolean.valueOf(b2))

Does Java allow nullable types?

In C# I can a variable to allow nulls with the question mark. I want to have a true/false/null result. I want to have it set to null by default. The boolean will be set to true/false by a test result, but sometimes the test is not run and a boolean is default to false in java, so 3rd option to test against would be nice.
c# example:
bool? bPassed = null;
Does java have anything similar to this?
No.
Instead, you can use the boxed Boolean class (which is an ordinary class rather a primitive type), or a three-valued enum.
you can use :
Boolean b = null;
that is, the java.lang.Boolean object in Java.
And then also set true or false by a simple assignment:
Boolean b = true;
or
Boolean b = false;
No, in java primitives cannot have null value, if you want this feature, you might want to use Boolean instead.
Sure you can go with Boolean, but to make it more obvious that your type can have "value" or "no value", it's very easy to make a wrapper class that does more or less what ? types do in C#:
public class Nullable<T> {
private T value;
public Nullable() { value = null; }
public Nullable(T init) { value = init; }
public void set(T v) { value = v; }
public boolean hasValue() { return value != null; }
public T value() { return value; }
public T valueOrDefault(T defaultValue) { return value == null ? defaultValue : value; }
}
Then you can use it like this:
private Nullable<Integer> myInt = new Nullable<>();
...
myInt.set(5);
...
if (myInt.hasValue())
....
int foo = myInt.valueOrDefault(10);
Note that something like this is standard since Java8: the Optional class.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
Yes you can.
To do this sort of thing, java has a wrapper class for every primitive type. If you make your variable an instance of the wrapper class, it can be assigned null just like any normal variable.
Instead of:
boolean myval;
... you can use:
Boolean myval = null;
You can assign it like this:
myval = new Boolean(true);
... And get its primitive value out like this:
if (myval.booleanValue() == false) {
// ...
}
Every primitive type (int, boolean, float, ...) has a corresponding wrapper type (Integer, Boolean, Float, ...).
Java's autoboxing feature allows the compiler to sometimes automatically coerce the wrapper type into its primitive value and vice versa. But, you can always do it manually if the compiler can't figure it out.
In Java, primitive types can't be null. However, you could use Boolean and friends.
No but you may use Boolean class instead of primitive boolean type to put null
If you are using object, it allows null
If you are using Primitive Data Types, it does not allow null
That the reason Java has Wrapper Class

Java Switch Incompatible Types Boolean Int

I have the following class:
public class NewGameContract {
public boolean HomeNewGame = false;
public boolean AwayNewGame = false;
public boolean GameContract(){
if (HomeNewGame && AwayNewGame){
return true;
} else {
return false;
}
}
}
When I try to use it like so:
if (networkConnection){
connect4GameModel.newGameContract.HomeNewGame = true;
boolean status = connect4GameModel.newGameContract.GameContract();
switch (status){
case true:
break;
case false:
break;
}
return;
}
I am getting the error:
incompatible types found: boolean required: int on the following
`switch (status)` code.
What am I doing wrong?
You can't switch on a boolean (which only have 2 values anyway):
The Java Language Specification clearly specifies what type of expression can be switch-ed on.
JLS 14.11 The switch statement
SwitchStatement:
switch ( Expression ) SwitchBlock
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.
It is a lot more readable and concise to simply use an if statement to distinguish the two cases of boolean.
you don't want to switch on a boolean, just use a simple if/else
if (status) {
....
} else {
....
}
edit : switch is only used for ints, chars, or enums (i think that's all, maybe there are others?)
edit edit : it seems short and byte are also valid types for switching, as well as the boxed versions of all of these (Integer, Short, etc etc)
Switch statements in Java can use byte, short, char, and int (note: not long) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it became possible to use enum types. Starting with Java SE 7, it became possible to use Strings.
Can't use boolean in switch, only int. Please read the Java docs for the switch statement.
Switch takes an integer value, and a boolean cannot be converted to an integer.
In java, a boolean is a type in its own right, and not implicitly convertible to any other type (except Boolean).
In Java, switch only works for byte, short, char, int and enum. For booleans you should use if/else as there are a very limited number of states.

Categories