I was asked a question in an interview to return 1 if provided 0 and return 0 if provided 1 without using conditions i.e if, ternary etc
Just to give you and idea below code without if's:
public int testMethod(int value){
if(value==0) return 1;
if(value==1) return 0;
return 0;
}
Java Fiddle
UPDATE: Though @Usagi's Answer may seem the best fit with respect to the code I wrote .. but re-considering the question I re-analyzed the answers .. and @Sergio's answer seems the simplest and best fit ..
The void keyword allows us to create methods which do not return a value.
You can return only one value in Java. If needed you can return multiple values using array or an object.
return 0: A return 0 means that the program will execute successfully and did what it was intended to do. return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.
It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void , you will get a compiler error.
If you are given only 0 and 1 then this could be simpler:
return 1 - value;
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