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:
public class Cat {
public void voice(){
// ...
}
}
This 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:
public class Car{
public int capacity(){
return 600;
}
}
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:
public static void main(String[] args) {
Car car = new Car();
int capacity = car.capacity();
System.out.println("The capacity is " + capacity);
}
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.
public static void main(String[] args) {
Car first = new Car();
Car second = new Car();
Car third = new Car();
double average = (first.capacity() + second.capacity() + third.capacity()) / 3.0;
System.out.println("Capacity average " + average);
}
To summarise:
- A method that returnes nothing has the
void
modifier as the type of variable to be returned:
public void methodThatReturnsNothing(){
// the method body
}
- A method that returnes a string has the
String
modifier as the type of the variable to be returned:
public String methodThatReturnsAString() {
// the method body, requires a return statement
}
- A method that returns a double-precision number has the
double
modifier as the type of the variable to be returned.
public double methodThatReturnsADouble() {
// the method body, requires a return statement
}
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.