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; } }
getName(); else name = "N/A"; 2. You can use ?: operators in java.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With