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();
}
Related
This question already has answers here:
If statement executing all conditions
(9 answers)
Closed 4 years ago.
Got a basic if statement question, so I have an if statement in Java as shown here:
if (
!isOmitted(word,map.get(word.length()+1)) &&
!isInserted(word,map.get(word.length()-1)) &&
!isTransposed(word,map.get(word.length())) &&
!isSubstituted(word,map.get(word.length())) &&
!isCapital(word,map.get(word.length())))
{
noSuggestion=true;
}
where each individual method works perfectly as desired. Is there any way for java to check all conditions even when one is false? I know that the nature of the && operator is that as soon as a condition does not hold true, there is no point in checking the remaining conditions, as the entire condition is going to be set to false, but I was hoping I could do something like this in order to keep my code someone cleaner. I know I can use boolean variables, and assign the returned value to 5 different variables, but is there any other work around to force every condition to be checked? Thanks a lot in advanced
A single & is a non-short-circuit operand - ie both sides are evaluated irrespective of whether required.
More info here - https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.2
However, this sounds like a poor design. In fact, some code analysis tools would automatically flag these operators as suspicious for this reason. Typically you would want to call each method as they make some change to the state of your objects, which is not something you would expect in an if statement. But your method names do not suggest this. What are you trying to achieve?
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
OK, my first question in stackOverflow.
This is something that I left me completely baffled.
Java (I use android Studio), I write the following code:
Integer aNumber = 200;
String aNumberInString;
aNumberInString = Integer.toString(aNumber);
Boolean result;
if(aNumberInString == "200"){
result = true;
} else {
result = false;
}
Log.i("result:",result+"");
OK, logic and what I expect is that the condition is true... But NO! it fails.
I was really shocked by this behavior, then investigate a little more, and run the code in debug mode step by step.
when I get to the condition, I inspect the value of "aNumberInString" and to my surprise, this is what I find:
OK, so the first thing I think is: "Integer.toString ()" are doing something wrong.
Let's try another way: "String.valueOf ()"
Run in debug mode, and:
THE SAME! and fails, of course.
Obviously fails because it compares different characters, and in Internet I found a way to fix it,
string.replace ("\\ u0000", "");
but my question is not how to fix it, is:
Why is this happening?
Is there a correct way to prevent this from happening?
From already thank you very much to all,
Regards, Nicolas
You are doing a reference comparison. For comparing Strings, you need to call equals. By doing == with an Object, you are asking Java to make sure they are the same object, not if they have the same value.
Change:
if(aNumberInString == "200"){
To this:
if(aNumberInString.equals("200") {
Or better yet, to reduce the chance of a NullPointerExcpetion:
if("200".equals(aNumberInString))
This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 7 years ago.
Just a general Java question. Why does the null variable exist? I'm working with some introduction to CS students and one of the most common mistakes is semi-colons where they are not supposed to be. For example
if(isTired());{
sleep(10);
}
The misplaced semi-colon before the open parenthesis keeps the if statement from working correctly, and I was wondering why the null line did in a Java program. In this example null seems to be a detriment and was wondering when someone would use it when coding.
The null statement is useful because there are some places in Java where you want to do nothing. They are not frequent, but they exist. Often they are the 'compulsory' statements that you have to put in as part of a construct. For example, if you want to write a for loop that only terminates on a 'break', then you want there to be nothing in the 'conditional' part of the for:
for (int i=0;;i++) {
int j = complexCalculation(i);
if (j<0 && complexCondition(j)) {
break;
}
}
If the null statement wasn't allowed, that wouldn't compile. If it was allowed there, but not in other places, that would be inconsistent (and make life more difficult for compiler writers).
The reality is that, once you get to be fairly proficient with the language, errors caused by accidentally adding null statements are rare.
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))