Java Method Parameters

Description

Parameters allow a method to be generalized by operating on a variety of data and/or be used in a number of slightly different situations.

Syntax

This is the general form of a method:


type methodName(parameterType variable,parameterType2 variable2,...) { 
   // body of method 
} 

Example 1

A parameterized method can operate on a variety of data.

The new Rectangle class has a new method which accepts the dimensions of a rectangle and sets the dimensions with the passed-in value.

 
class Rectangle {
  double width;/*  w ww .  ja v a2 s .  co  m*/
  double height;

  double area() {
    return width * height;
  }

  void setDim(double w, double h) { // Method with parameters
    width = w;
    height = h;
  }
}

public class Main {

  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle();
    double vol;
    mybox1.setDim(10, 20);

    vol = mybox1.area();
    System.out.println("Area is " + vol);

  }
}

The output:

Example 2

The following code passes objects to methods.

 
class Test {/*from   w w w .  j a v a2  s  .  c o m*/
  int a;

  Test(int i) {
    a = i;
  }
  boolean equals(Test o) {
    if (o.a == a )
      return true;
    else
      return false;
  }
}

public class Main {
  public static void main(String args[]) {
    Test ob1 = new Test(100);
    Test ob2 = new Test(100);

    System.out.println("ob1 == ob2: " + ob1.equals(ob2));

  }
}

This program generates the following output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures