0

Lately, I have been learning java and was coding the problem of finding the greatest number having the same digit as per given input(String input). The problem demanded a swap function.Below is the code.

swap(c,5,4); //c is my character array.5 and 4 are the integers whose characters are to be replaced

public static void swap(char demo[],int x,int y) 
/*the function defined in the same class where function is declared */
    {
        char temp=[x];
        demo[x]=demo[y];
        demo[y]=temp;
    }

My query :

1) I am aware of the fact that in java pointers are no there unlike C/C++, but I am in doubt then why did my characters at 4 and 5 got swapped in my original array c since in C/C++ pointers were helping to modify the original array.I am unable to understand how java deals with it?

2) Like in C/C++, when you return back from function definition, the temporary variables get erased.Isn't this the case with java because had it been coded in c/c++, my above code wouldn't have swapped my original array until I send references.

I am a naive, and have searched it here but couldn't find the answer to this.I would be grateful if I get a little insight on this.

Rishu
  • 47
  • 1
  • 1
  • 10

1 Answers1

0

demo is a reference type variable. It holds the value of a reference.

Both the caller of the method and the method itself have a reference to a char[] instance. The method uses that reference to locate the object and change it, ie. swap two elements.

When the method returns, the caller still has a reference to that same object and therefore can see the changes within that object.

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683