Why does this not compute in Java (v1.8). Seems perfectly logical to me....
boolean banana = true;
(banana == true || false) ? System.out.println("True") : System.out.println("False");
Output message: Error: java: not a statement
The ternary conditional operator must return a value. The second and third operands can't be statements that don't return anything. They must be expressions that return a value.
You could switch it to :
System.out.println(banana ? "True" : "False");
Note that banana == true || false is equivalent to banana == true, which is equivalent to banana as banana itself is a boolean type.
The Java Language Specification ยง15.25 says:
It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.
Better try like this:
System.out.println(banana ? "true" : "false");
What you want is
boolean banana = true;
System.out.println(banana ? "True" : "False");
A ? : operator has to return a value and println is a void method. Not only does it do what you want, it is more concise.
Note
banana == true
is the same as
banana
and
x || false
is the same as
x
Also unless you need to print "True" instead of "true" you can do
System.out.println(banana);
How about this?
System.out.println(banana ? "true" : "false");
The ternary operator always has to return a value which we're printing.
The other way is only using if-else statement, but it's not pretty.
if(banana)
System.out.println("true");
else
System.out.println("false");
You are using it incorrectly.
One use of the Java ternary operator (also called the conditional operator) is to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b) or Math.max(a,b) method call. Here's an example that assigns the minimum of two variables, a and b, to a third variable named minVal is:
minVal = (a < b) ? a : b;
You can do it like this.
if(boolean)
System.out.println("True");
else
System.out.println("False");
I guess because Java won't allow statement like that.
Try using if statement.
boolean banana = true;
if (banana == true || false) System.out.println("True"); else System.out.println("False");
Because there are only false bananas: https://en.wikipedia.org/wiki/False_banana. There is not any one "true" banana. You are likely thinking of the "true plantain", see https://en.wikipedia.org/wiki/True_plantains. Changing your banana to false will allow your code to once again be copacetic with biology.
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.
I have a simple if/elseif condition which I'm trying to convert it into a return statement with Ternay Operator for code redundancy but I have not been able to.
Any help would be appreciated, Thanks.
Here's my code snippet :
if (val.equals("a")||val.equals("s")){
return true;
}
else if (val.equals("b")||val.equals("t")) {
return false;
}
return true;
Could someone please suggest on how to proceed with return statement(Ternary Operator) for the above if/else-if ?
There's no need for a conditional operator here. Your code will return true so long as val is neither b nor t:
return !(val.equals("b") || val.equals("t"));
or:
return !val.equals("b") && !val.equals("t");
The first condition around a and s is completely irrelevant, as the "default" return true at the bottom already includes those cases.
EDIT: Now that you've changed the return type to int, this would be reasonable to use with the conditional operator:
return val.equals("b") || val.equals("t") ? 0 : 1;
return !(val.equals("b") || val.equals("t"))
The rest is redundant, val cannot equal "a" or "s" and equal "b" or "t" at the same time, so you basically need to check if it equals "b" or "t", and return false in this case, and true in any other case.
return !(val.equals("b") || val.equals("t"));
This is the only condition that returns false - so you don't need to check the first condition.
return !(val.equals("b") || val.equals("t"))
Try the follwing:
boolean b = ( val.equals("b") || val.equals("t") ) ? false : true;
return b;
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
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 9 years ago.
I came across this syntax:
System.out.println(boolean_variable ? "print true": "print false");
What is this syntax with two dots : called?
Where can I find info about it?
Does it work just for booleans or is it implemented in other different ways?
? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
So something like this:
int x = condition() ? result1() : result2();
is roughly equivalent to:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:
int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4
So, if the boolean expression evaluates to true, it will return the first value (before the colon), else the second value (after the colon).
You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?
It's a ternary operator, meaning that instead of having two operands like many other operators, it has three. Wikipedia on Ternary Operation and how it's used in Java. What it boils down to: the boolean operation (or just a variable) is evaluated. If it evaluates to true, the operator returns the value / executes the code before the :, otherwise the one after it.
That's an if statement.
What's to the left of ? is the condition, what's between the ? and : is the result if the condition is true, and what's to the right of : is the result if the condition is false.
This is ternary operator (http://en.wikipedia.org/wiki/?:). It can be used anywhere when you need a small if expression.
For your questions:
The ?: (both characters together) are called conditional operator (or ternary operator). Only both together will work.
Search for java ternery operator
It only works for boolean
In principle the ternery operator is a shortened if/else. The boolean will be the condition to the if, the part between ? and : is the if branch and the part after this is the else branch.
Please note that the return type of the conditional operator is determined by the first branch.
It's the ternary operator and it works with booleans. It can be used as a shorthand for if-else in some cases, but shouldn't be used for too complicated things as it can be difficult to read.
An example would be assigning value to a variable depending on a condition:
String message = doOperation() ? "Success" : "Error occurred";
System.out.println(message);
In this case, if doOperation returns a boolean telling whether it succeeded or not, the message to be shown can be assigned on a single line.
Please note that this example does not represent good programming practices.
Its ternary operator.
The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.
boolean b = true;
String s = ( b == true ? "True" : "False" );
This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:
boolean b = true;
String s;
if(b == true){
s = "True";
}else{
s = "False";
}
Its a short form of if-else statement.
It works in this way
(yourCondition ? STATEMENT1 : STATEMENT2)
The compiler checks for the condition.
IF it returns TRUE then STATEMENT1 will be executed.
ELSE STATEMENT2 will be executed.
The question mark followed by a colon (two dots) is a ternary operator usually called inline if.
In this case it returns a string depending on the value of boolean_variable.
http://en.wikipedia.org/wiki/%3F:
See here. The ternary operator is similar to an if expression but differs in that it is an expression - it has a return value, while if expressions don't. Sometimes you want to use it to make your code a little less cluttered.
This question already has answers here:
java ternary operator
(2 answers)
Closed 9 years ago.
I think this question is a general programming question,
but let's assume I'm asking this for Java.
what does the following statement do ?
return a ? (b || c) : (b && c);
I have seen the syntax with ?'s and :'s in many topics at SO, this particular one I found in Check if at least two out of three booleans are true
But I don't know what they mean, so how to use them, and I believe it's something very useful for me.
Thanks !
That's the conditional operator. It means something like:
condition ? value-if-true : value-if-false;
So in your case, it returns b || c if a is true, and b && c if a is false.
This is known as a ternary statement; it's shorthand for an if-else block - you can google that for more info.
Your example is equivalent to
if (a) {
return (b || c);
} else {
return (b && c);
}
condition ? first statement : second statement
if condition is true then first statement is executed otherwise the second statement
It's the ternary operator, the whole statement expands to something more like this:
if a == true then
if b == true or c == true then
return true
else
if b == true and c == true then
return true
As your link says a much more elegant way to check if at least 2 out of three booleans are true when applied in this way!
its an conditional operator... jst like if and else....
e.g----
a<b ? 4 :5 where a= 2 and b=5
as a is less then b.... then this operator will return 4... else it return 5....
in short... if your condition i.e statement before ? is correct then it returns 1st value.. i.e statement before colon.... else it returns 2nd value......
According to your code,
return a ? (b || c) : (b && c);
Result will be like this :
if a == true , then result = b || c
otherwise result = b && c
its a ternary operator & used in most of the languages C,C++, java, Javascript