01.11.2017 Views

book

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The CreateEmployee application sets the variable amount to 500 and invokes the<br />

Employee class increment method with amount as an argument.<br />

CreateEmployee<br />

1 class CreateEmployee {<br />

2<br />

3 public static void main(String[] args) {<br />

4 int amount = 500;<br />

5<br />

6 Employee fred = new Employee();<br />

7 fred.increment(amount);<br />

8 System.out.println("amount outside method: " + amount<br />

);<br />

9 }<br />

10 }<br />

The output of running the CreateEmployee application follows:<br />

> java CreateEmployee<br />

amount within method: 510<br />

amount outside method: 500<br />

CreateEmployee<br />

So although the increment method has increased the amount to 510, the amount in the<br />

calling program remains at 500.<br />

If, however, the argument passed to a method is a reference data type, the memory address<br />

of the argument is copied to the method's parameter. Consequently, both the calling method<br />

argument and the called method parameter reference the same object. If the method<br />

changes the value of this object, then this change is reflected in the calling program. To<br />

illustrate this, the second version of Employee has the increment method modified to<br />

accept an array argument, salary, of type int. The first element of salary is<br />

incremented by 10.<br />

Employee—second version<br />

1 class Employee {<br />

2<br />

3 public void increment(int[] salary) {<br />

4 salary[0] = salary[0] + 10;<br />

5 System.out.println(''amount within method: " +<br />

6 salary[0]);<br />

7 }<br />

8 }<br />

Employee—second version

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!