0

Basically, I would like to use Unicode symbols in my System.out.println lines, but these Unicode characters would need to be dynamically generated.

For example, take symbols U+2074, U+2075 and U+2076, which return, respectively, x^4, x^5 and x^6. To print them in Java I would use \u2074, \u2075 and \u2076, but what if I want to generate them based on another value (i.e. \u207x where x is a variable)?

If I were using PHP, i would use variable variables for this which would be extremely handy.

I even went as far as thinking about using a hack like saving u207 as a String, making my calculations on the value of x and appending this value to the string, but then there are issues introducing the \ symbol inside a string:

String unicodeBase = "u207";
// I do something to get a value for x
String unicodeChar = "u207" + x;
System.out.println("\unicodeChar");

If i do this, I get an illegal unicode escape error, which is expected. But then, if I escape the \ symbol, then the output is a string that is not processed:

System.out.println("\\unicodeChar");

This returns the string unicodeChar.

So, is it possible to dynamically generate Unicode characters in Java?

user1301428
  • 1,743
  • 3
  • 25
  • 57

1 Answers1

1

You can simply cast the codepoint value to a char:

(char)0x2070 + x

Note that you probably think about codepoint values in hex.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964