You can reassign to an existing variable, but to do that, you need to omit the type declaration; when you specify the type, you are declaring a new variable (albeit with the same name). That is:
while (i <= 10){
String superscript = "th";
if (i == 1){
superscript = "st";
}
System.out.println("the " + i + superscript +" element is: " + X);
i++;
}
... reassigns to the existing superscript variable. That being said, we can improve upon this a lot further by using a for-loop and also creating a subroutine for this formatting:
for (int i = 0; i < 10; i++) {
String element = arr[i];
System.out.println("the " + asOrdinal(i+1) + " element is: " + element);
}
... with a helper function "asOrdinal" defined like this:
private static String asOrdinal(int index) {
String suffix = "th";
int onesDigit = index % 10;
switch (onesDigit) {
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
return Integer.toString(index) + suffix;
}
Note that my default case above is somewhat redundant (the string was already initialized with this default), but is there to illustrate how "default" works in a switch statement. You could also use a "return" in each of the different cases instead of assigning to the same local variable. I generally prefer to use "return", since assigning to the same variable repeatedly is often a code smell (or, rather, it isn't "functional" style, which tends to be my preference). In short, as you can see from the many answers here, there are multiple different ways to do the same thing.
The key take away you should get is that:
// Outer scope
TypeOfVariable identifier [= initialization_expression1];
// Inner scope
{
TypeOfVariable identifier [= initialization_expression2];
// ... usage ...
}
... in the above, the inner usages of "identifier" are referencing the variable that was declared in the inner scope. This variable is in a different memory location from the one declared in the outer scope (though, if it is an object pointer, both can point to the same value if they have been assigned/initialized with the address of the same object).
By contrast:
// Outer scope
TypeOfVariable identifier [= initialization_expression1];
// Inner scope
{
identifier = expression2;
// ... usage ...
}
... in the above, the "=" statement is not initialization but assignment, and both variables in the inner and outer scope are the same (with the statement in the inner scope replacing/assigning its value).