Menu

Pass by reference and pass by value in Java

Today in this tutorial of Java program we will see how to work with pass by value and pass by reference. 

Below is code snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

package com.rashid.jorvee;


public class ValueRef {

 public static void main(String[] args) {

  Employee emp=new Employee();

  ValueRef valref=new ValueRef();

  emp.setSalary(12000.00);

  System.out.println("Employee emp salary: " +emp.getSalary());

  valref.salary(emp);

 }

 public void salary(Employee em){

  em.setSalary(14000.00);

  em=new Employee();

  em.setSalary(15000.0);

  System.out.println("Employee em salary: " +em.getSalary());

 }

}



class Employee{

 double salary;

 public double getSalary() {

  return salary;

 }


 public void setSalary(double salary) {

  this.salary = salary;

 }
}

Output:
Employee emp salary: 12000.0
Employee em salary: 15000.0 

No comments:

Post a Comment