Uel.Rose Uel.Rose - 1 month ago 7
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:

Problem.java
- my main project.

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

As you can see after I pass variable
account
to
GeAllDigits()
I immediately pass the values to String
AllDigits
(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
ThreeDigits
.

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();
proc.GetAllDigits(account);
AllDigits = proc.digits;

for(int x=0;x < (length-3);x++)
{
num += AllDigits.get(x);
}
proc.GetAllDigits(num);
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){
digits.clear();
for(int i =0; i < acc.length(); i++)
{
int j = Character.digit(acc.charAt(i), 10);
digits.add(Integer.toString(j));
}
}


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

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.

Comments