Java Method Example


A method in Java, like a function in C/C++ (in fact, a function of C/C++ is called a methods in Java), embeds a few statements. A method is delimited (separated) from the remaining part of the code by a pair braces. Method increases reusability. When the method is called number of times, all the statements are executed repeatedly. Java comes with static methods, final methods and abstract methods. All the three varies in their functionalities. This "Java Method Example" tutorial gives with normal methods. Other methods you can refer this site later.
Java Method Example
public class Demo
{
  public void display()                                    // a method without any parameters
  {
    System.out.println("Hello World");
  } 
  public void calculate(int length, int height)            // a method with parameters
  {
    System.out.println("Rectangle Area: " + length*height);
  } 
  public double show(double radius)                        // a method with parameter and return value
  {
    System.out.println("Circle Area: " + Math.PI*radius*radius);
    return 2*Math.PI*radius;
  } 
  public static void main(String args[])
  {
    Demo d1 = new Demo();                                  // create object to call the methods
    d1.display();    
    d1.calculate(10, 20);
    double perimeter = d1.show(5.6);
    System.out.println("Circle Perimeter: " + perimeter);
  }
}

Java Method ExampleOutput Screenshot on Java Method Example

Three methods are given with different variations and called from main() method. To call a method, an object is required. An object d1 of Demo class is created and called all the methods.

1. How to write methods, how to call variables from methods is discussed with good notes in Using Variables from Methods.
2. More in depth study is available at Using Methods and Method Overloading .

Leave a Comment

Your email address will not be published.