Why can't you change the value of a variable of a primitive type?

    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 isn't c changed?

-1


a source to share


6 answers


Java is strictly pass-by-value



+5


a source


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

For primitive type - c in your case - value is value c, so you use a copy of value 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 refers to the same object and you can modify the object using your copy of the reference ...

+4


a source


Because primitive parameters are passed by value to the method and therefore the value you are modifying is local to the method.

You probably want

c = thistest.getA()

      

where getA()

returns the value of a.

+2


a source


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

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

0


a source


Primitive data types are passed by value, not by reference, which means that c you get "trytoequal" - this is a variable that is only scoped inside the method, and its value is a copy of the method parameter.

0


a source


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

0


a source







All Articles