How to cast Object to boolean? - java

How can I cast a Java object into a boolean primitive
I tried like below but it doesn't work
boolean di = new Boolean(someObject).booleanValue();
The constructor Boolean(Object) is undefined
Please advise.

If the object is actually a Boolean instance, then just cast it:
boolean di = (Boolean) someObject;
The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:
boolean di = ((Boolean) someObject).booleanValue();
If someObject doesn't refer to a Boolean value though, what do you want the code to do?

Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())

use the conditional operator "?" like this below:
int a = 1; //in case you want to type 1 or 0 values in the constructor call
Boolean b; //class var.
b=(a>0?true:false); //set it in the constructor body

Related

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

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.

Cannot cast from int to MyClass

I have a problem in dealing with the conversion of integer to string. This is my code :
MyClass getRow;
getRow = (MyClass) getListAdapter().getCount();
I found an error on this line: Cannot cast from int to MyClass
This is my MyClass ListView Adapter :
public String toString() {
return myclass;
}
Solved
I have found a solution by adding a few tricks to convert an integer to a string, like this :
int i ;
i = getListAdapter().getCount();
String str = String.valueOf(i);
TextView totalRow = (TextView) findViewById(R.id.totalRow);
totalRow.setText(str);
thanks for all of your answers, awesome Stackoverflow !
int is a primitive and not a class, so the compiler is correct. Why do you expect that an int transform magically into MyClass? What are you trying to do here?
If I understand you correct, you must assing the value of getRow() to your class somehow (either via a setter, by constructor or by accessing the member) and then you can use MyClass. Of course if you want to convert the int to a String object, you have to convert it:
String s = String.valueof(integervalue);
You cannot cast an int to an Object. In the first row you mention you are exactly doing that. getCount() returns an int and you try to cast it to (MyClass).
You never cast primitives to objects in java.
No, you cannot cast this. However, you can achieve a similar effect if you create a constructor for MyClass which accepts an integer as input. So something like:
public MyClass(int x) {
// do stuff to convert as you see fit here
}
then when using it, you do:
getRow = new MyClass( getListAdapter().getCount());

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.

android-java: check boolean value checking for null

I am trying for null check like below
if (isTrue == null)
compile error says : "The operator == is undefined for the argument type(s) boolean"
Please help, how to do null check.
Thanks
You can't do null check on primitive types. boolean is a primitive type.
If you absolutely need to represent a null value with a boolean variable, you need to use the wrapper class java.lang.Boolean.
So, your example would be:
Boolean isTrue;
isTrue = null; // valid
isTrue = true; // valid
isTrue = false; // valid
if (isTrue == null) {
// valid!
}
Here's the WIKIPEDIA entry for primitive wrapper classes.
The right way is
boolean isTrue;
if(!isTrue)
or
if(isTrue)
You can not check if the boolean is null or not.boolean must be true or false.
A boolean is a primative type and cannot be null.
A boolean cannot be null in java.
A Boolean, however, can be null.

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

Categories