Passing primitive and reference types method parameters

-Parameters are pass-as-copy for primitive and reference data type
-Object will be passed as copy of reference  
-While passing primitive type as a method parameter, java passes copy of the primitive type to the calling method, so that the original value will be kept different from the copy, which results into two separate variables with separate memory locations.
Examples: int, long, double as a method parameters

-While passing reference type as a method parameter, java passes copy of reference to the calling method (copy of reference but not copy of Object). So original reference variable and its copy are pointing to the same Object memory location. which results into two reference variables pointing to the same Object memory location. With this you can modify Object states using either of the references (original or copy).
Fig. 1: Memory map for primitive and reference data types
-------------------------------------------------------------------------------------------------------------------------
Example: To demonstrate how java passes parameters for primitive and reference data types.
public class TestParamPass {
  public static void main(String[] args) {
  int age = 20; //primitive data type
  Employee emp = new Employee(); //reference data type
  System.out.println("Original age: " + age);
  System.out.println("Original salary: " + emp.getSalary());
  processAge(age, emp);
  System.out.println("Updated age: " + age);
  System.out.println("Updated Salary: " + emp.getSalary());
 }

  //Method to process passed parameters

  private static void processAge(int ageParam, Employee empParam) {
   empParam.setSalary(2000);
   ageParam++;
  }
}
Output:
Original age: 20
Original salary: 0.0
Updated age: 20
Updated Salary: 2000.0
------------------------------------------------------------------------
public class Employee {
     double salary;
     public double getSalary() {
          return salary;
     }
     public void setSalary(double salary) {
          this.salary = salary;
     }
}

1 comment :

  1. Blackjack – Casino & Racing - Dr. MD
    Whether you're into gaming or sports betting, you're 서울특별 출장안마 looking for the best casino games 부천 출장샵 you can play right now. The 김해 출장샵 casino floor offers over 안성 출장마사지 1300 김제 출장샵 games

    ReplyDelete