Monday, 9 September 2013

Java passed by value: Can primitive value be passed by reference?

Java passed by value: Can primitive value be passed by reference?

class Test{
int a,b;
void change(int i, int j){
a = i*i;
b = j*j;
}
}
class newTest{
public static void main(String args[]){
Test ob = new Test ();
ob.a = 10;
ob.b = 5;
System.out.println("a and b before call:" +ob.a+" "+ob.b);
ob.change(ob.a,ob.b);
Sytem.out.println("a and b after call:"+ob.a+" "+ob.b);
)
)
So ob.a and ob.b will be passed as arguments and their values should be
passed as parameters. According to the passed by value concept they should
still be equal to 10 and 5 after the change method is used. Is that the
case? If ob.a and ob.b are considered objects that would ruin my example
but I don't think they are.
I am trying to create a situation where a primitive value would be called
by reference and in this case my thought process would lead me to believe
it would be called by reference but the rules state otherwise. Can a
primitive value be called by reference?
I apologize for not running the code myself but I am still figuring out
how to set that up on my computer.

No comments:

Post a Comment