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;
Related
This question I found on my class work and I got confused
I haven't tried anything
public static String evenOrOdd(int num) {
return num%2==0?"Even":"Odd";
}
The code runs fine; I just wanna know how it works.
Ternary operator is just like if else statement.
if (num % 2 == 0) {
return "Even";
} else {
return "Odd";
}
If the part before ? mark is true then you will get the result before : .
If false then after :
It is basically an if elsestatement.
If the condition is true, it will return the first option. If not (if it is false), it will return the second:
num%2==0?"Even":"Odd";
If num%2==0then it is Even. If not, then it is Odd.
It is a one-liner to:
if(num%2==0) return "Even";
else return "Odd";
look for ternary operator
above code is short form of
public static String evenOrOdd(int num) {
if(num%2==0){
return "even";
}else{
return "Odd";
}
}
This is called a ternary operator and its logic works as follows
a question ? positive answer : negative answer
or, using more formal terms
boolean expression ? return value for true : return value for false
So, your question is about num % 2 == 0 which means if a remainder for the num divided by two is zero. If this is the case – it's an even number, if not – it's an odd number, and that is why a corresponding string value is returned.
Need best approach in the following scenario,
I've list of attributes like source , destination, Yes/No as below:
Example:
source , destination , Yes/No
abc, bcd, Yes
abd, gdc, Yes
In java i can go with condition like
if(Obj.getSource().equals("abc")) {
if(Obj.getDest().equals("bcd")) {
return true;
}
}
if(Obj.getSource().equals("abd")) {
if(Obj.getDest().equals("gdc")) {
return true;
}
}
In this way i can handle the above case , based on the resultant Yes , i can handle my business logic.
But my approach was two many check and , lines of codes to lengthy,
Please suggest me good approach in java7 or java8.
You can just combine all four conditions into one using logical operators. For example by using logical and && and logical or ||. It could then look like:
if ((first && second) || (third && fourth)) {
return true;
}
Or with all conditions substituted:
if ((Obj.getSource().equals("abc") && Obj.getDest().equals("bcd"))
|| (Obj.getSource().equals("abd") && Obj.getDest().equals("gdc"))) {
return true;
}
Note that you may memorize the result of Obj.getSource() and Obj.getDest() in a variable in order to save some performance and make the condition more readable by using that variable instead.
And if you would return false; in the other cases you could even completely leave out the whole if as you could directly return the boolean resulting after evaluating the condition (it evaluates to either true or false, no need to return true and false hardcoded then):
return (first && second) || (third && fourth);
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.
Just switched to Java from php
I encountered following issue
I want to rewrite
if(usrname.equals(username) && (passwd.equals(password))){
return true;
}
else{
return false;
}
as
(usrname.equals(username) && passwd.equals(password) )? return true : return false;
it is not working(syntax error)
however,
int a=1;
int b=2;
int minVal = a < b ? a : b;
is working
Why ternary operator are not behaving correctly while returning value depending on some condition
EDIT
return (usrname.equals(username) && passwd.equals(password));
could be solution if it return boolean .
lets say i need
(usrname.equals(username) && passwd.equals(password) )? return "member": return "guest";
You can do
return (usrname.equals(username) && passwd.equals(password) )? true : false;
true and false can be replaced by any return value you want. If it is just boolean then you can avoid ternary operator altogether. Just do
return (usrname.equals(username) && passwd.equals(password));
lets say I need
(usrname.equals(u) && passwd.equals(p)) ? return "member" : return guest";
The correct syntax is:
return (usrname.equals(u) && passwd.equals(p)) ? "member" : "guest";
The general form of the ternary operator is
expression-1 ? expression-2 : expression-3
where expression-1 has type boolean, and expression-2 and expression-3 have the same type1.
In your code, you were using return statements where expressions are required. In Java, a return statement is NOT a valid expression.
1 - This doesn't take account of the conversions that can take. For the full story, refer to the JLS.
Having said that, the best way to write your example doesn't uses the conditional operator at all:
return usrname.equals(username) && passwd.equals(password);
Why redundant boolean
Just use
return (usrname.equals(username) && passwd.equals(password));
By the way you can simplify:
return (usrname.equals(username) && passwd.equals(password) )? return true : return false;
To:
return usrname.equals(username) && passwd.equals(password);
The ternary operator work similar in php than Java, I think you have made a silly mistake, maybe "username" have a space or another white character
String a1 = "a";
String b1 = "b";
String a2 = "a";
String b2 = "b";
System.out.println((a1.equals(a2)&&b1.equals(b2))?"true":"false");
it return "true"
Java ternary operator is an expression, and is thus evaluated to a single value.
As per the Javadocs, for below given expression
result = someCondition ? value1 : value2;
if the boolean condition is true then assign the value of value1 to the result, else assign value2 to the result. Both value1 and value2 should be of same value type.
Hence the correct syntax of a return statement would be
return boolean_condition ? value_when_true : value_when_false
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