Simplifying statements - java

I am working on a project and I am using Intellij IDEA. While I was writing I got a notification that my if-statement could be simplified. (Note that I am still new to coding)
It says:
Reports if statements which can be simplified to single assignment or return statements.
For example:
if (foo()) {
return true;
} else {
return false;
}
can be simplified to
return foo();
How does this work?
Say foo() is the number 4, wouldn't this just return 4 instead of true? What am I misunderstanding?
Edit
Here is the code I am writing:
if (row > 0 && row < 4 && col > 0 && col < 4) {
return false;
} else {
return true;
}
and it can be simplified to:
return !(row > 0 && row < 4 && col > 0 && col < 4);
I just don't understand how this is simplified.

(row > 0 && row < 4 && col > 0 && col < 4) is itself a boolean (true or false).
We can break it down as boolean && boolean && boolean && boolean as < and > operators return booleans. Likewise, a boolean and a boolean is a boolean, therefore the entire expression is a boolean and can be returned as such.
You can think about it as such:
For the row, you have a number, so you can say "how many" or "which number". Same for the column.
For the comparisons, you can ask: If x and y are numbers, then is x < y? The answers possible are true or false. Hence boolean.
For &&, ||, or !, you can ask yourself: "If a and b are statements (true or false), then "a and b are both true" is either true or false. Same for "or", or "a is not true". The results are true and false.
Now you can look at the if, and read it as "if foo is true, then return false. Otherwise, return true". This clearly simplifies to "return the opposite of foo" or, "return not foo".

Your Foo() method returns a boolean value, so it will be true or false. Therefor, you do not need to add redundancy by adding an if statement to check for true or false, and then return true or false.

For an if statement to compile, the condition between parenthesis, has to be a boolean.
So, if you can put the method foo as the condition of an if, it's because it returns a boolean.
Therefore, you could write:
return foo();
In your particular case, the expression !(row > 0 && row < 4 && col > 0 && col < 4) evaluates to true or false, Therefore you could write:
return !(row > 0 && row < 4 && col > 0 && col < 4);

I have similar code like you:
if (other.getClassAbbr().equals(this.getClassAbbr())
&& other.getInstance().equals(this.getInstance())) {
return true;
}
return false;
After thinking of it, I take the suggestion:
'if' statement can be simplified
Then the code be changed to:
return other.getClassAbbr().equals(this.getClassAbbr())
&& other.getInstance().equals(this.getInstance());
Yes, code gets clean.

Related

conditional changes behavior when converted to ternary operator?

I am writing a function that compares the number of vowels in the first half of a string and compares it with the second half, and returns a boolean based on if the number is equal.
Example:
Input: "book"
Output: true
because bo | ok, numVowels = 1, one 'o' in both halves.
My code that works is here
class Solution {
public boolean halvesAreAlike(String s) {
Set<Character> set = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
int vowelCount = 0, length = (s.length()%2 == 0) ? s.length()/2 : s.length()/2+1;
boolean pastHalf = false;
for (int i = 0; i < s.length(); i++) {
if (i == length) pastHalf = true;
if (pastHalf && set.contains(s.charAt(i))) vowelCount--;
else if (!pastHalf && set.contains(s.charAt(i))) vowelCount++;
}
return vowelCount == 0;
}
}
In the if (i == length) pastHalf = true; line, I am checking to see if I have hit the middle of the String. This is a simple boolean. I changed it to this ternary pastHalf = (i == length) ? true : false; and the output was wrong for the test case Ieai. Does anyone know why? I believe that the statements are equivalent.
if (i == length) pastHalf = true;
is most definitely NOT the same as
pastHalf = (i == length) ? true : false
In the first case, pastHalf is changed only when i is exactly equal to length, so as you iterate beyond length, pastHalf remains true.
In the second, at each iteration pastHalf is reset, so pastHalf is true only when i is exactly equal to length.
Other improvements:
length = (s.length()+1) % 2; // Think about this one carefully
and
if (set.contains(s.charAt(i)))
vowelCount += pastHalf ? -1 : +1;

Returning multiple values from a method based on a condition

I have a function and I need to change the return value based on a condition, I managed to get only one return cause the data is static while I need to make it dynamic as shown in below code
public boolean outBound(int c_x, int c_y) {
return (blackCarX > 150 && blackCarX < 690 && blackCarY > 200 && blackCarY < 500);
}
I need to say if the x or y equals a specific number, return a different output
any advice?
This is the error I am receiving for my condition:
if (c_x > 150 && c_x < 690 && c_y > 200 && c_y < 500){
return(c_x, x_y);
}
DrawCars.java:132: error: ')' expected return(c_x, x_y) ^
DrawCars.java:132: error: not a statement return(c_x, x_y) ^
DrawCars.java:132: error: ';' expected return(c_x, x_y)
You can use if else statement
public boolean outBound(int c_x, int c_y) {
if(blackCarX > 150){
return a;
} else if (blackCarX < 690){
return b;
}
}
if you have only 2 values you can also use ? statement
public boolean outBound(int c_x, int c_y) {
return blackCarX > 150 ? a : b;
}
You need to use an if-else statement
or,
the ?: operator
Your question is not clear on how you want to use c_x or c_y so I'm making my own little example below.
For instance,
if-else statement
if(a > b) {
return i;
} else {
return j;
?: operator
(a > b) ? return i : return j // This does same thing as 1.

Prime Number checker is not working

This is the code for a function that is supposed to return true if the input is prime and returns false if it is not.
This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. Since 1(n) is less that 7(y) the loop can iterate. The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true.
I don't understand why it isn't working.
public static boolean checkIfPrime(long y) {
for ( long n =1L; n <= y; n++) {
if(y%n == 0) {
if( n != 1L || n != y) {
return false;
}
}
}
return true;
}
With a few optimizations the code will be like this
static boolean isPrime(long n){
long lim = (long) Math.sqrt(n);
if(n%2 == 0 && n != 2)
return false;
for (int i = 3; i <= lim; i=i+2)
if(n%i == 0)
return false;
return true;
}
This code:
checks if the number is even and different from 2 (all even numbers
except 2 are compound).
next iterates from 3 to sqrt(n), thats because to prove a number is
prime you don't need to check all the dividers (if you don't believe
me try, and if still don't believe use n/2 wich is enough but not the
minimum value).
For loop pace start from 3 and add 2 in each iteration getting only odd numbers as divder (we first checked that it wasn't an even number).
Remove equal to operator in n <= y. Start your loop from 2. It must be like this. ( long n =2; n < y; n++)
For what you are trying to achieve, pseudo code in my opinion should look like this:
set a flag = true;
Loop from 2 to y-1{
if(y%n==0){
flag = false
break; // Very important
}
}
check flag condition & return (if some othe computation is required) or just return flag
if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. try to avoid it.
Why use a flag instead of direct return statement ? Just a preference, a direct return definitely would work in this case.

Java boolean method needs extra return statement?

I am starting with java and while I was writing a way to identify whether a number was prime I wrote a method like this
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !Prime;
}
else if(((n % x) == 0) && (n > x)){
return Prime;
}
else {
return Prime;
}
}
What I couldn't figure out was the necessity of the last else statement. If I do not put it, I get an error message. However I don't think it is necessary since all possibilities are covered by the previous loops, with their respecting return statements. Or am I missing something?
You don't need the else. What you are being told by the compiler is the method must return SOMETHING. Your last else block could replaced by this:
return PrimeOrNot;
In fact, your method could look like this:
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
return (PrimeOrNot);
}
In any case your very last statement block cannot be an else if.
The method has a return type of boolean.
The compiler is scared by the possibility in which none of the 'if' cases are met. In this situation, the method know what to return. This method needs to return something, so just give it a 'return true' before the method ends. It won't ever be read, but it will make the compiler happy.
The conditional expressions within the if/else-if are only evaluated at runtime. Normally, the compiler wouldn't know what the result would be, because they are not evaluated at compile-time. Only, situation when the compiler can figure what the result of the expression would be is when it's some compile-time constant (like if(true) {).
public static boolean checkPrime(int n){
boolean PrimeOrNot = false;
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
else if(((n % x) == 0) && (n > x)){
return (PrimeOrNot);
}
return PrimeOrNot;
}
A method which returns a value will be compilable if it returns a value in all its possible code paths.
Imagine for a moment that you're the compiler. You see this code:
int myMethod()
{
if (cond)
return anInt;
}
While you may know that cond is in fact always true, the compiler will not know that. It can only be sure about the result of a boolean expression if it is an expression which can be evaluated at compile time only.
Note that the vast majority of "code optimization" in Java is in fact done at run time (JIT: Just In Time).
The compiler only checks to see if there are valid return paths from your method. The compiler isn't "smart" enough to inspect the conditional statements and determine whether the conditions can be logically met -- the compiler simply checks to make sure that some value is returned to respect the contract of the method declaration.
Some would argue that the following is a cleaner structure for the method (but I think it is just a matter of taste):
public static boolean checkPrime(int n){
int x = 2;
while (((n % x) != 0) && (n > x)){
x = x + 1;
}
if(((n % x) == 0) && (n == x)){
return !(PrimeOrNot);
}
return (PrimeOrNot);
}

Java value of if statements

In Java can I return a boolean value with the following:
public boolean areBothEven(int i, int j) {
return (i%2 == 0 && j%2 == 0);
}
Or do I need to surround the statement with an if and then return true and false appropriately?
No, in fact doing stuff like return xxx ? true : false; or if (xxx) return true; else return false; is generally considered redundant and therefore bad style. In your case, you might even speed things up slightly by avoiding the && (which may incur a branch mis-prediction):
return (i | j)%2 == 0;
The expression is of boolean type, and is therefore suitable to be returned. You do not need to use an if statement.
The syntax is correct. But, zero is neither even nor odd, isn't it?
So, may be
return i !=0 && j !=0 && i%2 == 0 && j%2 == 0;

Categories

Resources