tags:

views:

115

answers:

6
    public class testtype
{
  private   int a;
  private double b;

   testtype(int a,double b)
  {
    this.a=a;
    this.b=b;
  }

  public void maketoequal(testtype oo)
  {
    oo.a=this.a;
    oo.b=this.b;
  }

  void trytoequal(int c)
  {
    c=this.a;
  }

  public static void main(String[] args)
  {
    testtype t1,t2;
    t1=new testtype(10,15.0);
    t2=new testtype(5,100.0);
    t1.maketoequal(t2);
    System.out.println("after the method is called:"+"\n"+"the value of a for t2 is:"+t2.a
    +"\n"+"the value of b for t2 is :"+t2.b);
    int c=50;
    t1.trytoequal(c);
    System.out.println("the value of c after the method be called is:"+c);
  }
}

why the c is not changed?

+1  A: 

Because primitive parameters are passed by value to the method, and so the value you change is local to the method.

You probably want

c = thistest.getA()

where getA() returns the value of a.

Brian Agnew
A: 

In java, parameters are passed by value, not by reference, so what you are doing in "trytoequal" won't work.

See these explanations on java variables value: http://www.yoda.arachsys.com/java/passing.html

ckarmann
+5  A: 

Java is strictly pass-by-value

jonny
A: 

Primitive datatypes are passed by value and not by reference, meaning that the c you get in "trytoequal" is a variable whose scope is just within the method and its value is a copy of the method parameter.

Kim L
+3  A: 

Java passes parameters by value (so a copy of the value is made and used locally in the method).

For a primitive type -- c in your case --, the value is the value of c, so your using a copy of the value of c and you don't change c

For an object the value is the value of the reference so even if you pass it by value (copy it) it still references the same object and you can change the object using your copy of the reference...

pgras
A: 

The value of c in the method is changed, and then discarded.

Peter Lawrey