CS255 Syllabus

### Working with ASCII code in Java

• Characters in a programming language

• Characters:

• Characters (a.k.a. character constants) are denoted using single quotes:

 ``` 'A' 'B' 'C' '1' '2' ... ```

• The type of a character is:

 ``` char ```

• The value of a character is:

 The value assigned by the ASCII code to that character

• Example:

• 'H':

 The data type of the character constant H is: char the value of the character constant H is: 7210 (or 01001000 in binary)

• Quiz 1:

• Consider the following program:

 ``` char c; c = 'H'; ```

Question:

 What is the bit pattern stored in the variable c ?

 ``` 01001000 ```

• Quiz 2:

• Consider the following program:

 ``` byte c; c = 72; ```

Question:

 What is the bit pattern stored in the variable c ?

 ``` 01001000 ```

• Note:

• The difference between:

 The character constant H that is represented by the binary pattern 01001000 The unsigned value 7210 that is represented by the same binary pattern 01001000

is:

 The data type !!! (Remember the Java compiler use the data type as context to interpret (= decode) the values !!!)

• Strings

• String:

 String = a sequence of characters

• Casting between character type and integer type

• In Java, we can cast between char and byte (or short or int) data types:

 ``` byte b; char c; b = (byte) c; // Casts character value in c to byte type c = (char) b; // Casts byte value in b to char type ```

• What happens in a cast operation between character data type and integer data type:

 The bit pattern is copied         The type is changed !!!

• Example 1:

 ``` char c; byte b; c = 'H'; // c contains: 01001000 type: char b = (byte) c; // b contains: 01001000 type: byte System.out.println(b); // Prints 72 // Because it's the decimal representation for // the 2's complement code 01001000 ```

Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac CastingChar1.java To run:          java CastingChar1

• Example 2:

 ``` char c; byte b; b = 72; // b contains: 01001000 type: byte c = (char) b; // c contains: 01001000 type: char System.out.println(c); // Prints 'H' // Because it's the symbol representation for // the ASCII code 01001000 ```

Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac CastingChar1.java To run:          java CastingChar1

• Quiz:

• What is the output of:

 ``` char c; byte b; c = 'H'; b = (byte) c; b++; c = (char) b; System.out.println( c ); // ??????? ```

 ``` I ```