Monday, September 16, 2013

Pass by Value and Pass Reference by Value

The basic of OOP(Object Oriented Programming) is to understand what is Object and Class.Simply in java programming object is a representation from a class that has a behavior and a state that can be assigned a value.A class is the blueprint from which individual objects are created.It's a little bit confusing for now if you haven't learnt them.You can read them at here as a reference

It might be at your school you got the lesson,but you still didn't understand so you're trying to look for it in the internet.I hope this post will help you understand it clearly.The best learning of programming is to try a example program and to figure it out.When i am studying about programming i always write a example program and think how the program works.


I choose to change Pass By Reference to be Pass Reference by value because it more makes sense.

First you have to know what is difference between primitive and reference

Primitives vs. References
  • primitive types are the basic types of data
    • byte, short, int, long, float, double, boolean, char
    • primitive variables store primitive values
  • reference types are any instantiable class as well as arrays
    • String, Scanner, Random, Die, int[], String[], etc.
    • reference variables store addresses

I will give you a simple example and i hope you can try to code it all.
try this following example :
public class PassByValue
{
    public void pass(int value)
    {
       value = 100;
       System.out.println("Passing Value : " + value );
    }

    public static void main(String[] args)
    {
       int value = 10;
       System.out.println("First Value : " + value );
       pass(value);
       System.out.println("After Passing : " + value );
    }
}
public class PassReferenceByValue
{
    public void pass(int[] value)
    {
       value[0] = 100;
       System.out.println("Passing by reference : " + value[0]");
    }

    public static void main(String[] args)
    {
       int[] value = new value[0];
       value[0] = 10;
       System.out.println("First Value : " + value[0]");
       pass(value);
    }
}

When you run the code above you should understand what is difference between them.Variable integer value in class PassByValue will make no difference when the value is passed to pass method.How about PassReferenceByValue ? you can see the array value will be changed as the value has passed to pass method. "int value" is the basic types of data / primitive and "int[] value" is a reference data type.

If you have any question you can directly ask me here through comment.

No comments:

Post a Comment