Generate random character in java?

  • Character in java ranges from 0000-FFFF (hexa)

  • Each character corresponds to an integer value.

So, I use this formula to generate a random integer between 0 to FFFF.

randInt = (int) (Math.random() * (65535 + 1));

I get correct stuffs.

Say I get 4451

Now, I want to parse this integer to its unicode character.

randChar = (char)(randInt);

What I do is type cast randInt into randChar which is declared as char.

I'm always getting "?" as a string. (Probably because the generated values don't fit into a single character)...However, I want to get its unicode character, how do I do it? Or what I am trying is possible?

Google search says:

var stringVar = String.fromCharCode(randInt);

ChatGPT says:

To parse an integer to a Unicode character in JavaScript, you can use the String.fromCharCode() method, which converts the integer value (representing a Unicode code point) into its corresponding character. Here's an example:

const codePoint = 65; // Example: 65 is the Unicode code point for 'A'
const character = String.fromCharCode(codePoint);

console.log(character); // Output: 'A'

If you're working with code points outside the Basic Multilingual Plane (BMP), which are represented by values greater than 0xFFFF, you should use String.fromCodePoint() instead:

const codePoint = 128512; // Example: 128512 is the Unicode code point for the '😀' emoji
const character = String.fromCodePoint(codePoint);

console.log(character); // Output: '😀'

String.fromCodePoint() is more versatile and supports all valid Unicode code points.

Reference:

ChatGPT: parse integer to unicode character using javascript

Again, this question is easily answered in less than 1 minute on the net.

Search before asking questions, please. Do your own homework before asking others for help.

See Also: