Week 6, Notes 2 Characters

Scope review:

Scope rules are how the compiler determines which variable you mean when you mention a variable name.

In what part of the code is a variable name valid?

Method calls:

What does it mean to call a method?

What kind of error does the compiler give if you try to call a method using the correct name, but incorrect parameters?

 

Note: Lab 6 Method signatures use the type long instead of the type int

 

Characters

One of the primitive types, char,  has values that represent characters.  All primitive types can be assigned literal values, e.g.,

int i = 5;

long l = -59;

double d = 5.0;

char c = 'z';

boolean b = false;

Examples of char literals

‘A’, ‘a’, ‘0’, ‘\t’ (tab) ‘\n’ (newline)

 

Caution: Please avoid using \n in code graded by the autograder, it causes problems, though it is perfectly fine in general.

Operations

Characters may be concatenated to strings, e.g., "Hello" + '\n', concatenates the newline character onto the string "Hello".

Characters may not be concatenated with each other, e.g., 'A' + 'A' will not compile.

Represented as Integers

Values of type char are represented in memory as integers.  The integer stored for each character is given in the ASCII character code table, so, e.g.,

 

The character 'A' is represented in memory as the int 65

 

A value of type char can be viewed either as a char or as the underlying int that represents this char using the cast operator.

Cast operator

open-parenthesis type-name close-parenthesis, e.g., (int)

The operator is a unary right to left associative operator that applies to the thing that follows it.

E.g,

char c = 'a';

int ic = (int) c;

 

int i = 97;

char c = (char) i;

 

 

See ../demos/W06N03.java