Is it necessary to write else part , if we have written the else-if part, in Java?
for example
if(i>10){
//some code here
}
else if(i<10 && i>5){
//some code here
}
else{
//so in cases like this do we need to make, this else part??
}
Is it necessary to write else part , if we have written the else-if part, in Java?
for example
if(i>10){
//some code here
}
else if(i<10 && i>5){
//some code here
}
else{
//so in cases like this do we need to make, this else part??
}
It is important because the else if is still a condition and if the user does not follow that condition, they can get an error prompt.
But unless it's something chosen by a computer, maybe not, but I prefer to put an else statement on everything and making it print out error so it's easier to point it out to fix.
So I think you should do it like this:
if (i > 1) {
//some code here
} else if (i < 1) {
//some code here
} else {
system.out.println("ERROR, or just ERROR AT ________");
}
I hope this helped you, but if you decide to not put an else statement, that is ok, just make sure you are considering every possibility before not putting on in!
No it is not necessary. You can check this by compiling the code it won't throw an error.
However here in your example the else part can be useful to catch invalid inputs for example
// Porgramm to define spaces in positive numbers
if( i > 10){
System.out.println("Greater than 10");
}
else if(i > 5 && i < 10){
System.out.println("Number is 6, 7, 8, or 9");
}
else if(i >= 0 && i <= 5){
System.out.println("Number here is 0, 1, 2, 3, 4, 5");
}
else{
// so in cases invalid input
System.out.println("Your input was invalid!! The number have to be positive");
// You could also think about throw an exception here.
throw new Exception("Invalid Input!");
}
if(x < 5){
//do something if x is less than 5
} else if( x > 5 ){
//do something if x is greater than 5
} else{
//do something if x is equal to 5
}
So in the above code we check if x is less than 5 and we also check if x is greater than 5. We didn't check if x was equal to 5.
So what i'm trying to explain is that the else
statement is a way to execute some code if none of the if
and else if
conditions were true