24su ver.
Note: this is for the Summer 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.
Java Basics¶
method - a command for the computer
method - a public or private (do not need to know what this means yet) block of code that, when called, executes the code inside
public static void
- we call public static so that our method can be used (do not need to know what this means yet)
example - name of our method, similar to how we call the main method “main” (can be called anything you want)
()
- we do not need to worry about this right now and it will be introduced at a later point
public static void example() {
/***
Your code here
**/
}
header - the top line of a class
public class HelloWorld
body - the code in between two curly braces { }; note, all code must be in the body of a class
public static void main(String[] args) {
// the printlns are the body
System.out.println("Hello World!");
System.out.println("Hello World!");
}
statement - a bit of code that describes an action to be carried out
System.out.println("Hello World!"); // this is a statement that prints out Hello World!
calling - asking the computer to execute the method
public static void main(String[] args) {
// the example method is being called in main
example();
}
public static void example() {
System.out.println("Hello World!");
}
argument - anything in between the parenthesis
System.out.println("Hello World!"); // Hello World! is the argument
passing in - referring to the argument passed into the parenthesis
System.out.println("Hello World!"); // we are passing in Hello World!
whitespace - invisible characters in your code such as indentation (tabs), line breaks, and spaces
printing - prints specified text to the console
System.out.print("text"); // "prints" some text
System.out.println("text"); // "prints" some text and moves to a new line
System.out.println(); // "prints" a blank line
comment - text in a code file that isn’t intended for the computer to execute, but instead is a description of the code, or a note about the code for yourself and other humans looking at your code
// text (one line)
/* text (multiple lines) */
console - the place where the program’s output appears
compiler - turns your human-readable code into a different kind of file called an executable file that says the same actions for the computer to do but in a different format
execution - a program called the Java Virtual Machine executes your code, means performing the actions described by the executable file
bug - a functional problem with your code
debugging - process of finding and fixing bugs
Turtle Basics¶
software library - a collection of classes, methods, and/or other components that you can use in your code
Java-Turtle - a software library that supports drawing visual graphics using what’s called a Turtle
(don’t forget that we need the Turtle class to access Java-Turtle)
Turtle donatello = new Turtle(); // Creates a turtle called t to be used in the program
Methods | Description |
---|---|
donatello.forward(x); | moves turtle forward by a distance of x pixels |
donatello.left(deg); | turns turtle left by deg degrees |
donatello.right(deg); | turns turtle right by deg degrees |
donatello.up(); | lifts pen up and stops drawing |
donatello.down(); | puts pen back down and starts drawing |
donatello.penColor(color); | sets pen color (String or Java Color) options: black, blue, cyan, gray, green, magenta, orange, pink, red, yellow |
documentation - a reference that describes the classes, methods, etc. available in a software library, and how to use them
Data Types and Expressions¶
variables - containers (or boxes) that store values of a specific data type
type - the type must be specified for variables (int
, String
, etc.)
integers - whole numbers such as 1, 2, 3, 0, -1, -50; integers are stored using the keyword int
doubles - decimal numbers such as 0.25, -3.56, 3.14, 500.0; doubles are stored using the keyword double
Strings - represent text such as “Hello”, “Bye”, “CSE 121”; a collection of letters, digits, or other characters that are strung together to form a word or a sentence
booleans - a data type that has only two possible values: true or false
character - a single character; a letter, digit, or special character called char
expression - a construct made up of variables and operators; can be thought of as a mathematical expression
5 + 3.14
binary operators - used to combine two values (or operands) and each operation evaluates to a new value; can use basic mathematical operators for addition (using +
), subtraction (using -
), multiplication (using *
), and division (using /
)
modulo (mod) - uses the %
character; the remainder of an int division using the same two operands
relational operators - allow us to check the relationship between two operands (or values); evaluates an expression to see if it is true
or false
==, !=, >, <, >=, <=
10 > 5 returns true
3 == 9 returns false
logical operators - similar to relational operators, evaluates an expression to see if it is true or false
&&, ||, !
8 > 4 && 8 < 4 returns false
precedence - the order parts of an expression are evaluated in
PMMDAS - order of operations
-
P - parenthesis
-
MMD - modulo, multiplication, or division, whichever comes first (left to right)
-
AS - addition or subtraction, whichever comes first (left to right)
All of these operators have higher precedence than relational and logical operators (except for the “logical not” !)
Variables, Strings, and Debugging¶
declaration - specifying a data type (like int
, double
, or String
) and a name/label
variable declaration: <data type> <name>
ex: int age;
initialization - storing a value into it
variable initialization: <name> = <value>;
ex: age = 10
;
primitive - types that are directly built into Java; begin with a lowercase letter, and are Java reserved words which means that they often will be highlighted in a specific color when you type them into a Java program
index - each character in the string has a number associated with it that specifies its position within the string; this is called the index of the character
c o r g i
0 1 2 3 4 // these are the indices
zero-based indexing - the indices for Strings start at 0, not 1
\t
- tab
\n
- new line
Note: even though we can use n for a new line, we prefer to use a series of print and println statements to maintain proper code quality in 121 assignments
"
- quotation mark
\
- backslash
String methods¶
can be used to manipulate and examine strings
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 |
run - compile and execute code
For Loops¶
for loop - a programming construct that allows for a set of controlled statements (or lines of code) to be repeated a set number of times
definite loop - when we write a for loop, we will write it in such a way that we know exactly how many times the loop should run
iterate - the number of times code in a loop is executed
Elements of a for loop¶
initialization - we set up a counter at the beginning of the loop to keep track of how many times we’ve repeated the code.
test - before each repetition, we check a condition. If the condition is true, we keep going with the loop. If it’s false, we stop and move on to the next part of the program.
update - after each repetition, we update the counter. This helps us decide when to stop the loop.
Ways to Increment and Decrement the Update Variable¶
Statement | Description |
---|---|
i++ | increment i by 1; same as i = i + 1 |
i += 1 | increment i by 1; same as i = i + 1 |
i-- | decrement i by 1; same as i = i - 1 |
i -= 1 | decrement i by 1; same as i = i - 1 |
body - inside the loop, we write the code we want to repeat. This code will run over and over as long as the test remains true
// there would be actual values and conditions in the placeholders below
for (initialization; test; update) {
body (statements to be repeated)
}
// example that prints corgi corgi corgi corgi corgi
for (int i = 0; i < 5; i++) {
System.out.print("corgi ");
}
string traversal - process of accessing and processing each character in a string one by one
Nested for Loops, Scope¶
nested for loop - syntax involves placing a for loop inside another for loop; used when we need to repeat a task (inner loop) multiple times within another repetition (outer loop)
for (int i = 1; i < 5; i++) {
for (int j = 0; j < i; j++) {
// prints astericks based on i
System.out.print("*");
}
System.out.println();
}
Output
*
**
***
****
scope - the idea that different values can be accessed, altered, and utilized, within a particular part of a program; scope is important for methods and parameters as we are passing around information in between methods with different scope variables declared within a method have scope limited to that method. They cannot be accessed outside of the method in which they were declared
Parameters, Random¶
parameters - values of different data types such as String, int, double, etc. that we “pass into methods” to utilize these values within the methods; this allow methods to work with data or information from outside the method, which provides greater power and flexibility in what methods can do
WithParameters.java
public class WithParameters {
public static void main(String[] args) {
line(5); // prints 5 stars using the parameter
line(10); // prints 10 stars using the parameter
}
// int numStars is the parameter here
// we specify in main how many stars we want printed
// and run the loop according to that number
public static void line(int numStars) {
for (int i = 1; i <= numStars; i++) {
System.out.print("*");
}
System.out.println();
}
}
fenceposting - pulling one iteration out of the loop
// Let's say we want to print "p-i-c-k-l-e-b-a-l-l"
// If we used a loop, to do this,
// Incorrect version:
String word = "pickleball";
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
System.out.print(letter + "-");
}
// This would be the output p-i-c-k-l-e-b-a-l-l-
// To fix this, we use fenceposting
// Correct6 version:
String word = "pickleball";
System.out.print(word.charAt(0));
for (int i = 1; i < word.length(); i++) {
char letter = word.charAt(i);
System.out.print("-" + letter);
}
// This would be the output p-i-c-k-l-e-b-a-l-l
// By printing the first character of the word, starting the loop at
// the second letter, and moving the dash, we could print the correct output
randomness - generate a random value and use it
(don’t forget to use
import java.util.*;
outside of the class)
Random rand = new Random(); // Creates a Random called rand to be used in the program
// type name Random creation code
nextInt()
- random integer
nextInt(range)
- a Random method that returns a random integer within a given range; this range
- we get a range that always starts at 0 (inclusive) unless added to and will end just before the max (exclusive)
rand.nextInt(4); // Produces random integers between 0 and 3
rand.nextInt(4) + 1; // Produces random integers between 1 and 4
rand.nextInt(4) + 2; // Produces random integers between 2 and 5
nextDouble()
- returns any random double between 0.0 and 1.0 exclusive
Math Class¶
Math - used to do more complex mathematical operations easily
Method | Returns |
---|---|
Math.abs(value) | absolute value (make positive) |
Math.ceil(value) | value rounded up |
Math.floor(value) | value rounded down |
Math.max(value1, value2) | larger of two values |
Math.min(value1, value2) | smaller of two values |
Math.round(value) | value rounded to the nearest whole number |
Math.pow(base, exp) | base to the exp power |
Math.sqrt(num) | square root of num |
Returns¶
return statements - used to “return” values after the block of code prior to the return statement has been executed; you can return all different data types when using a method
- return types are specified when the method is set up
No return type
public static void example() {
/*
* code
*/
}
With String return type
public static String example() {
/*
* String word = "corgi";
* code
*/
return word;
}
- only one value can be returned in a method (you cannot return two different word variables for example)
- the return must be the last line of code in the method or else it will be unreachable
catch the return - since methods with a return only return one value, you can “catch the return” by creating a variable of that type in a different method and set the method equal to the created variable
Catch the return
public class Demo {
public static void main(String[] args) {
// here, num = 6 since the example method returned 6
int num = example();
System.out.println(num);
}
public static int example() {
int num = 6;
return num;
}
}
Output
6
Conditionals¶
conditional - allow us to execute some sequence of code if a condition is true, and to skip over that code otherwise; code only executes when we want it to
-
the conditions are established with relational and logical operators (listed above)
-
if statement: if the statement within the parenthesis is true (e.g. i
f (x > 5)
), then the code that is within the if branch will execute. -
if/else statement: if the statement within the parenthesis is true (e.g.
if (x > 5)
), then the code that is within the if branch will execute, otherwise the code that is within the else branch will execute (code must execute within either the if or else branch and the program will not skip over this code) -
if/else if statement: If the statement within the first if statement is false, the program will move on to each else if branches that all contain different expressions (e.g.
if (x > 5) {} else if (x > 2) {} else if (x > 0){}
) until it finds a branch that evaluates to true. -
With if/else if statements, there is no requirement for any branch to evaluate to true, so there is no branch that must execute (unless the if/else if statements end with an else branch, in which case the code within the else branch will execute).
Syntax
if (test) {
body (statements to be executed)
}
int num = 7;
if (num < 4) {
System.out.println("the number is less than 4");
} else {
System.out.println("the number is greater than or equal to 4");
}
// Since 7 is not less than 4, we skipped past the if branch and entered
// the else branch
mutually exclusive - we cannot execute more than 1 of a conditional structure’s branches at once (cannot enter if and else at the same time for example)
While Loops¶
while loop (indefinite loop) - a loop that runs until some condition is met; the number of iterations is unknown
-
the conditions are established with relational and logical operators (listed above)
-
test (parenthesis) - check whether or not to continue iterating in the while loop by way of a continuation test
-
body (brackets) - set of controlled statements that will be executed or run every time we take another iteration in the while loop
Syntax
while (test) {
body (statements to be repeated)
}
// Counts how many times it takes to produce a 6
int range = rand.nextInt(6) + 1;
int count = 0;
while (range != 6) {
count++;
}
System.out.println(count);
// Notice here, we do not know how many times it will take to
// produce a 6. We see that the loop runs until the condition is
// false (6 != 6)
Scanner¶
hardcode - directly write values we are dealing with into the program itself (instead of using a parameter, class constant, Scanner, etc.)
Scanner
- construct allows us even more flexibility in our programming by allowing us to write programs that execute some behavior based on information the user gives us directly
-
type - just like with any variable, when you create it you want to make clear what type the variable is. We can have variables of type
Scanner
by making sure you list the type as Scanner -
name - again, just like with any variables, we can name
Scanner
variables anything we want! You’ll usually see them being named something along the lines of console, input, etc. but it’s up to you what you’d like to name it
Scanner
construction code - (e.g. new Scanner(System.in)
) - to construct or create a new Scanner variable, you must have new Scanner(System.in);
after the equal sign when creating a Scanner variable. This code helps ensure that we are properly constructing a new Scanner variable. Note that new is a keyword needed to create an instance of a Scanner
(don’t forget to use
import java.util.*;
outside of the class)
Setting up the Scanner
Scanner console = new Scanner(System.in);
// type name Scanner construction code
System.out.print("Enter a name: ");
String name = scan.next(); // Example: if the user enters Hannah, the value of name is "Hannah"
System.out.print("Enter a number: ");
int num = scan.nextInt(); // Example: if the user enters an integer,
// that integer will be stored inside of num, otherwise
// InputMismatchException
// (even if the user enters a double)
// Note - when you press enter, the cursor will jump down to the next line
// This is why we use print and not println
enter - when a Scanner prompts the user the enter a value, pressing the enter key is what tells the Scanner to keep track of the entered value
Method | Description |
---|---|
next() | one token as String |
nextLine() | entire line as String |
nextInt() | one token as int (if possible) throws execption if not |
nextDouble() | one token as double (if possible) throws exception if not |
boolean zen - setting a condition equal to true or false (this is improper code quality)
Improper code quality
if (number < 0 == true) {
System.out.println("The number is negative.");
}
Proper code quality
if (number < 0) {
System.out.println("The number is negative.");
}
Arrays¶
data structure - a format used to store, manage, organize, and retreive data (arrays are an example of this!)
array - a list with a fixed size that contains values of the same type
Valid array examples
[0, 5, 12, 19]
["marvin", "photo", "1"]
element - each variable in an array is called an element, it is a name we use to specify a single value in an array
index (pl. indices) - the position of an element in a collection (such as a String or array)
in Java, we use zero-based indexing to specify the position of elements, meaning we count, starting at 0, from the first element
quick-initialization - a type of array creation where indices are not set to their default values, and instead are set to given values at the same time as creating the array
Standard array initialization
int[] arr1 = new int[10];
Quick array initialization
double[] arr2 = {3.3, 7.1, 10.0, 1.977};
array traversal - a process of accessing each index or “spot” in an array one by one
Reference Semantics¶
value semantics - this logic is obeyed by variables that hold primitive data types
- primitive data types include ints, doubles, booleans, etc.
reference semantics - this logic is obeyed by variables that have an object type
- objects such as arrays follow reference semantics
2D Arrays¶
two-dimensional (2D) array - an array where each element of the array is it’s own array. in other words, at each index of the overlying array, there is another array which is indexed into separately - to access individual elements in a 2D array, we must use two indices: