#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    208
    Rep Power
    13

    Variable scope question


    Hi,

    I don't understand why it won't update the value of x in the below code but it updates the name of the Employee object e. Please explain. Thanks.

    VariableScopeTest.java
    Code:
    public class VariableScopeTest
    {
       public static void main(String[] args)
       {
    	   int x = 0;
    	   Functions.updateValueOf(x);
    	   System.out.println(x);
    
    	   Employee e = new Employee();
    	   Functions.updateNameOf(e);
    	   System.out.println(e.getName());
       }
    }
    Employee.java
    Code:
    public class Employee
    {
    	private String name_;
    
    	Employee()
    	{
    		name_ = "foo";
    	}
    
    	public String getName()
    	{
    		return name_;
    	}
    
    	public void setName(String name)
    	{
    		name_ = name;
    	}
    }
    Functions.java
    Code:
    public class Functions
    {
    	public static void updateNameOf(Employee e)
    	{
    		e.setName("Alexandra");
    	}
    
    	public static void updateValueOf(int x)
    	{
    		x = 3;
            }
    }
    Last edited by soap; October 22nd, 2013 at 09:19 AM.
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    All parameter passing in Java is by value.

    For primitives, this means the value of the actual parameter is copied into the formal parameter in the method.

    For object references, this means the value of the reference is copied so that the formal parameter becomes an alias to the object referred to by the actual parameter.

    Therefore, there is no way to change the value of a primitive by sending it as a parameter, but you can can change the contents of an object by sending a reference to it to the method and having that method use the reference.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    208
    Rep Power
    13
    Thanks for your explanation.

IMN logo majestic logo threadwatch logo seochat tools logo