24sp ver.
Note: this is for the Spring 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.
Escape Sequences¶
| Sequence | Description | 
|---|---|
| \t | tab | 
| \n | new line | 
| \" | quotation mark | 
| \\ | backslash | 
Variables¶
containers (or boxes) that store values of a specific data type
| Variable Creation | Code Framework | Description | Example | 
|---|---|---|---|
| Declaration | <type> <name>; | creates a variable but doesn’t give it any value | int x; | 
| Initialization | <name> = <value>; | stores a value into a variable | x = 5; | 
| Declaration + Initialization | <type> <name> = <value>; | creates a variable and stores a value in it | int x = 5;int x = 3;( xhas the value3)int y = 1 + x * 2;( yhas the value7) | 
Variable Naming Rules & Conventions¶
- Case-Sensitive
- Starts with a letter, $, or_
- Can have letters, numbers, $, or_
- Generally, $, and_are not used
- Choose descriptive names
- Use “camelCasing”
Examples:¶
- age
- dogName
- numOfClasses
Strings¶
(Stores text)
Example
String name = "T. Swift";
System.out.println(name.length()); //string name has a length of 8
Indexing of String name:¶
| char | T | . | S | w | i | f | t | |
|---|---|---|---|---|---|---|---|---|
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 
String Methods¶
| Method | Returns | 
|---|---|
| charAt(i) | a character in this String at index i | 
| contains(str) | trueif this String containsstrinside it,falseotherwise | 
| endsWith(str),startsWith(str) | trueif this String ends/starts withstr,falseotherwise | 
| equals(str) | trueif this String is the same asstr,falseotherwise | 
| equalsIgnoreCase(str) | trueif this String is the same asstrignoring capitalization,falseotherwise | 
| indexOf(str) | the index in this String where strbegins,-1if not found | 
| length() | the number of characters in this String | 
| replace(str, newStr) | a new String with all strin this String replaced withnewStr | 
| substring(i) | characters in this String from index i(inclusive) to end (exclusive) | 
| substring(i, j) | characters in this String from index i(inclusive) toj(exclusive) | 
| toLowerCase(),toUpperCase() | a new String of this String with all lowercased or uppercased characters | 
Type Casting¶
(Assigning a value of one type to another data type)
Type Casting Framework¶
<type1> <name> = (<type2>) <value>;
double num = 5.2;
int myInt1 = num; // Compiler error. Incompatible types: possible lossy conversion from double to int
int myInt2 = (double) num; // Resolve incompatible types with casting; myInt2 has the value 5