• Post Reply Bookmark Topic Watch Topic
  • New Topic

return statment  RSS feed

 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is something I want to understand about the return statement of any method, I want to know why
The following code is correct:


but the following code gives me missing return statement error
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you meant:Ok, so tell me what will this method return if g = 3 ?

Assuming you posted whole body of your method just without signature and braces.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a method must always return what it is declared to return. In your second example, is that ALWAYS true?
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:a method must always return what it is declared to return.

... or throw an exception.
 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this a part of my code that if I have multiple if statement each of them return an integer value and the method itself was declared to return an integer but when I compile this method I got an error "missing return statment". but when I change the code to be if.../else if statements, no errors appeared but I don't know why.
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You got "missing return statment" because there are cases when end of method could be reached without hitting a return statement.
Take a look.
Execute this using pencil and paper or in your head. What will the method return if you pass g = 3 into it?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!