Java parameter passing method? By reference or by value?

Java is strictly Pass By Value !

Pass by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments are always passed by value whether its Java primitive types or Java Objects. In the case of Java Objects, Java copies and passes the reference by value, not the object.

Sample Java code to TEST java parameter passing

package com.as400samplecode;

import java.awt.Point;

public class ParameterTest {

 public static void main(String[] args)
 {

  int myVariable1 = 100;
  int myVariable2 = 200;
  SimpleTest(myVariable1,myVariable2);
  System.out.println("Variable1: " + myVariable1);
  System.out.println("Variable2: " + myVariable2);

  Point pointA = new Point(100,100);
  Point pointB = new Point(200,200);
  System.out.println("AX: " + pointA.x + " AY: " +pointA.y); 
  System.out.println("BX: " + pointB.x + " BY: " +pointB.y);
  ObjectTest(pointA,pointB);
  System.out.println("AX: " + pointA.x + " AY: " +pointA.y); 
  System.out.println("BX: " + pointB.x + " BY: " +pointB.y);
 }


 private static void SimpleTest(int variable1, int variable2)
 {
  int myVariable = variable1;
  variable1 = variable2;
  variable2 = myVariable;
 }

 private static void ObjectTest(Point pointA, Point pointB)
 {
  pointA.x = 500;
  pointA.y = 500;
  Point myPoint = pointA;
  pointA = pointB;
  pointB = myPoint;
 }

}

Results from the above Java Program

Variable1: 100
Variable2: 200
AX: 100 AY: 100
BX: 200 BY: 200
AX: 500 AY: 500
BX: 200 BY: 200

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.