Reputation: 11
is it possible to use the logical operator "!" on object that holds a value of true or false? specifically for an object like this?
public class Briefcase {
private final double amount;
private final String model;
private boolean removed = false;
private String face;
public Briefcase(double amount, int face, String model) {
this.face = Integer.toString(face);
this.amount = amount;
this.model = model;
}
public double getAmount() {
return amount;
}
@Override
public String toString() {
return face;
}
public String getModel() {
return model;
}
public void remove() {
removed = true;
face = "X";
}
public boolean isRemoved() {
return removed;
}
}
then use it like this
Briefcase[] cases = new Briefcase[];
if (!cases[5].isRemoved()) { .... block of code}
is that possible? if so provide me links to that document that and some other examples, I find this weird at the same time interesting
Upvotes: 0
Views: 4960
Reputation: 337
In this case ! negates the value of the call isRemoved() You can have a look here to see the list of operators: http://www.java-tips.org/java-se-tips/java.lang/what-is-java-operator-precedence.html
Also regarding the answer that said you can't write:
Briefcase[] cases = new Briefcase[];
if (!cases[5].isRemoved()) { .... block of code}
[] and . () operators have the same precedence.
The [] index operator will perform first because the line is evaluated from left to right, thus retrieving a Briefcase instance, on which you can call the isRemoved() method.
Upvotes: 0
Reputation: 8421
I am not sure whether you left the index in the array by mistake or design.. but this will definitely work:
if(!cases[i].isRemoved()){ .... block of code}
where i is the index.
Upvotes: 0
Reputation: 49187
The routine isRemoved
only exist on the Briefcase
object, not on the array. To use the negating operation ! you have to try something like the following
for(BriefCase c: cases) {
if (!c.isRemoved()) {
// block of code
}
}
Upvotes: 1
Reputation: 12523
It is. boolean
is a primitive type, but I see nothing weird with using !
.
Upvotes: 0
Reputation: 24791
Yes you can, but not with array as shown in code but as !case.isRemoved()
.
The point here is that !(negate operatior) works on boolean operands.
As long as the operand-expression resolves to a boolean ! this will work.
Upvotes: 0