CS62 - Fall 2026 - Class 3
Example code in this lecture
ClassBasics
Initialization
CardDealer
Lecture notes
Admin
- how is assignment 1 going?
- mentor hours posted
- my office hours posted soon!
- quiz tomorrow at the beginning of lab
- assignment 2 out on Thursday
constants: look at the Card class in
ClassBasics code
- at the top of the class I've defined two other instance variables, MIN_NUMBER and MAX_NUMBER. These are "constants".
- I've used them below in the isValidNumber method
- constants are variables that represent values that do not change in the code based on how the code is run
- We can access them just like any other instance variable
- Why use constants?
- can make the code easier to read
- makes the code easier to update maintain
- if I want to change the value, I can just change it at the top
- this is particularly critical if we're using the same constant in many places
- to indicate that they're constants, I make them all caps
- this indicates to anyone reading the code that they're constants
- to indicate to Java that they're constants (and therefore yell at me if I try and change them) I add the keyword "final"
- if I try and change a variable that has been set as final, Java will yell at me
MIN_NUMBER = 12; // Not valid
static
- variables
- Everything in Java has to be inside a class
- For instance variables, that means that each time we get a new copy of the object, we get extra copies of the variables
- For constants, that means each copy of the object will have it's own versions of the constants. Does that make sense?
- No!
- if we declare a variable to be static, there's only one version of it PER class, NOT per object
- all constants we will declare as static
- methods
- Java does not have functions, it only has methods
- a function is a standalone piece of code that is not associated with a class
- a method is called on an object, e.g. variable.methodName(...)
- There are some times when we might want to have function-like behavior? Any ideas when?
- Some things really should just be function (e.g., math operations like round, abs, etc. --
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
)
- our code has to start somewhere. Chicken and the egg problem: what code constructs the first object?
- For these reasons, there are static methods
- details:
- static methods can be called *without* instantiated an object
- if you're inside the class, you can just write the name of the method (though this isn't that different from calling a non-static method)
- if you're outside of the class, you can call it by saying the class name . (dot) the method name
MyClass.staticMethodName(...)
- static methods cannot access any non-static instance variables (instance variables are associated with an instance of the class).
JavaDoc: documentation in Java
- JavaDoc is a way of commenting your code that *also* allows for html documentation to be generated!
-
http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
- a way for you to communicate the "interface" to other programmers/users
- /** is the beginning comment delimiter for classes/methods
- if you type this above the class or a method and hit return, Eclipse will automatically generate a template for you!
- Two basic parts
- The document comment, which is written in HTML and is the first non-whitespace-line chunk of text
- block tags. The main ones we'll use are below, but many more online
- @author
- @param
- @return
- @throws
- Look at the JavaDocCard class in ClassBasicsCode
- We can generate the HTML from the comments on the command line:
- javadoc -d <destination> <list_of_java_files>
- For example:
javadoc -d documentation ClassBasics/*.java
initializing variables
- When we declare a new variable, Java creates a new space in memory for the value
- if it's a primitive type, the value will go directly there
- if it's anything else, it will be a reference to an object
- We often will declare the variable and assign to it immediately:
int x = 2;
Card c = new Card(1, "hearts");
- However, we can also decouple these steps:
int x;
x = 2;
Card c;
c = new Card(1, "hearts");
- What would happen if we looked at/printed out the value of a variable *before* assigning to it?
- In some languages, this isn't well defined!
- In Java, when you create a variable without assigning to it, it gets a default value
- For the primitive types, it's something reasonable (often 0)
- For everything else, we get "null"
- null is Javas way of indicating that this variable is not associated with a value.
- Why does Java give variables a default value?
- Makes the code predictable
- Security! If it didn't, we might be able to access what *used to be* at that location
- C/C++ has this behavior and is one of the causes for being able to compromise values/systems
look at Initialization.java in
Initialization code
- Anything unusual about the code?
- Where is the constructor?!?
- If you don't specify a constructor, Java will automatically generate a zero parameter constructor for you
- It doesn't do anything, but the object get created along with the instance variables
- this
- every class has an instance variable (that is implicitly declared) call "this"
- The type of the variable is the type of class, in this case Initialization
- It holds *the current object", i.e., it is a reference to the object that the methods are being called on
- Most of the time "this" isn't needed:
- you can just say
x = 2
- and don't need to say
this.x = 2
though they do the same thing
- in setX there is a parameter x and an instance variable x
- if we wrote x = x
- this is just assigning to the parameter x it's own value
- this.x = x
says store into the instance variable x the value of the parameter x
- we could have also just written
public void setX(int number){
x = number;
}
but it's often convenient to use the same name to make it explicit
look at Initialization.java in
Initialization code
- What would happen if we run test1()?
- We'll see:
2
4 of hearts
- What would happen if we run test2()?
- We haven't set the values, so we'll get the default values
0
null
- What would happen if we run test3()?
- try to call a method on an object that doesn't exist!
java.lang.NullPointerException
- You will get null pointer exceptions
- it just happens if you program long enough in Java
- The cause is that you tried to access some value as if it were an object, but it was actually null
Arrays in java
- Arrays (kind of like lists) allow us to store multiple objects in a single variable
- creating lists of primitive data_types
int[] nums = new int[10];
- will create an array with 10 elements, assigned the default value (0)
- just like in Python, we use square brackets to get the items in the array
nums[0] // first number
nums[3] // fourth number
- arrays are NOT lists
- lists start out empty and we can fill them up, e.g., via append (or add)
- arrays are always the same size!
- length: you can tell the number of elements in it using .length
cards.length
- would give us 10
- we can initialize the array with particular values if we want using {}
int[] nums = {10, 57, 6, 8, 2};
- this only works for primitive datatypes (and for Strings)
We're now able to understand the main method!!!
- public: accessible outside of the class
- static: stand-alone method that does not access/require any state of an object (i.e. access instance variables)
- void: doesn't return anything
- main: name of the method
- String[]: an array of Strings
- args: the name of the parameter
What does the constructor do in CardDealer in
CardDealer code
- What does the constructor do (ignoring shuffle for now)?
- creates a new array for number of decks * 13 * 4 entries
- adds each card for each deck to the array
- outer loop is over the number of decks
- second loop is over suits
- third loop is over numbers
What does the shuffle method of the CardDealer class in
CardDealer code
do?
- for each card, pick another random entry and swap the entries
- Where does Random come from?
- it's another class that we imported!
A package is a collection of classes
- usually they're related
- Any class inside a particular package may use any other class in the package without doing anything special
- If you want to use a class that is not inside your package, you need to import it
- To import a class:
import <package_name>.<class_name>
- sometimes, there are nested packages, e.g.
import <outer_package>.<inner_package>.<class_name>
- For example:
import java.util.Random
- imports the Random class from the java.util package
import java.util.Scanner
- imports the Scanner class from the java.util package
- To write your own package:
- Packages are indicated in two ways (both are required):
1) All classes inside a packages should be in a directory with the packages name
2) All classes inside a package should start with package <package_name>;
Look at the CardDealer in
CardDealer code
- What does the printDeck method do?
- it's static, so it doesn't have access to the instance variables
- creates a new card dealer and then prints out the entire deck
- utilizes next and getNext
- both use position to keep track of where we are
- using this pair of methods is a common way to iterate through data. we'll see it a lot!
Look at the CardPrinter class in
CardDealer code
- What does it do?
- What is new?
Scanner class
- Useful for reading data (we'll see more on this later)
- Requires a source, in this case, we give it System.in, which is user input from the keyboard
- Has a generic method nextLine, but many, many other methods that read specific types
- See the documentation at:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
- e.g., nextInt assumes the next value is an integer and returns it as an int
type casting
- What is does the CardDealer constructor expect as input?
- Why doesn't this give an error?
CardDealer deck = new CardDealer((numCards / 52) + 1);
- Java has different divisions for integers and floats/doubles
- integer division truncates the decimal part
System.out.println(5/2)
System.out.println(-5/2)
will print out
2
-2
- If any one of the numbers is a float/double, then it will do decimal divion
- Be careful, e.g.
double x = 5/2;
System.out.println(x)
time permitting: write a function called addArrays that takes as input two arrays of ints and returns an array with the element-wise numbers added together. You can assume that the arrays are the same length. EC: add if/else to check if they're the same length
int[] nums1 = {1, 2, 3, 4, 5};
int[] nums2 = {7, 8, 9, 10, 11};
addArrays(nums1, nums2);
would return [8, 10, 12, 14, 16]