5

So I'm making a basic GUI with the NetBeans IDE (in Java), and I want to make a button with a √ sign in it. It didn't let me copypaste it in, so I tried using its ASCII code - char sqrt = (char) 251. Instead of the square root sign, however, it gave me "û", and I have no idea why. Can someone please explain why this is happening, as well as offer an idea as to how I should go about this?

2 Answers 2

4

Java characters are Unicode, not ASCII. Unicode codepoint 251 (U+00FB) is "Latin Small Letter U with Circumflex". To make input of various Unicode characters using a character set with only the basic ASCII symbols, Java provides a way to input Unicode characters using a literal format. So, you can do this:

char sqrt = '\u221a';

since U+221A is the Unicode codepoint for the square root symbol.

This \uXXXX format can also be used in String literals:

String s = "The square root of 2 (\u221a2) is approximately 1.4142";

If you print that String, you will see

The square root of 2 (√2) is 1.4142
2
  • But how come this works (when I have it just by itself): char sqrt = (char) 251; System.out.println(sqrt);? At least it works when I compile it from the command line :o
    – Bluefire
    Aug 16, 2012 at 20:34
  • My guess is that you're using Windows using a default file encoding of CP437, which maps the square root glyph to 0xFB (251), and so when the int with value 251 is being cast to a char, it sees that the character with codepoint 0xFB in the CP437 code page is the square root symbol, and uses that.
    – joev
    Aug 16, 2012 at 20:51
3

Java uses Unicode, and the Unicode value for '√' is 8730. So, this should do it:

char sqrt = 8730;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.