Character codes: Difference between revisions

(Add lang example)
Line 1,182:
 
=={{header|Java}}==
In Java, a <code>char</code> is a 2-byte unsigned value, so it will fit within an 4-byte <code>int</code>.<br />
<tt>char</tt> is already an integer type in Java, and it gets automatically promoted to <tt>int</tt>. So you can use a character where you would otherwise use an integer. Conversely, you can use an integer where you would normally use a character, except you may need to cast it, as <tt>char</tt> is smaller.
<br />
To convert a character to it's ASCII code, cast the <code>char</code> to an <code>int</code>.<br />
The following will yield <kbd>97</kbd>.
<syntaxhighlight lang="java">public class Foo {
(int) 'a'
}</syntaxhighlight>
You could also specify a unicode hexadecimal value, using the <kbd>\u</kbd> escape sequence.
<syntaxhighlight lang="java">public class Bar {
(int) '\u0061'
}</syntaxhighlight>
To convert an ASCII code to it's ASCII representation, cast the <code>int</code> value to a <code>char</code>.
<syntaxhighlight lang="java">
(char) 97
</syntaxhighlight>
<br />
Java also offers the <code>Character</code> class, comprised of several utilities for Unicode based operations.<br />
Here are a few examples.<br /><br />
Get the integer value represented by the ASCII character.<br />
The second parameter here, is the radix.
This will return an <code>int</code> with the value of <kbd>1</kbd>.
<syntaxhighlight lang="java">
Character.digit('1', 10)
</syntaxhighlight>
Inversely, get the ASCII representation of the integer.<br />
Again, the second parameter is the radix.
This will return a <code>char</code> with the value of '<kbd>1</kbd>'.
<syntaxhighlight lang="java">
Character.forDigit(1, 10)
</syntaxhighlight>
 
In this case, the <tt>println</tt> method is overloaded to handle integer (outputs the decimal representation) and character (outputs just the character) types differently, so we need to cast it in both cases.
<syntaxhighlight lang="java">public class Foo {
public static void main(String[] args) {
System.out.println((int)'a'); // prints "97"
System.out.println((char)97); // prints "a"
}
}</syntaxhighlight>
Java characters support Unicode:
<syntaxhighlight lang="java">public class Bar {
public static void main(String[] args) {
System.out.println((int)'π'); // prints "960"
System.out.println((char)960); // prints "π"
}
}</syntaxhighlight>
=={{header|JavaScript}}==
Here character is just a string of length 1
118

edits