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
Rany
a source
to share
6 answers
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 to share
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 to share