0

Lets say I have a class as below:

public class class1{

   private int[] array1;

   public class1(){
      array1 = new int[10];
      }

   public int[] getArray(){
      return array1;
      }
}

If I create an instance of this class in another class or in main and use the getArray() method to assign the array to another variable in the upper class and then modify the values of the array there, will the original array values in the first class be modified also?

3
  • 4
    Why didn't you try this yourself? Commented Dec 8, 2012 at 8:29
  • Try and see.. :/ then you'll learn... Commented Dec 8, 2012 at 8:30
  • Yeah you guys are right. I get so caught up in trying to complete my projects perfectly I forget that I can always create a simple test class. Thanks. Commented Dec 9, 2012 at 5:12

2 Answers 2

2

will the original array values in the first class be modified also?

Yes it will be modified, because what you get in your caller, is not a copy of the array itself, rather you get a copy of the reference to the original array object.

And, if you modify the array using any reference, the change will be reflected for all the references pointing to the array.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. After playing around with the code a little, I realized that it doesn't work the same way if the original variable is an integer variable. From your explanation, I gather that there is a difference between passing a reference and a value. Is there a way to pass references of an integer variable of the first class to the calling class other than modifying it with traditional setter and getter methods?
@user1887413. Well, in Java everything is passed by value. So, if you pass an integer, its value is copied in the callie. So, the changes made will not be reflected in the caller. Now, you may think that you can use a Integer reference instead of primitive int, but in that case also, since Integer is immutable, anymodification done will create another Integer object, thus leaving the original object the same. So, no you can't do that. You will have to use setters to modify their value.
0

yes, the original array values will also be modified.

As you are returning the reference of the array from the method. The reference is nothing but a pointer to the address of the object. When you return it from the method, it is assigned to another reference. if you modify any thing using that reference, you are essentially modifying the same array i.e. the original array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.