Returning a Value From a Method
The method can return a value, but method that can’t return anything is marked by
void keyword in the method definition:
void keyword means that the method doeas not return a value. If you want the method to return a value, we need to replace the
void keyword with the type of the variable to be returned. For example:
In this example
Car class has a method
capacity that always returned an integer-type (int) variable. In this case, the value 600.
This happens the same way as regular value assignment, i.e., by using the equals sign:
The method’s return value is assigned to a variable of type
int value just as any other
int value would be. The return value could also be used to form part of an expression.
- A method that returnes nothing has the
voidmodifier as the type of variable to be returned:
- A method that returnes a string has the
Stringmodifier as the type of the variable to be returned:
- A method that returns a double-precision number has the
doublemodifier as the type of the variable to be returned.
My site is free of ads and trackers. Was this post helpful to you? Why not