Monday, 26 January 2015

Primitive Data Types are Passed to Methods by Value in Java

I created a class called my_class with a method called times_two. The method accepts an integer and multiplies it by 2:

Java > cat my_class.java
public class my_class
  {
  public void times_two(int a)
    {
    a = a * 2;
    System.out.println("a = " + a);
    }
  }
Java > javac my_class.java
Java >

I created a program called test_my_class. This sets up an instance of my_class called b. It then creates an integer variable called x and gives it a values of 2. Next, it passes x as a parameter to the times_two method, which multiplies it by 2 to give 4. Finally, it displays the original value, which is still 2. This is because the value of x is passed to the method, not a reference to its location in memory.

Java > cat test_my_class.java
public class test_my_class
  {
  public static void main(String args[])
    {
    my_class b = new my_class();
    int x = 2;
    b.times_two(x);
    System.out.println("x = " + x);
    }
  }
Java > javac test_my_class.java
Java > java test_my_class
a = 4
x = 2
Java >