Java - Class Method Parameter

One thing to remember

All parameters in Java are passed by value.

Primitive data type Parameter passing

When a parameter is of a primitive data type, the value of the actual parameter is copied to the parameter.

Any changes made to the parameter's value inside the method's body will change only the copy of the formal parameter.

It would not update the value of the actual parameter.

Demo

public class Main {
  public static void test(int a, int b) {
    System.out.println("#2: a = " + a + ", b = " + b);
    a = 10;//from  w w w .j  a v  a 2 s  .c  om
    b = 20;
    System.out.println("#3: a = " + a + ", b = " + b);
  }

  public static void main(String[] args) {
    int a = 1;
    int b = 2;
    System.out.println("#1: a = " + a + ", b = " + b);
    Main.test(a, b);
    System.out.println("#4: a = " + a + ", b = " + b);
  }
}

Result

Pass by Constant Value

To mark a parameter as constant value, use final keyword.

Demo

public class Main {
  public static void test(final int a, int b) {
    System.out.println("#2: a = " + a + ", b = " + b);
    //a = 10;//error 
    b = 20;// w  ww  .jav a  2  s . c  o m
    System.out.println("#3: a = " + a + ", b = " + b);
  }

  public static void main(String[] args) {
    int a = 1;
    int b = 2;
    System.out.println("#1: a = " + a + ", b = " + b);
    Main.test(a, b);
    System.out.println("#4: a = " + a + ", b = " + b);
  }
}

Result

Parameter passing for reference type parameters.

When a parameter is passed by reference value, the reference stored in the actual parameter is copied to the parameter.

You can assign a reference to another object to the formal parameter inside the method's body.

The following code demonstrates the pass by reference mechanism in Java.

Demo

class Car {
  public String model="default model";
  public int year = 0;
  public double price = 0.0;
}

public class Main {
  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.model = "Civic LX";
    myCar.year = 1999;//from  w w w.  jav a 2  s.  co  m
    myCar.price = 16000.0;

    System.out.println("#1: model = " + myCar.model + ", year = " + myCar.year + ", price = " + myCar.price);

    Main.test(myCar);

    System.out.println("#4: model = " + myCar.model + ", year = " + myCar.year + ", price = " + myCar.price);
  }

  public static void test(Car xyCar) {
    System.out.println("#2: model = " + xyCar.model + ", year = " + xyCar.year + ", price = " + xyCar.price);

    // Let's make xyCar refer to a new Car object
    xyCar = new Car();

    System.out.println("#3: model = " + xyCar.model + ", year = " + xyCar.year + ", price = " + xyCar.price);
  }
}

Result

Related Topics

Quiz

Exercise