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;
Related
class Solution {
public boolean isMonotonic(int[] A)
{
boolean increasing = true;
boolean decreasing = true;
for (int i = 0; i < A.length - 1; ++i)
{
if (A[i] > A[i+1])
increasing = false;
if (A[i] < A[i+1])
decreasing = false;
}
return increasing || decreasing;
}
}
Can anyone please explain how the return value is working.
increasing || decreasing means increasing OR decreasing. If either variable is true then the whole method will return true, otherwise it will return false.
|| is the logical OR operator.
So, the return value is an example of functional programming || is working as if condition.
return increasing || decreasing;
abobe line is similar to
if (increasing || decreasing)
return true;
else
return false
it will return true if one of them or both is true.
False if both are false.
private Comparator<Entity> spriteSorter = new Comparator<Entity>() {
public int compare(Entity e0, Entity e1) {
if (e0 == null || e1 == null) return -1; //was 0
if (e1.getY() < e0.getY()) return +1;
if (e1.getY() > e0.getY()) return -1;
return -1; //was 0
}
};
I have read many articles about this one, but I still don't know how to solve this little problem:
This is the core that works:
if (e1.getY() < e0.getY()) return +1;
if (e1.getY() > e0.getY()) return -1;
But sometimes (I have to deal with many houndred entities which are being added and removed from a concurrent array list very often in a second) one of the entities is null. Therefore I have to check this inside this comparator.
But then I violate this general contract, once one of the two objects is null.
Any idea how I can solve this? Please help! :)
Your comparator, if called with c.compare(null, null), will compare null < null, even though they are equal. Further, it breaks the rule for inverses, which is that sgn(compare(a, b)) == -sgn(compare(b, a)), that is, comparing two things backwards returns the opposite of comparing them forwards. You can fix all this simply by treating null as "negative infinity," that is enforcing that null < a for all nonnull a and null == null.
public int compare(Entity l, Entity r) {
if (Objects.equals(l, r)) return 0; // Handles normal and null equality
else if(l == null) return -1; // Enforce null < a ∀ nonnull a
else if(r == null) return +1; // Enforce a > null ∀ nonnull a
else return Integer.compare(l.getY(), r.getY()); // Base comparison
}
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.
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);
}
Just a declaimer:i am a beginner in java.
Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.
public int numUnique(int x,int y,int z){
if(x==y||y==z){
}
return 1;
else if(x!=y||y!=z){
}
return 2;
}
I am very confused about the relationship of if and return.I always put return inside if statement.But i dont understand why does it generate me an error message.if something is fulfil,i return in the loop.Why is it wrong.But on the other hand,the println statement can be put inside for loops.
Another issue,because this question,i tried to attempt using if else too.But my first condition is if and i return it.So after that i placed else if after the first return,it gives me error again.
I will appreciate someone will explain to me and i will alter the codes on my own.Please dont give me the full codes.Thank you.
Edited*
By the way,i read through all the comments and i finally understand it.This is my codes that i work out on my own(:
public static int numUnique(int x, int y, int z) {
if(x==y && y==z){
return 1;
}else if(x==y && y!=z || y==z && z!=x || x==z && y!=z ){
return 2;
}
return 3;
}
The return statements should be placed within the curly bracets.
To give you a clear understanding of "return" statements, i will say there can be only one return statement in one block of code i.e {...}.
"return" statement is used to return to the caller, and it has to be last statement of the block.
As suggested by you i am not providing you complete code, rather making you aware of usage of "return" statement.
In your code you are writing two "return" statements in one block.
i think you need to write return statements inside if-else blocks otherwise it will always return 1
The syntax for a what you want looks like this:
public static int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}else if(x!=y||y!=z){
return 2;
}
return 3;
}
Maybee this code ist better understandable:
public static int numUnique(int x, int y, int z) {
if (x == y && x == z && y == z) {
return 3;
} else if (x != y && x != z && y != z) {
return 1;
}
return 2;
}
Pseudocode If
if( condition ){
// do something if condition is true
}
Pseudocode If then else
if( condition){
// do something
}else{
// do something if condition is false
}
Pseudocode elseif
if( condition ){
// do something
}else if(condition2){
// do something, only if condition2 is true, if condition 1 is true, you never will be here
}else{
// do something, your only here if the two conditions above were false
}
A return statement, immidiently brakes execution ( there are some exception, exmaple: the finally block)
First, your return are outside the if statements, they should be inside. Because if you write:
if(Something) {
}
return 1;
Then 1 will be always returned because your if is empty. If you want to return 1 only if(Something) then write it inside the if body:
if(Something) {
return 1;
}
Second, your logic is not good. You need to check:
if x == y == z then they're all equal.
if x == y and x != z then you should return 2.
if x != y != z then you should return 0.
....
You need to cover all situations.
since if is a conditional flow, i may or may not run (depending on the condition),
but if your method has return type it should return in every cases. But in the later case, (if condition is false), it wont find any return.
so if you write
public int value(boolean flag){
if(flag){
return 0; //only reachable if flag is true, else value can not return from here
}
}
it is wrong, since if flag is false method wont return anything. so you must provide a return in else or after if block ends
using the fact that Sets store values only once...
public int numUnique(int x,int y,int z){
Set<Integer> number = new HashSet<Integer>();
number.add(x);
number.add(y);
number.add(z);
return numbers.size();
}
You have to put the return statement in the block from if and else:
public int numUnique(int x,int y,int z){
if(x==y||y==z){
return 1;
}
else if(x!=y||y!=z){
return 2;
}
}
it fails because the compiler think, that you have not a return statement for the function in every path.
Your code is ill-formed:
And if-else statement is as following:
if { code }
else { code }
So, if and else blocks make a pair. But you have:
if (condition) { code }
code
else { code }
code
So, the code just above the word else breaks this pair, and else remains isolated, and thus your program is syntactically incorrect.
You "want" to do:
if (x==y || y == z) {
return 1;
}
else if (x != y || y != z) {
return 2;
}
Moreover, if a if (or else) block has only one line, you can erase the brackets:
if (x==y || y == z)
return 1;
else if (x != y || y != z)
return 2;
Even more, you algorithms isn't a solution to your problem, ¿how about 3 unique values?. You should check more situations (all diferents, all equals, or only one different).