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;
(x has the value 3)

int y = 1 + x * 2;
(y has the value 7)

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) true if this String contains str inside it, false otherwise
endsWith(str), startsWith(str) true if this String ends/starts with str, false otherwise
equals(str) true if this String is the same as str, false otherwise
equalsIgnoreCase(str) true if this String is the same as str ignoring capitalization, false otherwise
indexOf(str) the index in this String where str begins, -1 if not found
length() the number of characters in this String
replace(str, newStr) a new String with all str in this String replaced with newStr
substring(i) characters in this String from index i (inclusive) to end (exclusive)
substring(i, j) characters in this String from index i (inclusive) to j (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