This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About Switch Statements

 
Augusteen Chelliah
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String f(int k)
{
switch(k)
{
case 0: return "A";
case 1: return "B";
}
}

gives comile error there is no return statement in the Function f()
Can any one explain
 
Saheed Adepoju
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Augusteen Chelliah:
String f(int k)
{
switch(k)
{
case 0: return "A";
case 1: return "B";
}
}

gives comile error there is no return statement in the Function f()
Can any one explain

Hello
You have a return type of a string and there is no place in your code that has a return, hence it will have a compile time error due to no return type. If you dont want to return any thing then you should just have a "return null" at the end of the method. I hope this helps.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

... and welcome, Augusteen, to the Java Ranch!!!


The compiler knows, that at runtime this method may return nothing. Would be the case if you call e.g.
f(123);
And if it isn't sure, that a String will returned in all circumstances, the code does not compile.

Better than Saheed's idea of returning a null at the very end of the method would be a default case, perhaps returning a blank or empty String (depends on your purposes).


Yours,
Bu.
 
Karthigeyan Kannabiran
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You can also avoid this compilation error just by putting the default case for the switch.

String f(int k)
{
switch(k)
{
case 0: return "A";
case 1: return "B";
default: return "No value";
}
}
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed, you have to guarantee that the method should return the appropriate value. Imagine k being 2, then nothing will be returned and therefore the compiler will complain of course.
 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a method containing a switch statement has a non-void return type and has no return statement, then each case of the switch statement must either have an appropriate return or a throw.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic