incomparable types boolean and nulltype - java

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.

Related

How to compare object type with boolean

import java.util.HashMap;
public class file{
public static void main(String args[]){
Object a;
a = true;
if (a == true){
System.out.println("Yes");
}
}
}
I get the error error: incomparable types: Object and boolean
I was to compare object a which stores a boolean value with an actual boolean type. How do I do that?
This happens because boolean primitive true is boxed for conversion to Object. You need to compare it to another boxed object, like this
if (a == Boolean.TRUE) {
...
}
or like this
if (a.equals(true)) {
...
}
You are comparing an Object reference to a primitive boolean - the types are not compatible for the equality operator (==). You should generally avoid using == with objects unless you really want to check if it is the same reference.
Prefer the equals method to compare objects.
if (Boolean.TRUE.equals(a)) { ... do stuff ... }
Note that we are invoking the method on a statically defined instance and passing the variable to be tested as the argument. The method will handle null arguments and incorrect type arguments (it will return false) so you don't have to.
Try this -
if (Boolean.TRUE.equals(a)) { ... }

Can Boolean.valueOf(String) return null?

Can Boolean.valueOf(String) ever return null? From what I can see in the java docs, the docs only specify when it returns true. Is false always returned otherwise, or can null be returned? I have not been able to get it to return null in the tests I have done, but I would like to be sure.
Essentially, I want to know if the following code is safe from a NullPointerException:
boolean b = Boolean.valueOf(...);
The docs pretty much answer it: no. It'll return a Boolean representing a true or false.
The code is also available:
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
No, this is impossible. See the source code of the class Boolean:
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
.. and then:
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
Actually it could cause NPE but can not return null. Try this:
Boolean bNull = null;
System.print(Boolean.valueOf(bNull)); // -> NPE!
This happens cuz Boolean.valueOf() accepts String or boolean values. Since bNull is of type Boolean java tries to unbox bNull value to pass it as boolean which causes NPE. Its funny but stupid actually... Also there is no Boolean.valueOf() for Number.
No it will not. If null is placed within the argument or if a string is set to null it will return a boolean value of false. You can see expected inputs and outputs in the Java docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#booleanValue()

boolean (Boolean) - getter is vs get

It looks like everyone says that right getter for:
primitive boolean -> getter is
object Boolean -> getter get
Example:
public class Test {
private boolean primitive;
private Boolean object;
public boolean isPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
//..
}
Question:
Is there any spec or document that states this is correct and this is the way to specify getters for boolean values? Or this is only a common assumption?
I'm asking becouse for example wsimport generates getter is for Boolean object. Is this a tool bug, or this is allowed and correct?
In the other hand some framweorks don't work properly with such getters. For example JSF (EL) or Dozer.
The getter method for the field boolean myField is getMyfield() or isMyField() (it's up to the user to choose). I personally use the second format, as many source code generating tools do.
This format is a standard, it is defined in the JavaBeans specification. See the section 8.3.2 of this documentation:
http://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/
Quote from the docs:
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is<PropertyName>();
The documentation doesn't talk about the primitive wrappers like the Boolean class.
// "is" used because the value can be either true or false. It's like asking isTrue?
public boolean isPrimitive() {
return primitive;
}
// "get" is used because the value returned can be either true, false or null.
// So, the third state 'null' makes you wonder if 'is' should be used or 'get'.
// "get" is more appropriate as Boolean can also have null.
public Boolean getObject() {
return object;
}
But frankly, it's left to the developer. There's nothing "wrong" in using getBoolean() on a boolean value (is makes more sense, that's it).

running boolean method from main

I'm trying to compare two integers or double parameters by using the method from main.
I don't understand what the problem is.
The parameters bitterChocolate_amount and milkChocolate_amount
are defined as integers.
Main:
boolean x = equals(bitterChocolate_amount,milkChocolate_amount)
Method:
public boolean equals (Fat other)
{
if (this == other) {
return true;
}
else {
return false;
}
}
The error message is
required: Object
found: int,int
reason: actual and formal argument lists differ in length
1 error
This public boolean equals (Fat other) is your method accept only one argument. But boolean x = equals(bitterChocolate_amount,milkChocolate_amount) in this you passing two argument.
Do like this
boolean x = equals(bitterChocolate_amount,milkChocolate_amount);
Method:
public boolean equals (int bitterChocolate, int milkChocolate)
{
if (bitterChocolate == milkChocolate)
return true;
else
return false;
}
This public boolean equals (Fat other) method accepts only one argument but you are passing 2 arguments here equals(bitterChocolate_amount,milkChocolate_amount) Also as you said to compare 2 integers then the method will be like this
public boolean equals (int other,int someother)
the problem is your actual and formal parameters doesn't match
you can edit your method like this.
boolean x = equals(bitterChocolate_amount,milkChocolate_amount)
Method:
public boolean equals (int value1,int value2)
{
if (value1 == value2)
{
return true;
}
else
{
return false;
}
}
Actually there is no need for an "equals" method. Simply use operators like:
if(int_a == int_b) { // returns true or false
//my code...
}
Take a look: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Like mentioned above, you're trying to pass two arguments (bitterChocolate_amount,milkChocolate_amount) to a method with only one available parameter (Fat other).
Not to mention the parameter type (Fat) is different to the arguments you're trying to pass in (int, int).
I can't really tell from the scope of the code you provided, but since you're calling that from a main class without any mention of an object instance you probably want to be declaring the method as static too.
This is bread and butter stuff here, I think you should be left alone to figure it out yourself as you'll learn a heck of a lot more that way. I'd recommend a good book if you're interested in long term investment; Head First books and Deitel and Deitel are pretty good.
You call method with one parameter and use two parameters.
The error message is self-explanatory
required: Object
found: int,int
The way you defined your equals method, it expects one parameter of type "Fat".
I assume you must have created the Fat class.
Now you are calling this method using two integer parameters, that's why its saying
required :object (of type "Fat")
and found: int, int
Now lets focus on your requirement
If you just want to compare two integer values, modify your equals method to the one defined below
public boolean equals (int value1,int value2)
{
if (value1 == value2)
{
return true;
}
else
{
return false;
}
}
In your equals method, you have used "this", which means you should call it on an object.
So it should be like this
Fat f = new Fat(3);
Fat g = new Fat(4);
f.equals(g)
But in this case, as you are comparing objects, (this==other) will not work as both the objects are different. == compares the object themselves and not the value they are storing. SO I am not sure what you want to achieve.
It will be better to get the right answer if you clarify your requirements.

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