# Strings and Characters

Source: https://cca.twango.dev/AP-Computer-Science/strings-and-characters

# Strings and Characters

## `String` and `char`

A double-quoted literal is a string; a single-quoted literal is a character. These original examples intentionally fail:

```java
char myChar = "A";    // Error: String is not char.
String myString = 'A'; // Error: char is not String.
```

Use `charAt(index)` to obtain one UTF-16 code unit from a string:

```java
char myChar = "A".charAt(0);
String myString = "" + 'C'; // "C"
```

## `int` and `char`

```java
int code = 'A';            // 65
char letter = (char) 65;   // 'A'
```

> [!note] Review clarification
> `char` holds a UTF-16 code unit from 0 to 65,535. An explicit cast from an out-of-range `int` still compiles and keeps the low 16 bits. Some Unicode characters require two `char` values.

Source: [Java types §4.2.1](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.2.1).

## String constant pool

Equal string literals share an interned string object. Variable names do not determine this sharing.

```java
String first = "Hello";
String second = "Hello";
String third = new String("Hello");

System.out.println(first == second);     // true
System.out.println(first == third);      // false
System.out.println(first.equals(third)); // true
```

> [!warning] Correction to the original notes
> The pool contains string objects, not variables. Sharing depends on the literal's contents, rather than declaring another variable with the same name. `new String(...)` creates a distinct object; `.equals(...)` still compares its text.

Sources: [String literals §3.10.5](https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.10.5), [String API](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html).

Related: [[logical-operators|Equality]] · [[introduction-to-java|String methods]]
