I would like to shorten my code by the use of the ?: (if-else-then) comparative operator instead of using the traditional if{}else{} blocks that inconveniently tend to take over the screen. I was never taught about this operator, and I would greatly appreciate any help regarding how to nest multiple comparisons within one line.
This is the code that I would like to shorten:
if(y<0)
y=0;
else
if(y+h>s.getHeight())
y = s.getHeight()-h;
I managed to condense each condition to this (not nested):
y = (y<0) ? 0 : y;
y = (y+h>s.getHeight()) ? s.getHeight()-h : y;
Is this the correct way to nest it?
y = (y<0) ? 0 : ((y+h>s.getHeight()) ? s.getHeight()-h : y);
Thank you!
EDIT: I was given a link to another post pertaining to the ?: operator. Link. However, my question has to do with nesting instead of just a simple if statement. Therefore, my question is not a duplicate of that post.
Yes, this is correct syntax but it's not readable.
You can check by yourself this in Java. Like this:
int a = 3;
int b = 5;
String s = (a < b) ? "Less than b" : (a > b) ? "More than b" : "Equal as b";
System.out.println(s);
But code is much more readable if you use if and if else statements. This ? and : is just for basic if statement.
For example:
int a = 3;
int b = 5;
String s = (a == b) ? "Equal" : "Not equal"
System.out.println(s);
But even in this case, I would rather use if statement. I really don't like to see ? and : instead of if statement :)
Regards,
golobic
You have correctly used ternary operator. However you could have avoided repeated method invocations for s.getHeight().
y = y < 0 ? 0 : y+h > s.getHeight() ? s.getHeight() - h : y;
Use the ?: (ternary) operator instead of an if-then-else statement if that makes code more readable.
ex. result = someCondition ? value1 : value2;
This can be nested further if value1, value2 are also ternary expressions.
Related
I have tried to leave the else part empty for ternary operator ( for int variables ), but I can't do it what is the problem?
here is the code
int FemaleCounter=0, MaleCounter =0, StateCounterIn =0 , StateCounterOut =0;
if(arr[0].equals("male") ) {
MaleCounter ++;
}
if(arr[0].equals("female") ) {
FemaleCounter ++;
}
if(arr[1].equals("in")) {
StateCounterIn++;
}
if(arr[1].equals("out") ) {
StateCounterOut++;
}
here is the ternary operator form :-
MaleCounter = arr[0].equals("male") ? MaleCounter++ : ;
FemaleCounter = arr[0].equals("female") ? FemaleCounter++ : ;
StateCounterIn = arr[1].equals("in") ? StateCounterIn++ : ;
StateCounterOut = arr[1].equals("out") ? StateCounterOut++ : ;
Thanks for your answers .
MaleCounter += arr[0].equals("male") ? 1 : 0;
FemaleCounter += arr[0].equals("female") ? 1 : 0;
StateCounterIn += arr[1].equals("in") ? 1 : 0;
StateCounterOut += arr[1].equals("out") ? 1 : 0;
A ternary expression must deliver a result. Also ++ inside and then assigment is overkill.
As its name indicates, the ternary operator takes three operands. You cannot omit any of them any more than you can omit either operand of any of the binary operators (*, /, ., etc.), or the one operand of a unary operator (++, --, among others).
The fact that an expression using the ternary operator is in some ways analogous to an if / then / else statement is irrelevant here, but the key distinction is important: an expression in the ternary operator evaluates to a value. It is necessary to designate that value for each alternative.
Observe, further, that your analogy is false anyway. You might consider fixing the syntax issue by using forms similar to this ...
// useless
MaleCounter = arr[0].equals("male") ? MaleCounter++ : MaleCounter;
..., but that does not have the same effect as your corresponding if statement, because in the case where the increment is performed, the pre-increment value is afterward assigned back to MaleCounter.
I find your original code pretty clear, but if for some reason you insist on using the ternary operator, then one of these is the model I would follow:
MaleCounter = arr[0].equals("male") ? MaleCounter + 1 : MaleCounter;
FemaleCounter += (arr[0].equals("female") ? 1 : 0);
I have been currently wondering if we can ever use ternery operator in JAVA if only if statement is given, and no else part is to be executed. I worked a lot on it but couldn't find. Is it possible for us to use it this way?
Consider the following if statement having no else clause:
int x = 0;
if (something) {
x = 5;
}
you have to give the variable a default value. Otherwise, it may not be initialized after the if statement, so you wouldn't be able to access it.
This can be written as a ternary conditional expression:
int x = something ? 5 : 0;
Of course, the original if statement can be re-written with else clause:
if (something) {
x = 5;
} else {
x = 0;
}
The typical idiom for writing
if (condition) {
x = newValue;
}
with a ternary operator is
x = condition ? newValue : x;
The idiom here is that when condition is false, the value of the ternary is the current value of x; the entire statement then boils down to x = x;, which effectively does nothing.
You can decide for yourself which way is better...
I am beginner to android, I am looking at this tutorial and came accross this code:
int temp = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
can some one explain this for me.
May be this question is duplicate, but I don't know what to search for.
It will be great if you can tell me what it is in C# aswell.
(sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
means
int result;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
result = 1;
else
result = 0;
I am not 100% sure as what you want to be explained, but it seems that you are not understand/knowing about the ternary operator in Java.
It essentially means:
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
temp = 1;
}
else {
temp = 0;
}
Furthermore, I am unsure if this is correct Java code. It seems like you have left out something of your question, as the ternary operator most likely belongs to either an assignment or a return statement.
If you are talking about the parenthesis, question mark, and colon, then... it goes like so
(Condition ? If_condition_is_true_do_this : otherwise_do_this);
Exactly like doing this:
if(Condition)
If_condition_is_true_do_this
else
otherwise_do_this
And it is the same syntax in C#;
This is Java, not C# but ternary operators exist there as well.
About ternary operators, click here.
What the (full) code (not your snippet) does here is to check the sensor variable for equality with class constant Sensor.TYPE_ACCELEROMETER and assign the missing variable on the left with 1 if they are equal or 0 otherwise.
ı want to use short form for if statement. How can ı write if statement at one line? and how can ı compare them ı know there is same question at here. but my statement do not have else so ı could not do it without else statement.
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
You can use a ternary operator :
return uyum < u.uyum ? -1
: uyum > u.uyum ? 1
: 0;
You perhaps want:
return a < b ? -1 : (a > b ? 1 : 0);
you may simply write this:
public int compareTo(Uyum u) {
return uyum - u.uyum;
}
Inline if statement (question mark) are normally only desired if you have two states. Readability of your code is very important.
In your case you have 3 states (0, 1 and -1); I would not recommend using the inline if statement.
Example inline if statement:
String value = variable==null?"defaultvalue":variable;
This if statement notation is called ternary operator
It seems to me that u.uyum is an int, in which case, why is the following not satisfactory?
return Integer.compare(uyum, u.uyum)
If you really must use a ternary operator, you can do as everybody else is suggesting:
return uyum > u.uyum ? 1 : uyum == u.uyum ? 0 : -1
This tends to be frowned upon though, as it's not terribly legible.
return (uyum-u.uyum)==0?0:((uyum-u.uyum)<0?-1:1)
In Java, if I use a ternary if operator inside a regular if, for example:
if ((x > y - z) ? true : callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
will it execute the callLongWaitedMethod if x > y - z is indeed true? I hope it is not and I can use this nice statement, slightly complicated at the first glance, but more attractive to compare with the extra boolean variable:
boolean b = (x > y - z) ? true : callLongWaitedMethod(many, parameteres);
if (b) {
loveTeddyBear();
}
especially if I'm using this inside a big loop which iterates over and over, so creating boolean each time will not be nice from the performance point of view while if I declare the boolean outside the loop, I may miss the neat because of the big size of the loop.
This will work as you hope, but it would be clearer to simply use the normal || operator to accomplish exactly the same result:
if ((x > y - z) || callLongWaitedMethod(many, parameteres)) {
loveTeddyBear();
}
According to the Java Language Specification 15.25, the long method will only be evaluated if necessary:
The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
callLongWaitedMethod will not be called if x > y - z is true.
If you want to execute callLongWaitedMethod when (x > y - z) is true you actually have to swap the expression:
if ((x > y - z) ? callLongWaitedMethod(many, parameteres) : true ) {
loveTeddyBear();
}
It seems like you have the answer you want. You could also just use debugging statements with a simple version of your code to see what gets executed as a way of verifying the behavior. Something like
if ((1 > 2) ? true : someSimpleMethod()) {
System.out.println("true if");
}
And as your someSimpleMethod() have
public boolean someSimpleMethod() {
System.out.println("calling someSimpleMethod()");
return true;
}
From there you can swap 1 and 2 to see if the someSimpleMethod() would execute.
You should ask yourself as the coder, if you can't figure out what it's going to do, should you really be coding it that way? why not just this:
if ( (x>y-z) ||
(x<=y-z && callLongWaitedMethod(many, parameteres))) {
loveTeddyBear();
}
This will make much more sense to the novice programmer who is not familiar with your code.