### Popular

 Pass-by-value vs Pass-by-reference in Java and C++
Written by FemiByte
Tuesday, 29 April 2014 03:36

# Pass-by-value vs Pass-by-reference in Java and C++

In this article I illustrate what it means to pass-by-value as opposed to pass-by-reference with a focus on Java vs C++.

The question often asked is this : Is Java pass-by-reference ?
A common and often erroneous answer is : Java is pass by reference for objects, and pass-by-value for primitives.
This is WRONG. To illustrate why this is so, let me refer you to this quote by the father
of Java himself, James Gosling:

Some people will say incorrectly that objects are passed “by reference.” In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory…. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode — pass by value — and that helps keep things simple.

– James Gosling, et al., The Java Programming Language, 4th Edition

The above clearly states that Java passes object references by value meaning that when the reference is passed, a copy of that reference (which is an address) is passed. Since the copy of the reference and the reference refer to the same object, if a call is made to a method that modifies the object in Java, that object is modified, hence the line “Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other”.

I will now illustrate what pass-by-reference means, via a clear example in C++.

Let us create the following files in an appropriate directory with the following contents:

PassByReference.hpp:
#ifndef PassByReference_hpp#define PassByReference_hppvoid swapIntByRef(int& iParam, int& jParam);void swapIntByVal(int iParam, int jParam);#endif

PassByReference.cpp:
#include <iostream>#include "PassByReference.hpp"using namespace std;

 int main(){int i=1000;int j=2300; cout << "Illustration of Pass By Reference:\n";cout << "Before: i= " << i << " j=" << j;cout << "\n";swapIntByRef(i,j);cout << "After: i= " << i << " j=" << j;cout << "\n"; cout << "\nIllustration of Pass By Value:\n"; i=1100;j=2500; cout << "Before: i= " << i << " j=" << j;cout << "\n";swapIntByVal(i,j);cout << "After: i= " << i << " j=" << j;cout << "\n"; } void swapIntByRef(int& iParam, int& jParam){int temp(iParam);iParam=jParam;jParam=temp;} 

void swapIntByVal(int iParam, int jParam){int temp(iParam);iParam=jParam;jParam=temp;}

We now compile and run the code (assuming you have the g++ compiler):

g++ -o PassByReference PassByReference.cpp./PassByReferenceIllustration of Pass By Reference:Before: i=1000 j=2300After: i=2300 j=1000

Illustration of Pass By Value:Before: i=1100 j=2500After: i=1100 j=2500

The results above perfectly illustrate the difference between passing by reference vas pass-by-value, at least from the C++ point of view.
By using the reference operator &, when the value of i is passed to the swapIntByReffunction, the actual parameter value is modified in the function such that when the function returns back to the main() function that calls it and the values of i and j are printed out, the values of i and j have been swapped.

In the latter case of pass-by-value, copies of i and j are passed, not references via the & operator.
The result of this is that even though an attempt is made to swap the values in theswapIntByVal function, the original actual parameter values remain unchanged, and this is what we see in the result.

The latter case is what prevails in Java even for all cases, even in the case of objects.

Here is an illustration in Java for both primitives and object references:

Create the file PassByValueDemo.java:

public class PassByValueDemo {

 public static void main(String[] args) {int i=1000;int j=2300;System.out.println("Primitives Case");System.out.println("----------------");System.out.println(" Before: i=" + i + " j=" + j);swapInt(i,j); System.out.println(" After: i=" + i + " j=" + j + "\n"); System.out.println("Wrapper Case");System.out.println("--------------");Integer iw=1000;Integer jw=2300;System.out.println(" Before: iw=" + iw + " jw=" + jw);swapInteger(iw,jw); System.out.println(" After: iw=" + iw + " jw=" + jw); } static void swapInt(int iParam, int jParam){int temp=jParam;jParam=iParam;iParam=temp;System.out.println(" iParam=" + iParam + " jParam=" + jParam); } static void swapInteger(Integer iParam, Integer jParam){Integer temp=jParam;jParam=iParam;iParam=temp;System.out.println(" iParam=" + iParam + " jParam=" + jParam);} 

}

We now compile and run the code:

javac PassByValueDemo.java

java PassByValueDemo

which produces:

Primitives Case----------------Before: i=1000 j=2300iParam=2300 jParam=1000After: i=1000 j=2300

Wrapper Case--------------Before: iw=1000 jw=2300iParam=2300 jParam=1000After: iw=1000 jw=2300
Thus we can see that in both cases of primitive and wrapper classes the values of the actual parameters i and j remain unchanged in the calling routine main. There is no way to achieve the effect we observed in the C++ method PassByRef in Java where the original actual parameters are changed. The underlying object that the reference refers to can be changed via a call to a modifying method on the referenced object, but the reference parameter is always a copy of the original actual parameter.

## Summary

• C++ supports pass-by-value and pass by reference via its & operator.
• Java supports pass-by-value ONLY. What is erroneously thought of as pass-by-reference is really pass-by-value of an object reference.
Last Updated on Tuesday, 29 April 2014 06:39

 Math Finance Series : Annuity PV
Written by FemiByte
Tuesday, 26 June 2012 04:12

## Present Value of an Annuity

An annuity is an investment product that is designed to pay out a series of payments to an investor at a certain point in time. Annuities are mainly used to secure a cash flow for an investor during their retirement years. In order to calculate the present value of an annuity over $n$ years, we can consider the sum of present values of the individual cash flows which are paid out as level payments $c$. This is given by:

$PV = \frac{c}{(1+r)} + \frac{c}{(1+r)^2} + \frac{c}{(1+r)^3} + \cdots + \frac{c}{(1+r)^n}$

How can we derive a closed-end formula for the above expression? To do that, let us consider the following sum of a geometric series:

$S = 1 + a + a^2 + a^3 + \cdots + a^{n-1} (i)$

where $a < 1$

Multiplying the above by $a$ we get:

$aS = a + a^2 + a^3 + a^4 + \cdots + a^n (ii)$

Let's do the math and subtract ii from i:

$(1-a)S=1-a^n$

since the intervening terms cancel themselves out.

Hence $S = \frac{1-a^n}{1-a}$

and

$aS = \frac{a(1-a^n)}{1-a}$

Let us use the formula for $aS$ above to derive the closed form of our annuity fomula as follows:

Comparing with our formula for $aS$ above, replacing $\frac{1}{1+r}$ by $a$ we get

$PV = c(a + a^2 +a^3 + \cdots +a^n) = c\frac{a(1-a^n)}{1-a}$

If we replace $a$ by $\frac{1}{1+r}$ we get

$PV = c \left[\frac{1}{1+r} + \frac{1}{(1+r)^2} + \frac{1}{(1+r)^3} + \cdots + \frac{1}{(1+r)^n} \right]$

$= \frac{c}{1+r} \left[\frac{1-\frac{1}{(1+r)^n}}{1-\frac{1}{1+r}}\right]$

which upon simplifying becomes

$PV = \frac{c}{r}\left[1 - \frac{1}{(1+r)^n}\right]$

giving us the formula for the PV of an annuity.

Last Updated on Wednesday, 27 June 2012 04:52

 Written by FemiByte Friday, 25 December 2009 05:37 The focus of our latest series of articles is on Design patterns in Technology and fundamental fixed income concepts in Finance. This allows us to lay the groundwork for a series on the open source finance software framework known as Quantlib written in C++ as well as it's Java port JQuantlib, of which Next Matrix Solutions is a participating developer.

 Review : "Middleware Vendors Hold the Key to Integration Strategies"
 Written by FemiByte Friday, 08 January 2010 02:48 Wall Street and Technology: Middleware Vendors Hold the Key to Integration Strategies This article provides a brief synopsis of the state of middleware in the financial services industry. It defines middleware as 'synonymous' with EAI (enterprise application integration), stating it as vital to achieving STP or achieving T+1 (1-day) settlement. Last Updated on Friday, 08 January 2010 12:18 Read more...

 Risk Management Certification
 Written by FemiByte Tuesday, 05 January 2010 03:23 There are quite a few organizations for professionals involved in risk management, other than universities that offer courses and train individuals. The 2 most internationally recognized organizations are: GARP - Global Association of Risk Professionals PRMIA- Professional Risk Managers Association The GARP offers membership, certification exams for Financial Risk Manager, Energy Risk Professional, training services, online resources, an online community and an online career center.

More Articles...
«StartPrev123NextEnd»

Page 1 of 3

### Polls

Joomla! is used for?
 Community Sites Public Brand Sites eCommerce Blogs Intranets Photo and Media Sites All of the Above!

### Who's Online

We have 100 guests online