-1

while learning C language I have learned that when you pass a variable to a function. you are not passing the variable itself you are passing a copy of it so the actual varible's value will not change unless the function returns a value and you assign that value to the variable. but I just executed this program and this happened when I passed "Newobj" object to a "changer" function and then change the values of the variables and then print the new variables values it is working. It should not happen right? because I am sending the copy of "Newobj" to "copyobj". explain please I am confused.

Note: Explain in detail please. My brain is slow. I know the concepts of c and few concepts of c++;

here is my code:

public class PassObjects {
int regno;
String name;
double per;

PassObjects(int a,String s,double p){
    regno=a;
    name=s;
    per=p;
}
PassObjects changer (PassObjects copyobj){
    copyobj.regno=797;
    copyobj.name="Srimanth";
    copyobj.per=70.9;
    return copyobj;

}

public static void main(String[] args){

    PassObjects Newobj= new PassObjects(86,"srimanth",85.4);
    System.out.println("The original values of Instance variables are "+Newobj.regno+" "+Newobj.name+" "+Newobj.per);
    Newobj.changer(Newobj);
    System.out.println("The changeed values of Newobj are "+Newobj.regno+" "+Newobj.name+" "+Newobj.per);
}

}

output is here:

The original values of Instance variables are 86 srimanth 85.4
The changeed values of Newobj are 797 Srimanth 70.9
Srimanth
  • 1,042
  • 8
  • 13

2 Answers2

0

What you are doing is passing a pointer to an object. You are effectively modifying the PassObjects object.

There is a difference between a reference type and a value type. For example, a function that takes an integer and modifies it will indeed receive a copy of that integer.

public void add(int x)
{
    x = x + 1;
}

However, an array of ints is also a reference type.

When you call this function using the following code:

int x = 5;
add(x);
// X will still have a value of 5.

This is because x is a value-type. You call the function and pass in a copy of the integer.

However, when you create an object, you do not pass a copy of the entire object. See code below.

public void ChangeName(SomeObject x, String newname)
{
    x.name = newname;
}

SomeObject x = new SomeObject("thename");
ChangeNameTo(x, "newname"); // As the comment below pointed out, you don't even have to reassign.
//x.name will have the value "newname" now.

You can read more here and here.

Community
  • 1
  • 1
Christophe De Troyer
  • 2,852
  • 3
  • 30
  • 47
0

Java does manipulate objects by reference, and all object variables are references.

That means u only created a new reference to the same object and when u changed the values then it gets changed in actual object.

kirti
  • 4,499
  • 4
  • 31
  • 60