Professional Documents
Culture Documents
Slides:
by Jonathan Lui & Spencer Lee
http://bit.ly/1n3fNh3
moves
Wheel
Engine
What is Java?
● Code you write (.java) -> compiled to Java Byte code (.class) -> run by
Java Virtual Machine which converts it to native code run by your computer
OOPS!
What can be done with Java?
Make cool Physics simulations (PhET) Make Android apps Build Enterprise Software
How is Java different from Racket?
Your CPU does not understand Racket or Java, so how does it run these
programs?
Text Editors
● Sublime Text (for people who know what they are doing)
Variables
Now I want my program to remember the result of 1+1 and then multiply it by 2
Let’s create a variable:
System.out.println(“Hello world!”);
}
}
The Main Function
● The glue that ties the different parts of a Java program together
● The function that gets executed at the beginning of a Java program
● Used to call any other functions as needed
Hello World - Dissected
//SomeClass.java
class declaration
public class SomeClass { argument
function name type name
public static void main(String[] args) { function declaration
call a system
System.out.println(“Hello world!”); defined function
argument to function -
} the text to print
}
1+1=?
Okay, let’s have Java do something more useful than saying hello to the world
}
}
Arithmetic in Java is a little different than in Racket:
(+ 1 1) => 2 1 + 1 => 2
Variables - Mutable
Did I say variables can change?
int x = 5;
System.out.println(x); // outputs 5
x = 6; // re-assignment
System.out.println(x); // outputs 6
Also, note that once a variable has been declared (x is an int), you don’t have
to redeclare it (say it’s an int) in successive “reassigning” of the variable
Primitive Types - numbers
This brings us to the topic of data types:
Let’s start with numbers:
byte stores integers (both +ve and -ve) from -128 to +127
short stores integers (both +ve and -ve) from -32,768 to +32,767
int stores integer (whole) numbers (both +ve and -ve) from
-2,147,483,648 [-231] to +2,147,483,647 [2 31-1]
long stores integers (both +ve and -ve) from -263 to +263-1
float (32-bit)
double (64-bit)
Where is pow?
So someone extended the Java language by writing a library called Math which has a
function in it for calculating the power
Java docs
Numbers and Functions - 1
Let’s start bringing together the things we’ve learned so far
We’ll write a program that prints the result of all of the following:
● 32 multiplied by 134
● 76 multiplied by 134
● 134 multiplied by 134
Numbers and Functions - 1
Of course, we can do this:
public static void main(String[] args) {
System.out.println(32 * 134);
System.out.println(76 * 134);
System.out.println(134 * 134);
}
Number operators follow PEMDAS, or “order of operations”, like the way you learned Math in grade
school.
For your own peace of mind, you can add (redundant) brackets to prioritize operations:
System.out.println(someStr);
into a function
In Java, it’s OK for a function to not return anything, just specify void as the
return type
Done!
public class SomeClass {
}
Back to variables
● Variables are just short form ways of remembering previous results
○ Try computing 4! (i.e. 4*3*2*1)
Example 1 - Variables
● Variables are just short form ways of remembering previous results
○ Try computing 4! (i.e. 4*3*2*1)
You probably did this by keeping track of the result so far, modifying it as you
went along
● Memory is finite
Declaring a variable
● To declare a variable in Java you need
○ variable type
○ variable name
e.g.
int myFirstVariable;
int myFirstVariable = 3;
is the same as
int myFirstVariable;
System.out.println(myFirstVariable); // ERROR
However, static variables (more on this laster) do have a default value. And for
number types, this is 0
String s = “hello”;
here, the + operator serves to combine two strings
Appending two strings: together - this is called concatenation
Yes, this is a little weird. But wait until you see this:
String s = “hello”;
Declaring a static variable of type String with no value would make the
variable null:
static String s;
//….
System.out.println(s);
if (<condition1>) {
//executes if condition1 is met
} else if (<condition2>) {
//executes if condition1 is NOT met
// and if condition2 is met
} else {
//catches everything else
//i.e. neither condition1 nor condition2 met
}
Conditions
So what is a condition?
x < 0 // x is negative
x >= 42 // x is greater than or equal to 42
x == 134 // x is equal to 134 note the double ==
x != 134 // x is not equal to 134
int x = 42;
String s = “hello”;
- live code
Number Checker - Solution
public static void main(String[] args) {
numberChecker(13);
}
If the string is less than 4 characters long, print the whole string.
If the string is 4-8 characters long, take the first 4 characters and add ‘...’ after.
If the string is more than 8 characters long, print out “String too long”
For example:
lengthChecker(“abcd”) // => “abcd”
lengthChecker(“hello”) // => “hell...”
lengthChecker(“helloworld”) // => “String too long”
Length checker - solution
public static void lengthChecker(String s){
if (s.length() < 4){
System.out.println(s);
}
else if(s.length() >= 4 && s.length() <= 8){
System.out.println(s.substring(0,4) + "...");
}
else{
System.out.println("String too long");
}
}
Iteration vs Recursion
● In Racket, we achieved repetitive behaviour in code using Recursion
● for Java, recursion still exists, but we will be mainly focusing on Iteration
For example:
System.out.println(“hello world”);
System.out.println(“hello world”);
Iteration
But what about 10 times? or 42 times?
We use iteration!
System.out.println(“hello world”);
}
for loops - live code
Write a program to print only the even numbers from 1 to 50
Hint: You can use the counter variable i inside the body of your loop
for loop - solution
Logistic:
● expressions within the block will be executed while condition is true
while - practice 1
Let’s rewrite our first for code using while
while (true) {
if (i % 3 == 0 && i % 4 == 0 && i % 5 == 0) {
return i;
} this is called early return
i++;
}
}
break
What if there are other things we want to do before returning a result for our
function?
static int divisibleBy345() {
int i = 1;
int result = -1;
while (true) {
if (i % 3 == 0 && i % 4 == 0 && i % 5 == 0) {
result = i;
return result;
}
i++;
}
System.out.println(“The result is ” + result);
}
What’s the problem with this code?
When a result is found, return exits the function
break
break works like return, but it does not exit the function, it only exits the
code block it’s in
static int divisibleBy345() {
int i = 1;
int result = -1;
while (true) {
if (i % 3 == 0 && i % 4 == 0 && i % 5 == 0) {
result = i;
break;
}
i++;
}
System.out.println(“The result is ” + result);
}
○ fizz if x is divisible by 3
○ buzz if x is divisible by 5
○ fizzbuzz if x is divisible by 15
○ x otherwise
}
Summing up...
Variables
● are mutable - but must remain in the same type
● must be declared with type (int, String, boolean...) and name
Functions
● must specify return type and types and names of input arguments
● early return
Conditional
● if / else if / else statements
Arrays
● get and set using index number
Loops
● for
● while
Project: hangman
Design a hangman game with Java:
Description:
(1) The program starts with accepting an input for the word to guess (e.g. java)
○ have your partner type in this word
(2) Type a character for your guess
(3) If the character matches one from the guessed word, display it like this:
○ User input: a output: _ a _ a
(4) Repeat (2) - (3) until the whole word is revealed
○ output: java - You guessed it, congratulations!
Bonus: also keep track of attempts, and let player know their score!
An Object is an instance of a Class - e.g. : the many pens that exists in the world
- all Objects of a Class gets its defined properties and methods
Looks familiar?
Instead of making a variable with primitive type, we make the variable myDog
belong to the class Dog
new - it’s a Java keyword that creates an instance of the class that follows
Dog() - is the constructor for the class Dog, which creates a Dog object
Class - fields
Now let’s expand our Dog class to include more:
This class has 2 fields - essentially the properties of the object - called breed
and name, both of which are Strings
Class
This is very much like Racket’s struct:
Except:
our default Dog() constructor doesn’t take in any arguments
- we can’t specify values for breed and name of myDog ... YET!
Class - constructor
public class Dog {
private String breed;
private String name;
// totally optional
public Dog() {
// this executes when creating new object
}
This is the constructor. It creates a new instance (object) of the class. This
default, no argument constructor, does not explicitly need to be defined
this
● the keyword this, when used within a class refers to an instance of the
object
● we use dot notation to call a function on an object AND to access its fields
○ this.someField
○ this.someMethod()
Class - constructor
public class Dog {
private String breed;
private String name;
Treat the constructor as a function - a special one, thus it can accept any
arguments you desire.
Class - constructor
Creating a new object:
}
Challenge... BST!
Since we are recent 110 graduates... let’s represent a Binary Search Tree
using a Class in Java
2
Recall:
;; BST is one of
;; - false ; if its a leaf
;; - (make-node Integer String BST BST)
; key ;value ;l ;r 1 3
5
BST
public class BST {
private boolean isLeaf; // used instead of “false”
private int key;
private String value;
private BST left; // YES! you can have fields of the same class!
private BST right;
//INSERT CONSTRUCTOR HERE
private String findNode(int key) {
// some recursive/iterative codes to find child
node with key
}
}
But, don’t worry about data structures for 210, you will likely never see them
Members
The fields of a class and its methods are called its members
Access Modifiers - 1
● We can use dot notation to call a method on an object but why not access
its properties
at Test.main(Test.java:7)
This explains why we could use access the breed field in its class but NOT
outside it
Encapsulation
Why do we want to make fields private?
● modular
● more maintainable
● prevents unwanted modifications by code which other people write (or our
own code!)
● abstraction
○ interface
Encapsulation - Example
Q: Let’s say you want to write a program that models a thermometer and
returns its temperature various units of measurement?
Encapsulation - Example
Q: Let’s say you want to write a program that models a thermometer and
returns its temperature various units of measurement?
A: You’d need
● a Thermometer class
● a temperature field
● getFahrenheit()
● getCelsius()
● getKelvin()
● modular
● maintainable
Getters and Setters
We’ll generally want to make fields private
But what if want to provide third party code with a means to alter or get these
properties?
○ class functions
Class Variables - 1
● a variable can be associated with a class
○ constants
Class Variables - 2
public class Dog {
Dog.defaultNumberOfLegs
Class Variables - 3
TASK: Add a number_of_legs field to your Dog class and have it set to the
default number of legs in the constructor
Class Variables - 4
public class Dog {
}
Constants
● Declared in the same way except we use the final keyword to denote its
cannot be changed after initialization
● Use SNAKE_CASE
e.g. the scientific name of a dog will never change (nor will the default number
of legs, I’m sure!)
public SomeProgram {
}
}
Class Variables and Functions - 1
Class functions are often used to access class variables
TASK: Create a PlayStation class with a class variable specifying its brand
name (make it private), and define a class function that prints its brand name
● We make brand private because its not something other classes should be
able to change directly
● Maybe the brand could change, but there should be some checks
around that - so create a setter
array: more
Let’s go back to talking about array:
Problem:
Given an array of int[], insert the number 42 to the last non-empty position
add it here
4 6 15 0 0 0 0 0 0 0
System.out.println(name);
Sets
- no duplicate elements
- no positional guarantee
Queue
- First-in-first-out
Inheritance - 1
● The aim is always to write DRY (Don’t Repeat Yourself) code
PC:
Have the constructor also take in a windows version define associated getter
Mac:
Have the constructor also take in an OS X version, define associated getter
Inheritance - an example
public class Mac {
private double screenSize;
private double OSXName;
e.g.
m.getScreenSize();
//works through inheritance since a mac is a
//computer
Inheritance and Variables - 2
but if Computer didn’t have a getScreenSize() method
m.getScreenSize(); //works as method in mac class
c.getScreenSize();
// no method since not all computer may be Macs and
// therefore might not have the getScreenSize
method!
● the type of an object, i.e. what is used to construct it, is its actual type, and
determines which implementation of a method (amongst the containing
class itself and its superclasses) gets called
Dispatching - 1
But wait, what if we defined a getScreenSize method for our Mac class
vs
vs
vs
vs
someObject.someMethod();
//overriding method
public double getScreenSize() {
//<some alternate logic>
}
}
Overriding Example
So now both Computer and Mac have an implementation of
getScreenSize(), which implementation is called in the following code?
vs
vs
A: The Mac version of getScreenSize is called in both examples. But in the second
example, we say the Mac version overides the Computer version of the method
Overriding and super
super can be used to call the parent’s implementation of some method (same
signature)
Overloading is when you have multiple functions with the same name but
different argument lists (different types, number of arguments but NOT
argument type)
● This means that a subclass cannot have two parents at the same
“generation” level, any inheritance relationship must be sequential
A A B
X X
OK in Java OK in C++
Multiple inheritance
Q: What might be some of the problems with multiple inheritance?
Multiple inheritance
Q: What might be some of the problems with multiple inheritance?
D.someMethod()
But still, we want these animals to share some properties and methods,
hence the use of an abstract class
Class vs Abstract Class
class when you want objects for that class
abstract class when it has some subclass that you want objects for.
}
}
Interfaces
Specifies some methods that an Class is required to implement.
<<interface>>
Edible
<<abstract>> <<abstract>>
Plants Animal
Interfaces have
● methods with a signature and no implementation (like an abstract method)
● NO fields
Abstract methods are methods that have no implementation when it’s declared,
waiting to be implemented in a subclass and a class that implements its
interface.
implementing interface
public class Chicken extends Animal implements Edible {
@Override
public int getDietaryCalories() {
return 500;
}
}
Multiple interfaces
A class can implement multiple interfaces!
<<interface>> <<interface>>
Edible Friable
<<abstract>>
<<abstract>>
Plants
Animal
@Override
public int getDietaryCalories() { // from Edible
return 500;
}
@Override
public void fry() { // from Friable
System.out.println(“Deep frying...”);
}
}
Abstract Class vs Interface
Remeber:
Use class/abstract class when it’s logically the higher hierarchy of a class.
Use interfaces for specifying what the objects of the class can do.
Example Java built-in interfaces: Sortable, Iterable, Collection (next)
Error (Exception) Handling
Error arises from programs all the time. Consider this program:
throw stops the execution of the method and spits out the Exception.
But. what to do with the exception?
try/catch block
Let’s say we have a code that calls the divide method:
//...
double result = divide(5, 0); // division by 0
System.out.println(result);
If we do nothing about it, we will receive an Exception (or stack trace) that
identifies the place where the exception was thrown.
try/catch block
To make it produce a more user friendly error:
try {
double result = divide(5, 0);
System.out.println(result);
} catch (Exception e) {
System.out.println(“Cannot divide by 0”);
}
Exception vs RuntimeException
RuntimeException is a subclass of Exception.
}
checked Exception example
public class Account {
private int balance;
static void withdraw(int amount) throws Exception {
}
}
Caller to this function is required to try/catch the exception
checked Exception example
// create new account with initial balance 500
Account myAccount = new Account(500);
try {
myAccount.withdraw(600);
} catch (Exception e) {
System.out.println(“Insufficient funds.”);
}
Exception subclass
What if we want a more specialized Exception for our method?
Exception is a class.
We can extend the class with a more specialized subclass for our purposes:
InsufficientFundsException
public class InsufficientFundsException extends Exception
{
private int balanceAfterWithdrawal;
}
InsufficientFundsException
static void withdraw(int amount) throws
InsufficientFundsException {
}
InsufficientFundsException
Account myAccount = new Account(500);
try {
myAccount.withdraw(600);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
System.out.println(“After withdrawal balance:” +
e.getBalanceAfterWithdrawal());
}
Advice - Doing well in CPSC 210 and
Beyond
● Write CODE!!! - start a personal project
● Read API documentation
● Read other people’s code
● Code with other’s (when your code gets inadvertently changed, you’ll
realize the importance of access modifiers!)
● Write MORE code!!!