I am trying to write my own string reverse algorithm (I know this already exists in java but I am doing this for education). The code below is what I have so far. It outputs only half the string reversed. I have done some debugging and the reason is that it is changing stringChars2 at the same time as stringChars but I have no idea why that is happening as I am only trying to change stringChars. All help greatly appreciated.
EDIT my question was not "how to reverse a string" which has been asked before... but why my objects where changing without instruction, the answer below completely explains the problem.
public static void main(String[] args) {
//declare variables
Scanner input = new Scanner(System.in);
String myString = "";
int length = 0, index = 0, index2 = 0;
//get input string
System.out.print("Enter the string you want to reverse: ");
myString = input.next();
//find length of string
length = myString.length()-1;
index2 = length;
//convert to array
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
//loop through and reverse order
while (index<length) {
stringChars[index] = stringChars2[index2];
index++;
index2--;
}
//convert back to string
String newString = new String(stringChars);
//output result
System.out.println(newString);
//close resources
input.close();
}