Ternary operator gives "Not a statement" error [duplicate] - java

This question already has answers here:
ternary operator not working
(3 answers)
Closed 4 years ago.
Hi below statement throws error . It says "Not a statement"
map.containsKey(1)? someObject.setFlag(true) : map.put(1,"hello");
Is it needed to store the returned value in some variable on the left hand side of the statement?

You are using the Ternary operator as a statement, not an assignment. In your case, you should use if else
if(map.containsKey(1)) {
someObject.setFlag(true)
}else{
map.put(1,"hello");
}
Here is the java docs of Ternary operator.

The ternary operator is an expression, not a statement. It is commonly used to set the value of a variable depending on some condition. In this case, you need to assign the result to a variable in order to make it into a statement:
String result = map.containsKey(1) ? someObject.setFlag(true) : map.put(1,"hello");
(Note: You should choose a better variable name.)
I think you will still have problems here because setFlag() probably doesn't return a String. Also, since you are creating side effects, you should replace this with an if statement.

Related

Ternary Operator. true is empty [duplicate]

This question already has answers here:
Java: Ternary with no return. (For method calling)
(6 answers)
Closed 7 years ago.
I was wondering how this code would look like with the ternary operator
if (a) {
// pass
} else {
b();
}
We got no(thing) code to execute when a is true but in case a is false there is some code b() which is then executed.
So we write that:
a ? : b();
But I am not sure if that is correct when you let the code for true empty or if you have to replace it with something. Actually I never use the ternary operator but we were asked to do so.
That's not what the conditional operator is for... it's not to execute one statement or another, it's to evaluate one expression or another, and make that the result of the expression.
You should write your code as:
if (!a) {
b();
}
Actually I never use the ternary operator but we were asked to do so.
If you were asked to do so for this particular situation, then I would be very wary of whoever was asking you to do so. My guess is that it was actually not quite this situation...
If you had tried this code, then you would get compiler errors because the ternary operator expects expressions, not statements. The true section doesn't even have an expression or a statement. If b() returns void, then the false section is a statement, not an expression. If b() returns something, then it can be considered an expression and it would be ok.
If you have statements to execute, and you don't have to choose an expression value, then choose if/else over the ternary operator. Your first if/else can be simplified to:
if (!a)
{
b();
}
This isn't possible. Taken from the official Oracle Docs:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
The conditional operator ? : uses the boolean value of one expression
to decide which of two other expressions should be evaluated.
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The definition of "ternary" is "Composed of 3 parts". If you want only one possible evaluation of your condition, you will just have to use an if statement.

Expressions vs Literals && Expressions vs Statements [duplicate]

This question already has answers here:
Expression Versus Statement
(21 answers)
Closed 7 years ago.
What's the significant difference between Expressions vs Literals && Expressions vs Statements in Java? I'm aware that an expression represents a simple value or a set of operations that produces a value. However, literals can also be a simple value which makes it a little confusing to make difference between them. Could smb explain the differences? Thanks in advance!
A literal is a notation for representing a fixed value in source code. For example: 'a', "a", Object.class, and 1 are all literals. Their value is known at compile-time, and they are expressions, since they evaluate to a single value.
Statements are complete units of execution. Most statements terminate with a semicolon. For example: new Object(); is a statement, while new Object() is an expression that returns a reference to a newly created object. Examples of statements that don't terminate with a semicolon are blocks and control flow statements.

parameters in this function call are not understood [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
This function is supposed to take two parameters, however there are characters included that I do not understand what they mean. What is the value of "?". What are the two parameters in this function, I know panel.id is one of them . any link to a library that explain them well ? thank you
setPanelType(panel.id, ((encType) ? PANEL_ST_ENC : PANEL_NORMAL))
The duplicate question posted here might be explaining what the "?" operator is. However I was not sure if it is used differently in a function parameter call. This question is not a duplicate of any.
You've run in to something called the "conditional operator"*. It's basically a short way of writing an if-statement.
For example:
String var;
var = 1 > 0 ? "It's bigger than 0" : "It's 0 or smaller";
Is the same as:
String var;
if(1 > 0){
var = "It's bigger than 0";
}else{
var = "It's 0 or smaller";
}
* It's also sometimes called the "ternary" operator, but that's not quite correct. It's a "ternary operator" (an operator that accepts three operands, just like the multiplication operator * is a binary operator because it accepts two operands), but in theory there could be others. In fact, I think it's the only ternary operator in Java or JavaScript (at least for now).
This syntax is shorthand for a conditional action in Javascript.
(condition) ? (true action) : (false action)
Related: JavaScript ternary operator example with functions
The '?' means Ternary Operator as said above, encType is a boolean variable.
setPanelType(panel.id, ((encType) ? PANEL_ST_ENC : PANEL_NORMAL))
is equals to:
if (encType)
setPanelType(panel.id, PANEL_ST_ENC))
else
setPanelType(panel.id, PANEL_NORMAL))

The ? boolean zen operator [duplicate]

This question already has answers here:
Short IF - ELSE statement
(6 answers)
Closed 9 years ago.
Ive never used the ? operator before and i'm trying to figure out how it works.
I have been reading countless pages and decided to try for my self.
i have the following statement:
getSelection().equalsIgnoreCase("Måned") ? calendarView.currentlyViewing.set(Calendar.Year) : showPopup();
So as far as i cant understand if the left hand side (boolean) is true it will set my calendarView.to year and if not (getSelection is not equal to måned) it will call the method showPopup();
but when i type this into eclipse i get a syntax error.
can someone explain what i am doing wrong?
You're trying to use the conditional ? : operator to decide which statement to execute. That's not its intention. The conditional operator can't be used as a statement - it's only to choose which expression to use as the overall result.
So this is fine:
foo(condition ? nonVoidMethod1() : nonVoidMethod2());
but this isn't:
condition ? voidMethod1() : voidMethod2();
You should just use an if statement here:
if (getSelection().equalsIgnoreCase("Måned")) {
calendarView.currentlyViewing.set(Calendar.Year);
} else {
showPopup();
}

The expressions which evaluate to a boolean value can not be concatenated with a String in Java. Why? [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 2 years ago.
Let's see the following simplest code snippet in Java.
final public class Parsing
{
public static void main(String[] args)
{
int p=10;
int q=10;
System.out.println(p==q);
}
}
The above code in Java is fine and displays true as both p and q of the same type (int) contain the same value (10). Now, I want to concatenate the argument of println() so that it contains a new line escape sequence \n and the result is displayed in a new line as below.
System.out.println("\n"+p==q);
Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java. Therefore, the above mentioned statement is invalid and it issues a compile-time error. What is the way to get around such situations in Java?
and surprisingly, the following statements are perfectly valid in Java.
System.out.println("\n"+true);
System.out.println("\n"+false);
and displays true and false respectively. How? Why is the same thing in the statement System.out.println("\n"+p==q); not allowed?
You have to add parentheses () around p==q (the way you write it, it will be interpreted as ("\n"+p) == q, and String cannot be compared to a boolean). This operator precedence is desired for expressions like
if(a+b == c+d)
etc. So,
System.out.println("\n"+(p==q));
Should work just fine.
System.out.println("\n"+p==q);
compiler treat it as
System.out.println(("\n"+p)==q);
Use
System.out.println("\n"+(p==q));
Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java.
This is completely wrong. Concatenating anything to a String is implemented by the compiler via String.valueOf(), which is also overloaded to accept booleans.
The reason for the compiler error is simply that + has a higher operator precedence than ==, so your code is equivalent to
System.out.println(("\n"+p)==q);
and the error occurs because you have a String and an int being compared with ==
On the other hand, this works just as intended:
System.out.println("\n"+(p==q));
The order of precedence of operators means that your expression gets evaluated as
("\n" + p) == q
It is nonsensical to compare a string to an int so compilation fails, try:
"\n" + (p == q)
Ah. The statement is wrong.
System.out.println("\n"+(p==q));
~Dheeraj

Categories