Do i also need to return string outside if-else condition ,when the return type is String Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Do i also need to return string outside if-else condition ,when the return type is String without wasting too much if your time.

The question is published on by Tutorial Guruji team.

enter image description hereThe compiler keeps telling to return string.I used if-else condition and from within if-else i have returned string.The compiler problem will be solved if i put return statement at the end of the code but my problem will start .I dont understand how to solve this problem.I want to return right when its right.

Code:

public String isValidID(String id) {
     if(getId().length()!=6) {//checks for 6 digit id
         return "wrong";
     }
     else{//checks if digit contains invalid entry
        for(int i=0;i<getId().length();i++){
            if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
                return "wrong";
            }
     }


}

Answer

In reply to my comment to add return "right" at the end, you said:

but that will make the program return “right ” always.Becoz after if-else condition check ,the compiler will execute rest statement and will return “right” always

Now the source of your confusion is clear: return doesn’t just set the value the method will return, it also exits the method, immediately. So for instance, the return "wrong"; inside your loop will exit from the loop, and the method, immediately. This is true of all the languages I’ve seen that use the return keyword (whereas there are some languages, like VB/VB.Net, where you assign a value to the function’s name to set the return value, but execution continues normally until you use “exit”).

That’s why adding return "right"; at the end is how you resolve this, because the code won’t reach that point if it ever reached return "wrong"; during the program flow above it:

public String isValidID(String id) {
     if(getId().length()!=6) {//checks for 6 digit id
         return "wrong";                        // <== Exits immediately if reached
     }
     else{//checks if digit contains invalid entry
        for(int i=0;i<getId().length();i++){
            if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
                return "wrong";                 // <== Exits immediately if reached
            }
     }
     return "right";                            // <== Exits immediately if reached
                                                // (granted, we would have exited
                                                // below anyway :-) )
}
We are here to answer your question about Do i also need to return string outside if-else condition ,when the return type is String - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji