Java: Passing Arguments to methods

Passing Arguments to Methods

Java uses the ‘call by value’ method when passing values to a method, and it gives different results depending on the type of the actual parameter.

Java is a reference data type except for eight base types, and if the actual parameter is the base type, it copies the value of the actual parameter to the type parameter. In this case, the value of the actual parameter does not change even though the value of the type parameter changes.

If the actual parameter is a reference type, copy the address of the actual parameter object to the type parameter. In this case, the value of the actual parameter changes as the value of the type parameter changes. This is called call by reference effect.

class ParaPassing1 {
  public void change(int i, int j[], StringBuffer sb) {
    i = 20;
    j[3] = 400;
    sb.append("Easy explained Java!");
  }

  public void display(int i, int j[], StringBuffer sb) {
    System.out.println("The value of the object attribute variable i: " + i);
    System.out.print("The value of the array: ");
    for(int index=0; index<j.length; index++) {
      System.out.print(j[index] + "");
    }
    System.out.println("");
    system.out.println("The value of the string sb: " + sb);
  }
}

class ParaPassingDemo1 {
  public static void main(String args[]) {
    ParaPassing1 cb = new ParaPassing1();
    int 1 = 10;
    int j[] = {1, 2, 3, 4};
    StringBuffer sb = new StringBuffer("Easy to learn?");
    System.out.println("The first call to the display() method");
    cb.display(i, j, sb);
    cb.change(i, j, sb);
    System.out.println("===========================");
    system.out.println("Converts the value and then calls the second display() method");
    cb.display(i, j, sb);
  }
}
Example of passing a value to a method

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post