Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method to return 1 or 0 without using conditions?

Tags:

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 ..

like image 947
Rafay Avatar asked Aug 01 '17 13:08

Rafay


People also ask

Can we develop a method without return type?

The void keyword allows us to create methods which do not return a value.

Can methods only return one value?

You can return only one value in Java. If needed you can return multiple values using array or an object.

What is the difference between return 0 and return 1?

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.

Does a method always need a return statement?

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.


1 Answers

If you are given only 0 and 1 then this could be simpler:

return 1 - value;

like image 61
Sergio Muriel Avatar answered Oct 02 '22 20:10

Sergio Muriel