I get an error on Eclipse when i try this code
boolean notif = (Boolean) null;
if(notif == null) // <== ERROR at this line saying "No suggestion available" (very helpful)
{
System.out.println("Notif = null");
}
Why it doesn't work ?
boolean is a primitive type, it only accepts true or false. If you want to assign null to your variable, use the object Boolean instead.
Boolean notif = null;
if(notif == null) {
System.out.println("Notif = null");
}
But... if you're using the primitive type, do this:
boolean notif = // true or false;
if(notif) {
System.out.println("Notif = true");
}
else {
System.out.println("Notif = false");
}
EDIT: The difference between Boolean and boolean is that the first one is an object, and it comes with some methods you might want to use. The second one, as a primitive type uses less memory. Now consider those points and choose what you need ;)
More on Boolean object here on the docs.
When you casting null to "Boolean it's wrapper class not the primitive boolean. but when you are comparing you are comparing with the primitive boolean which expects value only true or false not null.
boolean can't be null. It can either be true or false
boolean notif = false;
if(notif)
{
System.out.println("notif is true");
}
else
{
System.out.println("notif is false");
}
while the Object Boolean can be.
You are trying to get the value of all null in the primitive datatype,
instead you should use Boolean class which can be null and suits your type of implementation.
Boolean notif = null;
if( notif == null ) {
System.out.println("notif is null");
} else {
if(notif){
System.out.println("notif is true");
} else {
System.out.println("notif is false");
}
}
Related
I'm making some changes into an old code than requires maintenance, and I found something like this
public boolean aMethod(){
boolean isValid = true;
**isValid = isValid &&** executeGetDocs(id.toString(),program().toString(), document.get(name));
return isValid;
}
The method executeGetDocs may return true or false.
But I'm not sure if: **isValid = isValid && executeGetDocs ** is correct or is just redundant.
So here I am, can anyone please, give me some explanation about this?
Thanks a lot!
EDITED
Whole method:
private boolean validateDocs(List<Map<String, Object>> documentsList) {
boolean isValid = true;
StringBuilder gradoAntComp = new StringBuilder();
for (Map<String, Object> document : documentsList) {
String id = document.get("ID_DOC").toString();
if (id.equalsIgnoreCase("25")) {
isValid = getData(id.toString(),program().toString(), document.get(name))
} else if (id.equalsIgnoreCase("26") ) {
isValid = isValid && getDocs(id.toString(),program().toString(), document.get(name));
}
}
return isValid;
}
Not that we see your entire method, we can see that you're attempting to assign to isValid within a loop. Written this way, the code is using the && conditional-and operator to only execute the method getDocs if isValid is still true.
If a previous assignment to isValid set it to false, then getDocs won't even be called; it will be short-circuited. This means that the && operator already knows that the result of the expression will be false, because isValid is false, so it "short-circuits" the evaluation and doesn't evaluate the other operand -- the call to getDocs.
This makes a lot of sense especially if getDocs is a method with a large overhead cost.
It was redundant in your original question. The original method you posted could be reduced to:
public boolean aMethod() {
return executeGetDocs(id.toString(),program().toString(), document.get(name));
}
since (true && x) == x for any boolean x.
However, since you changed the question, the answer changes as well. Now the boolean variable may change multiple times within a loop. Therefore it makes sense to AND the previous value of the variable (which may be true or false) with another boolean, which might cause its value to change.
private boolean validateDocs(List<Map<String, Object>> documentsList) {
boolean isValid = true;
StringBuilder gradoAntComp = new StringBuilder();
for (Map<String, Object> document : documentsList) {
String id = document.get("ID_DOC").toString();
if (id.equalsIgnoreCase("25")) {
// this can set isValid to either false or true
isValid = getData(id.toString(),program().toString(), document.get(name))
} else if (id.equalsIgnoreCase("26") ) {
// therefore performing logical AND between the previous value of
// isValid and some additional boolean is meaningful - isValid will
// be assigned true only if it was true before this statement AND
// getDocs(id.toString(),program().toString(), document.get(name)) is true
isValid = isValid && getDocs(id.toString(),program().toString(), document.get(name));
}
}
return isValid;
}
As you initialize isValid as true it's useless you can rewrite it as:
public boolean aMethod(){
return executeGetDocs(id.toString(),program().toString(), document.get(name));
}
Not sure if I am wording this correctly however I'm trying to get an input from a user which then checks if the answer is 'yes', and if it is I want it to return 'true', then use this in my main method.
[Main Method]
String inputFromUser = JOptionPane.showInputDialog(null, "Yes/No?");
checkBoolean(inputFromUser);
if(inputFromUser = true) {
System.out.println("Yes, true!"); }
else if(inputFromUser = false) {
System.out.println("No, false!"); }
public static boolean checkBoolean(String inputFromUser) {
boolean returnValue;
if(inputFromUser.equals("yes")) {
returnValue = true; }
else {
returnValue = false; }
}
return returnValue;
}
With this code I get incompatible types in my main method where I am doing inputFromUser = true. Required string but receives boolean.
error: incompatible types. if(inputFromUser = true) {
required: String
found: boolean
How can I make this work exactly? There's probably an answer on this site already but I do not know how to word the question exactly.
Change
checkBoolean(inputFromUser);
if(inputFromUser = true) {
System.out.println("Yes, true!"); }
else if(inputFromUser = false) {
System.out.println("No, false!"); }
to
if(checkBoolean(inputFromUser)) //This is same as if(checkBoolean(inputFromUser)==true)
System.out.println("Yes, true!");
else
System.out.println("No, false!");
In your current code,you try to assign a String to a boolean which makes no sense. I think you meant == there as you want to compare them.But even if you change that,it is wrong as you compare a String with a boolean value. Another way would be t store the return value of the method in a boolean variable and use it in the if.The below code does that:
boolean check = checkBoolean(inputFromUser);
if(check) //This is same as if(check==true)
System.out.println("Yes, true!");
else
System.out.println("No, false!");
Also,your checkBoolean method can be shortened into a single line using
return inputFromUser.equals("yes");
First, inputFromUser = true is an assignment statement that assigns the value true to the variable inputFromUser. The check should use == instead, i.e. assuming inputFromUser had been of type boolean, it should be inputFromUser == true (knowing that you can simply go with if(inputFromUser) in that case).
However, in your case inputFromUser is of type String and this is cause of the compilation error. You should assign the return value of checkBoolean to a variable and use that instead of inputFromUser:
boolean answer = checkBoolean(inputFromUser);
if(answer) {
System.out.println("Yes, true!");
} else {
System.out.println("No, false!");
}
Or you can skip using checkBoolean and go with:
if(inputFromUser.equals("yes")) {
System.out.println("Yes, true!");
} else {
System.out.println("No, false!");
}
Boolean is a different data type to a string. Its not simply a string that contains 'True' or 'False'. Instead of assigning a boolean string to the returnValue variable, just return true or false and remove the return statement from the end. This way you'll only be dealing with boolean values and not strings
That's because inputFromUser variable is of type String and you are comparing it with boolean.
You can do the following:
boolean doContinue = checkBoolean(inputFromUser);
if (doContinue) {//intead of if(inputFromUser = true) {
System.out.println("Yes, true!");
}
And similarly you could change your other conditions. Remember even if your inputFromUser were meant to be a boolean you need to compare it with "==" with true instead of "="
Look at the first line of your code.
The datatype you used is String but you are requesting for a Boolean datatype from the user.
Go ahead and change String to Boolean and recompile your program
I'm programming a Maze and I have some problems.
I have:
HashSet<State> closedList = HashSet<State>(); //it hold State objects
My State class look like this:
public class State implements Comparable<State>{
private double f;
private double g;
private String state;
private State prev;
.
.
.
closedList.add(state);
closedList().contains(state); // this equals true
but when I do this:
State temp = State(0,0,"");
temp.setStateName(state.getStateName());
closedList().contains(temp); // this equals false
I have implemented equals and hashCode in State:
#Override
public int hashCode(){
return state.hashCode();
}
#Override
public boolean equals(Object object){
if(this.state == object){
return true;
}
if(object == null || object.getClass() != this.getClass()){
return false;
}
return false;
}
closedList().contains(state); // this equals true
This is a red herring, it only returns true because HashSet checks with == before it makes a call to equals.
What you should try is something like this:
State temp = new State(0, 0, "");
System.out.println(temp.equals(temp));
And you will find this returns false. Why is that? Well let's follow the logic through.
First, you have this check:
if(this.state == object){
return true;
}
If you really intended this to be the way it is, it means you were expecting equals to be called with the String state as the argument, like this:
temp.equals(temp.getStateName())
(And it's the case the above call would return true.) This is incorrect, one would not expect equals to return true for unrelated classes (and in terms of the equals contract, it's the case this is not symmetric). I assume this is unintended and just like a mistake. You should think more carefully about what your code is doing when you are writing it.
Also you should be comparing Strings with equals, not ==.
Then there is this construct:
if(object == null || object.getClass() != this.getClass()){
return false;
}
return false;
This is pointless because first what it implies logically is this, returning false either way:
if(object == null || object.getClass() != this.getClass()){
return false;
} else {
return false;
}
And, second, combined with the earlier check it is not particularly logical:
if(this.state == object)
return true;
if(object.getClass() != this.getClass())
return false;
This is returning true if object is == to a String but returning false if object's class is not State. These are mutually exclusive.
So the equals implementation you wrote doesn't work. The correct equals to match your hashCode is like this:
#Override
public boolean equals(Object object){
if(object == null || object.getClass() != this.getClass()){
return false;
}
State other = (State)object;
return this.state.equals(other.state);
}
First check that the object is not null and that its class is State (you had that part right), then check that the state member is equal to the other object's state member.
In Eclipse, is there any way to find which return statement a method returned from without logging flags at every return statment?
For example:
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ABC)) {
return false;
}
ABC other = (ABC) obj;
if (var1 == null) {
if (other.var1 != null) {
return false;
}
} else if (!var1.equals(other.var1)) {
return false;
}
return true;
}
In this case, how do I find out at which point my equals method returned?
No, but a more understandable and debug friendly code can be with a boolean local variable that represents the result.
then you can see with debugger who assign it when and the return value before returned.
No. This is one reason that some people prefer single point of exit:
Why should a function have only one exit-point?
Note also the links in the first comment on that question.
Use breakpoints in debug mode.
I tried different ways to fix this, but I am not able to fix it. I am trying to get the Boolean value of an Object passed inside this method of a checkBox:
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String key = preference.getKey();
referenceKey=key;
Boolean changedValue=!(((Boolean)newValue).booleanValue()); //ClassCastException occurs here
}
I get:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
Instead of casting it, you can do something like
Boolean.parseBoolean(string);
Here's some of the source code for the Boolean class in java.
// Boolean Constructor for String types.
public Boolean(String s) {
this(toBoolean(s));
}
// parser.
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
// ...
// Here's the source for toBoolean.
// ...
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
So as you can see, you need to pass a string with the value of "true" in order for the boolean value to be true. Otherwise it's false.
assert new Boolean( "ok" ) == false;
assert new Boolean( "True" ) == true;
assert new Boolean( "false" ) == false;
assert Boolean.parseBoolean( "ok" ) == false;
assert Boolean.parseBoolean( "True" ) == true;
assert Boolean.parseBoolean( "false" ) == false;
From the code you posted, and the result you are seeing, it doesn't look like newValue is a boolean. So you try to cast to a Boolean, but it's not one, so the error occurs.
It's not clear what you're trying to do. Ideally you'd make newValue a boolean. If you can't do that, this should work:
boolean newValue;
if (newValue instanceof Boolean) {
changedValue = newValue; // autoboxing handles this for you
} else if (newValue instanceof String) {
changedValue = Boolean.parseBoolean(newValue);
} else {
// handle other object types here, in a similar fashion to above
}
Note that this solution isn't really ideal, and is somewhat fragile. In some instances that is OK, but it is probably better to re-evaluate the inputs to your method to make them a little cleaner. If you can't, then the code above will work. It's really something only you can decide in the context of your solution.
If you know that your Preference is a CheckBoxPreference, then you can call isChecked(). It returns a boolean, not a Boolean, but that's probably close enough.
Here is some code from the APIDemos Device Administration sample (DeviceAdminSample.java).
private CheckBoxPreference mDisableCameraCheckbox;
public void onResume() {
...
mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());
...
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
...
boolean value = (Boolean) newValue;
...
else if (preference == mDisableCameraCheckbox) {
mDPM.setCameraDisabled(mDeviceAdminSample, value);
reloadSummaries();
}
return true;
}