Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short form for Java If Else statement

I have a method which checks for nulls. Is there a way to reduce the number of lines in the method? Currently, the code looks "dirty":

private int similarityCount (String one, String two) {      if (one == null && two == null) {         return 1;     } else if (one == null && two != null) {         return 2;     } else if (one != null && two == null) {         return 3;     } else {         if(isMatch(one, two))              return 4;         return 5;     }  } 
like image 241
userit1985 Avatar asked Feb 02 '17 10:02

userit1985


People also ask

How do you shorten if else statements in Java?

getName(); else name = "N/A"; 2. You can use ?: operators in java.

What is the short form of ELSE IF statement?

Answer: To use a shorthand for an if else statement, use the ternary operator. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.

What is if else statement in Java?

Java has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


1 Answers

private int similarityCount (String one, String two) {      if (one == null && two == null) {         return 1;     }       if (one == null) {         return 2;     }       if (two == null) {         return 3;     }       if (isMatch(one, two)) {         return 4;     }     return 5; } 
like image 193
Manh Le Avatar answered Sep 19 '22 06:09

Manh Le