I thought else at the end of
if{}
else if{}
else if{}
is not necessary in java but unless I put it in the code does not work. why is this?
I thought else at the end of
if{}
else if{}
else if{}
is not necessary in java but unless I put it in the code does not work. why is this?
It's not required. If you are getting an error when you omit it, please post the code that gives you the error.
This compiles and runs for me:
public class ElseIfTest
{
public static void main(String [] args)
{
if (args.length == 0)
{
System.out.println("zero args");
}
else if (args.length == 1)
{
System.out.println("one arg");
}
else if (args.length == 2)
{
System.out.println("two args");
}
}
}
No trailing else required.
The compiler may complain if your if-statements are inside a function that has a return value and you don't return a value for the last "else" part.
Example:
String returnSomething(int i)
{
if (i < 0)
return "negative";
else if (i > 0)
return "positive";
else if (i == 0)
return "zero";
}
The compiler will complain because it thinks that there's a missing return statement if none of the if-conditions are true.
You can fix that by either adding an else at the end, or replacing the last else-if with an else (but you have to make sure that the condition is always true).
So, it becomes
String returnSomething(int i)
{
if (i < 0)
return "negative";
else if (i > 0)
return "positive";
else // it's not < 0 , and not > 0, it is definitely 0
return "zero";
}