Aug 2, 2012

Java - Parameter Passing By-Value and By-Reference

This post will explain on how to manipulate Java pass-by-reference and java pass by value.

ByReference.java

package com.fluxion.mrcos.test;

public class ByReference {
 private int x=100;
 public void setX(int pX){
  this.x=pX;
 }
 public int getX(){
  return this.x;
 }
}

ByValue.java

package com.fluxion.mrcos.test;
public class ByValue {

 public static void main(String[] args){
  int a=2,b=7;
  ByValue bValue = new ByValue();
  ByReference bRef = new ByReference();
  
  System.out.println("a="+a+"; b="+b);
  bValue.swapMe(a, b);
  System.out.println("a="+a+"; b="+b);
  
  System.out.println("================================");
  bRef.setX(500);
  System.out.println("By Reference X:"+bRef.getX());
  bValue.chanceObject(bRef);
  
  System.out.println("By Reference X:"+bRef.getX());
  
 }

 private void chanceObject(ByReference pByRef)
 {
  pByRef.setX(300); // change the value 
 }
 
 private void swapMe(int x, int y){
  int temp = x;
  y=x;
  x=temp;
 }
}

Output When Running ByValue.java

a=2; b=7
a=2; b=7
========
By Reference X:500
By Reference X:300

Coclusion/Observation

Java is works on both By-Value and By-Reference however this will defends on the use. Is you pass a data, Java will tricks the paramater as Pass By-Value(See swapMe function), however if you pass a Object, it will treat the parameter as pass By-Reference(See chanceObject function)

No comments: