String groupType="local";
if(groupType==null ||groupType.equals("")||!groupType.equalsIgnoreCase("local")||!groupType.equalsIgnoreCase("global")||!groupType.equalsIgnoreCase("universal")){
System.out.print("evlauate to true ");
}
Why does this code evaluate to true, !groupType.equalsIgnoreCase("local") should set it to false ,
Even if you reduce the condition to
if (!groupType.equalsIgnoreCase("local")||!groupType.equalsIgnoreCase("global"))
It will always be true, since groupType can't be equal to both "local" and "global" at the same time.
You probably want to use && (AND) instead of || (OR).
if (groupType == null || groupType.equals("") ||
(!groupType.equalsIgnoreCase("local") && !groupType.equalsIgnoreCase("global") && !groupType.equalsIgnoreCase("universal"))) {
System.out.print("evaluate to true ");
}
Now it will evaluate to true if groupType is either null or empty or isn't equal to one of the values "local"/"global"/"universal". I'm assuming that's what you wanted.
Let's look at each of the operands of the || operator:
the string is equal to null? False.
the string is empty? False.
the string is not equal to "local"? False.
the string is not equal to "global"? True.
the string is not equal to "universal"? True.
Two of the conditions evaluate to true. Therefore, the whole if statement evaluates to true.
maybe you wanted this:
if(groupType==null ||groupType.equals("")
||!(groupType.equalsIgnoreCase("local")
||groupType.equalsIgnoreCase("global")
||groupType.equalsIgnoreCase("universal")
)
)
Related
I'd like to confirm the meaning of != before a boolean expression in a control statement means the opposite:
For example:
if (!networkConnected())
Does that mean "if the network is not connected"?
Yes it does mean the logical opposite. It works even with equals operator.
Assuming your method return a basic bool type
// means the Network is NOT connected
if (!NetworkConnected())
This is equivalent to
if (NetworkConnected() != true)
So logically means
if (NetworkConnected() == false)
Now assuming you method return a Boolean (indeed a real object), this means
// means the Network is NOT connected
if (! Boolean.TRUE.equals(NetworkConnected());
or
if (Boolean.FALSE.equals(NetworkConnected());
Yes, it's boolean negation
So
true == true
!true == false
!!true == true
!!!true == false
Likewise with false
!false == true
The actual name for this unary operator is the Logical Complement Operator which inverts the value of a boolean
Yes. The exclamation mark negates the boolean that appears next to it.
To precisely answer your question: no. This operator != is not negation. It means NOT IDENTICAL and is the opposite of == which stands for identity.
! is a unary operator that switches the boolean value of an expression.
Consider the following piece of code:
boolean b = true;
System.out.println(!b); // outputs: false
System.out.println(!!b); // outputs: true
b = !b; // first switch: b is false now
b = !b; // second switch: b is true now
So:
Does that mean "if the network is not connected"?
Yes!
In java,exclamation mark (!) that is used for inverted the value and also we call Boolean negation operator (!= being not equal to).
example:if(string variable!=null) here check whether string variable
is null or not.null means if block is not executed.otherwise it will
be executed.
In my Java program, this creates a directory and returns a boolean true when successful:
new File(String.valueOf(subdir)).mkdir();
So why does that not work as the second part of this boolean? I.e., the directory does not get created and it does nt return a boolean true.
if (!subdir.exists() || new File(String.valueOf(subdir)).mkdir()) {
logger.error("subdir not created");
}
The second condition won't be calculated if the first condition is already true and the conditions are joined with OR || operator.
Similarly, second condition is not calculated for AND && operator if the first condition is false.
It is so called short circuit for logical operations - because it does not make sense to continue evaluation of other terms if the result of the expression is already defined:
false && any_operand == false
true || any_operand == true
So, in your case you need to use && in the condition and possibly use File::mkdirs() method to create parent directories if they don't exist:
if (!maint.exists() && !maint.mkdirs()) {
logger.info("no directories {} created", maint);
}
In Oracle Java Docs it is mentioned that && operator has higher precedence over || operator.
Please look at the following code:
class TestLogicalOperators
{
public static void main(String... args)
{
if(doFalse() || doTrue1() && doTrue2() )
{
System.out.println(true+" inside if");
}
}
static boolean doTrue1()
{
System.out.println("doTrue1");
return true;
}
static boolean doTrue2()
{
System.out.println("doTrue2");
return true;
}
static boolean doFalse()
{
System.out.println("doFalse");
return false;
}
}
The output is:
doFalse
doTrue1
doTrue2
true inside if
Now if && operator has higher precedence over || operator shouldn't the methods doTrue1() and doTrue2() be evaluated first before doFalse()?
No.
The && operator has precedence, insofar as the expression:
doFalse() || doTrue1() && doTrue2()
... can also be read as:
doFalse() || ( doTrue1() && doTrue2() ) (note the parenthesis).
It doesn't mean the && expression will be evaluated before, your expression is still evaluated left to right.
The || operator can be a shortcut (i.e. no evaluation of second operand), if the first operand is true.
See example below:
// no shortcut, evaluates (true && false) and returns false anyway
System.out.println(false || true && false);
// no shortcut, evaluates (true && true) and returns true
System.out.println(false || true && true);
// shortcut (see warning), evaluates true and disregards "&&" expression
System.out.println(true || false && false);
You are missunderstanding the documentation. It doesn´t mean that the && operator will get executed first, it just says that the conditions surrunding a && are precedence over an other condition with a lower precedence.
In your example you can notice that the compiler is checking the condition of the if statement from left to right.
If we would go straigt from left to right the condition would be: (note parenthesis)
if((doFalse() || doTrue1()) && doTrue2() )
{
//This means either doFalse or doTrue1 would be true and doTrue2 would be true
}
But since the precedence of the && operator is higher then the on of the || operator it is read correctly as
if(doFalse() || (doTrue1() && doTrue2()))
{
//This correctly means either doFalse is true or doTrue1 and doTrue2 are true
}
NO, Normally first condition of OR operation is executed first. Which if evaluated to false, further checks second condition.
Otherwise it doesn't.
Operator && has preference over || but evaluation from left to right is still present and has precedende over operators as described in JLS §15.7
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results
Suppose we use and operator such that
if (a.enable() && b.enable())
so the above statements indicates that both the statements need to be true to proceed
What about the case if a.enable() return false, and if we write the statement such that
if (a.enable() && (b.enable() || c.enable()))
so this above statement means that a.enable() needs to be true and from the second part either b.enable() or c.enable() needs to be true. Either one of them needs to be true to proceed, but if a.enable() is not true then the condition fails without any further checks.
Is this correct?
Yes, && means AND, and || means OR. And they're both short-circuit, so in the following case:
if (a.enable() && b.enable())
b.enable() would not even be called if a.enable() returns false.
And in the following case:
if (a.enable() || b.enable())
b.enable() would not even be called af a.enable() returns true.
That's what allows conditions like
if (s != null && s.equals(foo))
which would cause a NullPointerException if the operator wasn't short-circuit.
if (a.enable() && b.enable())
The 2nd condition will be called only if the 1st condition is true.