How to prevent changing the value of variable? The Next CEO of Stack OverflowIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?

Indicator light circuit

Are there any unintended negative consequences to allowing PCs to gain multiple levels at once in a short milestone-XP game?

Rotate a column

Is it possible to search for a directory/file combination?

Interfacing a button to MCU (and PC) with 50m long cable

Bold, vivid family

Anatomically Correct Strange Women In Ponds Distributing Swords

Is 'diverse range' a pleonastic phrase?

What's the best way to handle refactoring a big file?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Why do airplanes bank sharply to the right after air-to-air refueling?

What connection does MS Office have to Netscape Navigator?

In excess I'm lethal

What does "Its cash flow is deeply negative" mean?

Complex fractions

Elegant way to replace substring in a regex with optional groups in Python?

How to prevent changing the value of variable?

Is it professional to write unrelated content in an almost-empty email?

Can you replace a racial trait cantrip when leveling up?

How did the Bene Gesserit know how to make a Kwisatz Haderach?

If the heap is initialized for security, then why is the stack uninitialized?

Return the Closest Prime Number

Does it take more energy to get to Venus or to Mars?

Should I tutor a student who I know has cheated on their homework?



How to prevent changing the value of variable?



The Next CEO of Stack OverflowIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?How do I fix android.os.NetworkOnMainThreadException?










7















I am a beginner in java. When developing a program, I created an object with a constructor with variables as arguments. But when I change the value of the variable after creating the object, my object has the second value instead of the first one. I don't want my object to change the value. What do I do?



public class Person 

public Person(int[] arrayTest)
this.arrayTest = arrayTest;

public int[] getArray()
return this.arrayTest;

public boolean canHaveAsArray(int[] arrayTest)
return true;

private int[] arrayTest = new int[2];

public static void main(String[] args)
int[] array = new int[] 5, 10;
Person obj1 = new Person(array);
array[0] = 20;
System.out.println(Arrays.toString(obj1.getArray()));




My output should be [5, 10], but instead, I am getting [20,10]. I need to get [5,10] even when I change an element of the array as shown above. What should I do?










share|improve this question


























    7















    I am a beginner in java. When developing a program, I created an object with a constructor with variables as arguments. But when I change the value of the variable after creating the object, my object has the second value instead of the first one. I don't want my object to change the value. What do I do?



    public class Person 

    public Person(int[] arrayTest)
    this.arrayTest = arrayTest;

    public int[] getArray()
    return this.arrayTest;

    public boolean canHaveAsArray(int[] arrayTest)
    return true;

    private int[] arrayTest = new int[2];

    public static void main(String[] args)
    int[] array = new int[] 5, 10;
    Person obj1 = new Person(array);
    array[0] = 20;
    System.out.println(Arrays.toString(obj1.getArray()));




    My output should be [5, 10], but instead, I am getting [20,10]. I need to get [5,10] even when I change an element of the array as shown above. What should I do?










    share|improve this question
























      7












      7








      7








      I am a beginner in java. When developing a program, I created an object with a constructor with variables as arguments. But when I change the value of the variable after creating the object, my object has the second value instead of the first one. I don't want my object to change the value. What do I do?



      public class Person 

      public Person(int[] arrayTest)
      this.arrayTest = arrayTest;

      public int[] getArray()
      return this.arrayTest;

      public boolean canHaveAsArray(int[] arrayTest)
      return true;

      private int[] arrayTest = new int[2];

      public static void main(String[] args)
      int[] array = new int[] 5, 10;
      Person obj1 = new Person(array);
      array[0] = 20;
      System.out.println(Arrays.toString(obj1.getArray()));




      My output should be [5, 10], but instead, I am getting [20,10]. I need to get [5,10] even when I change an element of the array as shown above. What should I do?










      share|improve this question














      I am a beginner in java. When developing a program, I created an object with a constructor with variables as arguments. But when I change the value of the variable after creating the object, my object has the second value instead of the first one. I don't want my object to change the value. What do I do?



      public class Person 

      public Person(int[] arrayTest)
      this.arrayTest = arrayTest;

      public int[] getArray()
      return this.arrayTest;

      public boolean canHaveAsArray(int[] arrayTest)
      return true;

      private int[] arrayTest = new int[2];

      public static void main(String[] args)
      int[] array = new int[] 5, 10;
      Person obj1 = new Person(array);
      array[0] = 20;
      System.out.println(Arrays.toString(obj1.getArray()));




      My output should be [5, 10], but instead, I am getting [20,10]. I need to get [5,10] even when I change an element of the array as shown above. What should I do?







      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 1 hour ago









      OpheliaOphelia

      362




      362






















          2 Answers
          2






          active

          oldest

          votes


















          5














          Array is passed by reference in Java. If you pass the original array to the constructor of Person, you are just passing the reference to the original array and the changes in original array will reflect in Person instance.



          So if you don't want to change the value of array in Person so don't pass the original array, instead just send a copy of original array like below:



          Person obj1 = new Person(java.util.Arrays.copyOf(array, array.length));


          You can also modify the code in Person constructor to achieve the same results:



          public Person(int[] arrayTest) 
          this.arrayTest = java.util.Arrays.copyOf(arrayTest, arrayTest.length);






          share|improve this answer
































            3














            There is no such thing as immutable (unchangeable) array in Java. The Java language does not support this, and neither does the JVM. You can't solve this at the language level.



            In general, the only way to prevent changes to an array is to not share the reference to the array with other code that might change it.



            In your example, you have what is known as a leaky abstraction. You are passing an array to your Person class, and the caller is keeping a reference to that array so that it can change it. To solve this, you can:



            • copy the array, and pass a reference to the copy, or

            • have the constructor (or a setter for the array attribute) make the copy.

            (See answer https://stackoverflow.com/a/55428214/139985 for example code.)



            The second alternative is preferable from an OO perspective. The Person class should be responsible for preserving its own internal state from interference ... if that is your design requirement. It should not rely on the caller to do this. (Even if the caller is technically part of the same class as is the case here.)






            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55428172%2fhow-to-prevent-changing-the-value-of-variable%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5














              Array is passed by reference in Java. If you pass the original array to the constructor of Person, you are just passing the reference to the original array and the changes in original array will reflect in Person instance.



              So if you don't want to change the value of array in Person so don't pass the original array, instead just send a copy of original array like below:



              Person obj1 = new Person(java.util.Arrays.copyOf(array, array.length));


              You can also modify the code in Person constructor to achieve the same results:



              public Person(int[] arrayTest) 
              this.arrayTest = java.util.Arrays.copyOf(arrayTest, arrayTest.length);






              share|improve this answer





























                5














                Array is passed by reference in Java. If you pass the original array to the constructor of Person, you are just passing the reference to the original array and the changes in original array will reflect in Person instance.



                So if you don't want to change the value of array in Person so don't pass the original array, instead just send a copy of original array like below:



                Person obj1 = new Person(java.util.Arrays.copyOf(array, array.length));


                You can also modify the code in Person constructor to achieve the same results:



                public Person(int[] arrayTest) 
                this.arrayTest = java.util.Arrays.copyOf(arrayTest, arrayTest.length);






                share|improve this answer



























                  5












                  5








                  5







                  Array is passed by reference in Java. If you pass the original array to the constructor of Person, you are just passing the reference to the original array and the changes in original array will reflect in Person instance.



                  So if you don't want to change the value of array in Person so don't pass the original array, instead just send a copy of original array like below:



                  Person obj1 = new Person(java.util.Arrays.copyOf(array, array.length));


                  You can also modify the code in Person constructor to achieve the same results:



                  public Person(int[] arrayTest) 
                  this.arrayTest = java.util.Arrays.copyOf(arrayTest, arrayTest.length);






                  share|improve this answer















                  Array is passed by reference in Java. If you pass the original array to the constructor of Person, you are just passing the reference to the original array and the changes in original array will reflect in Person instance.



                  So if you don't want to change the value of array in Person so don't pass the original array, instead just send a copy of original array like below:



                  Person obj1 = new Person(java.util.Arrays.copyOf(array, array.length));


                  You can also modify the code in Person constructor to achieve the same results:



                  public Person(int[] arrayTest) 
                  this.arrayTest = java.util.Arrays.copyOf(arrayTest, arrayTest.length);







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 1 hour ago

























                  answered 1 hour ago









                  Aniket SahrawatAniket Sahrawat

                  6,32121339




                  6,32121339























                      3














                      There is no such thing as immutable (unchangeable) array in Java. The Java language does not support this, and neither does the JVM. You can't solve this at the language level.



                      In general, the only way to prevent changes to an array is to not share the reference to the array with other code that might change it.



                      In your example, you have what is known as a leaky abstraction. You are passing an array to your Person class, and the caller is keeping a reference to that array so that it can change it. To solve this, you can:



                      • copy the array, and pass a reference to the copy, or

                      • have the constructor (or a setter for the array attribute) make the copy.

                      (See answer https://stackoverflow.com/a/55428214/139985 for example code.)



                      The second alternative is preferable from an OO perspective. The Person class should be responsible for preserving its own internal state from interference ... if that is your design requirement. It should not rely on the caller to do this. (Even if the caller is technically part of the same class as is the case here.)






                      share|improve this answer





























                        3














                        There is no such thing as immutable (unchangeable) array in Java. The Java language does not support this, and neither does the JVM. You can't solve this at the language level.



                        In general, the only way to prevent changes to an array is to not share the reference to the array with other code that might change it.



                        In your example, you have what is known as a leaky abstraction. You are passing an array to your Person class, and the caller is keeping a reference to that array so that it can change it. To solve this, you can:



                        • copy the array, and pass a reference to the copy, or

                        • have the constructor (or a setter for the array attribute) make the copy.

                        (See answer https://stackoverflow.com/a/55428214/139985 for example code.)



                        The second alternative is preferable from an OO perspective. The Person class should be responsible for preserving its own internal state from interference ... if that is your design requirement. It should not rely on the caller to do this. (Even if the caller is technically part of the same class as is the case here.)






                        share|improve this answer



























                          3












                          3








                          3







                          There is no such thing as immutable (unchangeable) array in Java. The Java language does not support this, and neither does the JVM. You can't solve this at the language level.



                          In general, the only way to prevent changes to an array is to not share the reference to the array with other code that might change it.



                          In your example, you have what is known as a leaky abstraction. You are passing an array to your Person class, and the caller is keeping a reference to that array so that it can change it. To solve this, you can:



                          • copy the array, and pass a reference to the copy, or

                          • have the constructor (or a setter for the array attribute) make the copy.

                          (See answer https://stackoverflow.com/a/55428214/139985 for example code.)



                          The second alternative is preferable from an OO perspective. The Person class should be responsible for preserving its own internal state from interference ... if that is your design requirement. It should not rely on the caller to do this. (Even if the caller is technically part of the same class as is the case here.)






                          share|improve this answer















                          There is no such thing as immutable (unchangeable) array in Java. The Java language does not support this, and neither does the JVM. You can't solve this at the language level.



                          In general, the only way to prevent changes to an array is to not share the reference to the array with other code that might change it.



                          In your example, you have what is known as a leaky abstraction. You are passing an array to your Person class, and the caller is keeping a reference to that array so that it can change it. To solve this, you can:



                          • copy the array, and pass a reference to the copy, or

                          • have the constructor (or a setter for the array attribute) make the copy.

                          (See answer https://stackoverflow.com/a/55428214/139985 for example code.)



                          The second alternative is preferable from an OO perspective. The Person class should be responsible for preserving its own internal state from interference ... if that is your design requirement. It should not rely on the caller to do this. (Even if the caller is technically part of the same class as is the case here.)







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 38 mins ago

























                          answered 56 mins ago









                          Stephen CStephen C

                          525k72585944




                          525k72585944



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55428172%2fhow-to-prevent-changing-the-value-of-variable%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

                              Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

                              चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि