Computers store values in memory. Everything else is a convenience for our dumb human brains (and eyes). By default, in Java any textual output of those values is going to be in base10 (decimal).
A
is 65 in base10, and 101 in base8 (provided we're talking about a character set that preserves US-ASCII values).
When talking about literals in Java, by default they are interpreted as base10. To use an octal literal, you need to precede it by a 0
:
int a1 = 65; // literals are by default base10
int a2 = 0101; // an octal literal in Java is preceded by a 0
int a3 = 'A';
System.out.println(a1 == a2 && a2 == a3);
The above will output true
.
If you want to in your example, you can set n
via an octal literal or parse an octal String
to an int, you get the result you expect:
int n = 010; // octal literal equal to decimal 8
int a = 'A' + ('Y' - 'A' + n) % 26;
System.out.println(a);
System.out.println(Integer.toOctalString(a));
outputs:
71
107
You could also parse an octal String
for n
:
int n = Integer.valueOf("010", 8);
The issue you're really facing here is trying to do base8 math, but performing base10 arithmetic (and you left n
as decimal 8
):
int o = 101 + (131 - 101 + 8) % 26;
System.out.println(o);
System.out.println(Integer.toOctalString(o));
Java interprets those literals as base10 representations, and that most certainly will result in:
113
161
On the other hand, were you to use octal literals and do the same...
int o = 0101 + (0131 - 0101 + 010) % 26;
System.out.println(o);
System.out.println(Integer.toOctalString(o));
Outputs:
71
107