We will study how characters in text are represented inside a computer next
Remember the importance of context:
|
The context of is given (provided) by the data type:
int x; // Tells the compiler to use 2s compl code float y; // Tells the compiler to use IEEE 754 code char c; // Tells the compiler to use ASCII code |
The variable will contain (= store) the code (= data).
This code (= data) is interpreted using the data type (context) to obtain the meaning (= information)
Computers today uses the ASCII code to represent English text:
|
The string compare method compareTo( ) of Java (and any programming language) uses the fact that code(A) < code(B) < ... < code(Z) < code(a) < code(b) < ... < code(z)
When you compare 2 strings, the computer program will compare (= subtract) the character codes individually:
"ABC".compareTo("ABXY"): (1) compares (subtract) code(A) in "ABC" with code(A) in "ABXY" (2) compares (subtract) code(B) in "ABC" with code(B) in "ABXY" (3) compares (subtract) code(C) in "ABC" with code(X) in "ABXY" and so on, until one of <, == or > relationship is determined |
(1) because code(A) in "ABC" == code(A) in "ABXY", we continue with the comparison
(2) because code(B) in "ABC" == code(B) in "ABXY", we continue with the comparison
(3) because code(C) in "ABC" < code(X) in "ABXY", we determine that: "ABC" < "ABXY"
A tool by Mathias I found on the web:
|
Type in:
012, ABC, abc
What is:
code(2)-code(0) ? Is
code(A) < code(B) ?)
Perform
binary arithmetic on the
codes to find the
answer
Important fact that you must keep remembering (especially in CS255):
|
Important consequence: a program can perform computations (= calculate) with the ASCII code as it they are "ordinary" (integer) binary numbers !!!
You can calculate (e.g.: + 1) using the ASCII codes (= binary number) store in char type variables:
char c = 'A'; c = (char) (c + 1); // type of c+1 is int // So we need casting // to assign back to c System.out.println(c); // What will this statement print ? |
Question: what character is in the variable c after the increment ?
The DEMO program is here: /home/cs255001/demo/ASCII-code/ascii.java