Uel.Rose Uel.Rose - 1 year ago 45
Java Question

Value of a variable pass from method overwrite when method call again - Java

I'm a student and currently learning java,
As what I know in java, it read codes from top to bottom, but how my program behave confuse me.
This not the my complete program I just created a simpler program just to emphasize the part that I don't understand. I had two projects:

- my main project.

- contain many public void methods, I just create this to reuse a set of codes. Example:
- this is to get every digits/char of a String and store inside an ArrayList.

As you can see after I pass variable
I immediately pass the values to String
(this is to save the first result. I did this because I know i will call the method again and will have an another result).Then I store the second result inside variable

So my expected output would be:

All Digits: [2, 0, 1, 0, 0, 5]

Three Digits: [2, 0, 1]

But instead I get

All Digits: [2, 0, 1]

Three Digits: [2, 0, 1]

String account = "201005";
ArrayList<String> AllDigits = new ArrayList<>();
ArrayList<String> ThreeDigits = new ArrayList<>();
String num = new String();

Public Problem()
{ int length = account.length();
Procedures proc = new Procedures();
AllDigits = proc.digits;

for(int x=0;x < (length-3);x++)
num += AllDigits.get(x);
ThreeDigits = proc.digits;

System.out.println("All Digits: " + AllDigits.toString());
System.out.println("Three Digits: " + ThreeDigits.toString());

public static void main(String[] args) {
new Problem();

this is what Procedures.java looks like:

public ArryList<String> digits = new ArrayList<>();

public void OddEvenDigits(String number)

public void GetAllDigits(String acc){
for(int i =0; i < acc.length(); i++)
int j = Character.digit(acc.charAt(i), 10);

Sorry if my post is kind of long for this simple problem. Any answer is greatly appreciated, and if any site/books that you can refer to me for my learning would be awesome!

Answer Source

You are getting
All Digits: [2, 0, 1] Three Digits: [2, 0, 1] because you call GetAllDigits from same proc object.
In java an object can have multiple references so each time you call GetAllDigits from same proc object this change is reflected in all references that's why Alldigits and Threedigits are same
To get the required values call GetAllDigitsfrom a new procobject.