5 Replies Latest reply on May 10, 2007 4:21 AM by 807599

    Newbie Array Question

      I am sure this has been asked before, but can anyone tell me why this code creates two identical arrays.
      int[] test = {1, 2, 3};
      int[] tempTest = test;
      test[0] =5;
      test = tempTest;
      Now, I would think that test would return to its initial value because it is stored in tempTest but that is not the case both arrays are containing the new value of 5 in position 0.
        • 1. Re: Newbie Array Question
          temp and tempTest are variables not arrays. They store references (or pointers) to the same array. Therefore there is only only array so any changes you make is reflected by the two variables because they both refer to the same array.
          • 2. Re: Newbie Array Question
            You should also try changing a value in one of the positions of the second array. Are the changes reflected again?
            • 3. Re: Newbie Array Question
              Yep, if I change a value in the second array it is reflected in the first. I figured it had to do with them being just pointers. Thanks for the help. I guess one more question to add to this would be is there any way to set them equal with a one line command, or is the only way a type of loop to set each positions equal.

              Message was edited by:
              • 4. Object assignment
                Read a basic tutorial of java,

                When you assign a reference of object to other variable of type object, you are actually assigning a reference, it will neither create a new object nor copy existing object, both variable will point to same object,


                Car c1 = new Car();
                Cac c2 ;
                c2 = c1; // both c1 and c2 referes to same inmemory representation of car

                //if you make any change in c2, tht changes will be reflected on c1 also, coz both referes to same object

                if (c1 == c2) {
                System.out.println ("both are same");
                else {
                System.out.println ("Different");

                • 5. Re: Object assignment
                  Thanks for that Sudhir but they already understood.

                  Thanks also for pimping your website!