Thursday 29 January 2015

How to Return Values From a Java Method

This example is based on an earlier post but I have changed it to show how a method can return a value. The first part creates a class called Square:

andrew@UBUNTU:~/Java$ cat Square.java
public class Square
  {
  double width;
  public void display_area()
    {
// The next line calls the calculate_area method.
// The value returned is assigned to area:
    double area = calculate_area();
    System.out.println("Area = " + area);
    }
// The word double in the next line tells you
// that this method returns a double value:
  private double calculate_area()
    {
    double area = width * width;
// The next line returns the value:
    return area;
    }
  }
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$
 

The second part creates a member of the Square class and calls the methods which calculate and display its area:

andrew@UBUNTU:~/Java$ cat SquareExample.java
class SquareExample
  {
  public static void main(String args[])
    {
    Square my_square = new Square();
    my_square.width = 5;
    my_square.display_area();
    }
  }
andrew@UBUNTU:~/Java$ javac SquareExample.java
andrew@UBUNTU:~/Java$ java SquareExample
Area = 25.0
andrew@UBUNTU:~/Java$