What do return statements do in java




















Thanks for sharing good post. Keep it up. This site uses Akismet to reduce spam. Learn how your comment data is processed. Author Recent Posts. Founder at Kode Java Org. I am a programmer, a runner, a recreational diver, currently live in the island of Bali , Indonesia. If these posts help, you can support me, buy me a cup of coffee or tea. Latest posts by Wayan see all. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:.

If you try to return a value from a method that is declared void , you will get a compiler error. Any method that is not declared void must contain a return statement with a corresponding return value, like this:. The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.

The getArea method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:. The getArea method returns a primitive type.

A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:.

If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance. Case 2: Methods not returning a value For methods that do not return a value, return statement in Java can be skipped. Note: Return statement not required but can be used for methods with return type void. Now moving ahead geek you must be wondering what if we do use return statement at the end of the program?

Note : return statement need not to be last statement in a method, but it must be last statement to execute in a method. This article is contributed by Rajat Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Skip to content. Change Language.

Related Articles. Basics of Java. Operators in Java. Packages in Java. Flow Control in Java.



0コメント

  • 1000 / 1000