Example Java method that return values
In this tutorial, we will learn how to write Java methods that return values to the caller method i.e main method. Below is an example of java code with methods that return double datatypes.
Example Java Method with void
public void readRadius() {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter radius =:”);
radius=sc.nextFloat();
}
Java method with return type
public double getPerimeter() {
perimeter = 2*Math.PI*radius;
return perimeter;
}
Java Program
The complete java program with the Java methods.
import java.util.*; public class JavaMethodsDemo { private double radius=00.0; private double area=0.0; private double perimeter=0.0; /*********************************** * This is an example of java method that doesn't * return anything i.e void ***********************************/ public void readRadius() { Scanner sc = new Scanner(System.in); System.out.print("Enter radius =:"); radius=sc.nextFloat(); } /*********************************** * Java method that returns area * to the caller of the data type double. ***********************************/ public double getArea() { area= Math.PI*radius*radius; return area; } /*********************************** * Java method that returns perimeter * to the caller of the data type double. ***********************************/ public double getPerimeter() { perimeter = 2*Math.PI*radius; return perimeter; } public static void main(String []args) { JavaMethodsDemo area=new JavaMethodsDemo(); area.readRadius(); System.out.println("Area of circle :" +area.getArea()); System.out.println("Perimeter of circle :" + area.getPerimeter()); } }
Program Output
Enter radius =:5.0
Area of circle :78.53981633974483
Perimeter of circle :31.41592653589793