Soniya Soniya - 1 month ago 10
Java Question

Java return a value from a method using nested if else statements

I have a method that returns something depending on the if conditions. But when I am using the below code, it doesn't recognize my return statement and says to change the method declaration to void. Can you please help optimizing the code.

if(myList == null){
return abc;
} else {
for(myList myListItem : myList){
if(myList.getId() != null){
if(TEST1.equals(myListItem.getId())){
return abc;
} else if(TEST2.equals(myListItem.getId())){
return xyz;
} else if(TEST3.equals(myListItem.getId())){
return pqr;
}
}
}
}

Answer
if(myList == null){
    smth = abc;
} else {
    for(myList myListItem : myList){            
        if(myList.getId() != null){
          if(TEST1.equals(myListItem.getId())){
            smth = abc;
          } else if(TEST2.equals(myListItem.getId())){
            smth = xyz;
          } else if(TEST3.equals(myListItem.getId())){
            smth = pqr;
        }
    }  
 }
   return smth;
    }

Try this it will work for your function with different conditions

Comments