Java Method Parameters

In this chapter you will learn:

  1. What are parameters for
  2. Syntax for Java Method Parameters
  3. How to add parameters to a method
  4. How to use class type as 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;/*from   w  w  w  .  ja  v  a 2 s. c om*/
  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 www .  java 2  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:

Next chapter...

What you will learn in the next chapter:

  1. What is Java class constructor
  2. Syntax for Java Class Constructors
  3. Example - Java Class Constructors