D
D
DDwrt1002019-09-05 10:24:17
Java
DDwrt100, 2019-09-05 10:24:17

How to correctly use return in a method if there is a branch?

Good day to all.
There was a simple basic question. Maybe someone will tell?
There is a simple code. I get a number and if the number is 1 I return a string, if the number is different then I return nothing.

public String method(int i){
if(i = 1){ return "Hey";)
} else { return null;}
}

I'm having a couple of problems.
1) The compiler wants return to be outside the IF. He is not satisfied that he is in a branch.
Of course I can create a variable outside of the loop and assign a value to it and so on. But how to make the return be right in the branch? And why is this happening?
2) If we have a number not 1, then I do not need to carry out any calculations. How to correctly interrupt the execution of the method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Zagaevsky, 2019-09-05
@DDwrt100

if(i = 1){ return "Hey";)
I think the compiler doesn't like this closing brace. Because if all branches have a return, it suits him.

D
Dmitry Eremin, 2019-09-05
@EreminD

return i == 1 ? "Hey" : null;

C
Cheypnow, 2019-09-05
@Cheypnow

First, i == 1
Second, remove the parenthesis here"Hey";)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question