Lets see how your code works:
for (int i = 0; i<25; i++) { //1
for (int j=65; j<91; j++) { //2
tab[i] = (char)j; //3
} //4
} //5
1) Outer loop sets i=0
,
2) Inner loop sets j=65
3) (char)65
represents 'A'
ant is placed in tab[0]
2) Inner loop sets j=66
3) (char)66
represents 'B'
and is also placed in tab[0]
Here you should notice the problem, which is that inner loop is working on same i
, so while iterating over A...Z it is modifying same array location, which means that location will hold last value placed there, which is 'Z'
.
(BTW i<25
should be i<26
)
Possible solution
don't use inner loop, you can calculate value which should be placed at index by adding i
to 65
which in Unicode Table is codepoint of 'A'
for (int i=0; i<26; i++)
tab[i] = (char)(65+i);
BTW you can farther improve readability of this code by avoiding magic numbers (more info: What is a magic number, and why is it bad?). So this code can be rewritten into something like:
int amountOfLetters = 'Z' - 'A' + 1;
char[] tab = new char[amountOfLetters];
int i = 0;
for (char ch = 'A'; ch <= 'Z'; ch++) {
tab[i++] = ch;
}
System.out.println(new String(tab));