CSC201 Lecture 1
CSC201 Lecture 1
B. S. Afolabi
1
Information
Tutorial One
Questions 3 and 4
Tutorial Two
Questions 1 and 3
2
Popular Issues 1
Array Index vs Array Value
int[] values = {99, 100, 101};
System.out.println(values[0] ); // 99
3
Popular Issues 2
Curly braces { … } after if/else, for/while
4
Popular Issues 3
Variable initialization
int getMinValue(int[] vals) {
int min = 0;
for (int i = 0; i < vals.length; i++) {
if (vals[i] < min) {
min = vals[i]
}
}
}
What if vals = {1,2,3}?
Problem?
Set min = Integer.MAX_VALUE or vals[0] 5
Popular Issues 4
Variable Initialization – secondMinIndex
6
Popular Issues 5
Defining a method inside a method
public static void main(String[]
arguments) {
public static void foobar () {
}
}
7
Debugging Notes 1
Use System.out.println throughout your code to
see what it’s doing
9
Today’s Topics
10
Object oriented programming
Represent the real world
Baby
Name
Sex
Weight
Decibels
# poops so far
11
Object Oriented Programming
Objects group together
Primitives (int, double, char, etc..)
Objects (String, etc…)
Baby
String name
boolean isMale
double weight
double decibels
int numPoops
12
Why use classes?
Why not just primitives?
Name
Weight
Sex
…
Baby 1
14
Why use classes?
Name Name Name Name
Weight Weight Weight Weight
Sex Sex Sex Sex
… … … …
496
more
Babies
… 15
Why use classes?
16
Why use classes?
17
Why use classes?
18
Why use classes?
19
Defining classes
20
Class -overview
public class Baby {
String name;
boolean isMale;
double weight;
double decibels;
int numPoops = 0;
void poop() {
numPoops += 1;
System.out.println(“Dear mother, ” +
“I have pooped. Ready the diaper.”);
}
} 21
Class -overview
22
Let’s declare a baby!
Public class Baby {
}
23
Note
Class names are Capitalized
1 Class = 1 file
24
Baby fields
public class Baby {
TYPE var_name;
TYPE var_name = some_value;
25
Baby fields
public class Baby {
String name;
double weight = 5.0;
boolean isMale;
int numPoops = 0;
XXXXX YYYYY;
26
Baby Siblings?
public class Baby {
String name;
double weight = 5.0;
boolean isMale;
int numPoops = 0;
Baby[] siblings;
}
27
Ok, let’s make this baby!
28
Constructors
public class CLASSNAME{
CLASSNAME ( ) {
}
CLASSNAME ([ARGUMENTS]) {
}
}
30
Baby constructor
public class Baby {
String name;
boolean isMale;
Baby(String myname, boolean maleBaby)
{
name = myname;
isMale = maleBaby;
}
}
31
Baby methods
public class Baby {
String name = “Slim Shady”;
...
void sayHi() {
System.out.println(
“Hi, my name is.. “ + name);
}
}
32
Baby methods
public class Baby {
String weight = 5.0;
void eat(double foodWeight) {
if (foodWeight >= 0 && foodWeight <
weight) { weight = weight + foodWeight;
}
}
}
33
Baby class
public class Baby {
String name;
double weight = 5.0;
boolean isMale;
int numPoops = 0;
Baby[] siblings;
void sayHi() {
…
}
void eat(double foodWeight) {
…}
} 34
Using classes
35
Classes and Instances
// class Definition
public class Baby {…}
// class Instances
Baby lamidi = new Baby(“Lamidi Mundundu”,
true);
Baby tapere = new Baby(“Tapere Mundundu”,
true);
36
Accessing fields
Object.FIELDNAME
System.out.println(lamidi.name);
System.out.println(lamidi.numPoops);
37
Calling Methods
Object.METHODNAME([ARGUMENTS])
38
References vs Values
39
Primitives vs References
Primitive types are basic java types
int, long, double, boolean, char, short, byte,
float
The actual values are stored in the variable
40
How java stores primitives
Variables are like fixed size cups
Primitives are small enough that they just
fit into the cup
41
How java stores objects
Objects are too big to fit in a variable
Stored somewhere else
Variable stores a number that locates the
object
42
How java stores objects
Objects are too big to fit in a variable
Stored somewhere else
Variable stores a number that locates the
object
43
References
The object’s location is called a reference
== compares the references
NO 44
References
Baby dende1 = new Baby(“Dende”);
Baby dende2 = new Baby(“Dende”);
“Dende”
“Dende”
45
References
Baby mybaby = new Baby(“davy”, true)
mybaby.name = “david”
name = “david”
46
References
Using = updates the reference.
baby1 = baby2
47
References
Using = updates the reference.
baby1 = baby2
48
References
using [ ] or .
Follows the reference to the object
May modify the object, but never the reference
Imagine
Following directions to a house
Moving the furniture around
Analogous to
Following the reference to an object
Changing fields in the object
49
Methods and references
void doSomething(int x, int[] ys, Baby b) {
x = 99;
ys[0] = 99;
b.name = “99”;
}
...
int i= 0;
int[] j = {0};
Baby k = new Baby(“50”, true);
doSomething(i, j, k);
i=? j=? k=?
50
static types and methods
51
static
Applies to fields and methods
Means the field/method
Is defined for the class declaration,
Is not unique for each instance
52
static
public class Baby {
static int numBabiesMade = 0;
}
Baby.numBabiesMade = 100;
Baby b1 = new Baby();
Baby b2 = new Baby();
Baby.numBabiesMade = 2;
Baby b3 = new Baby();
What is
b1.numBabiesMade?
b2.numBabiesMade?
b3.numBabiesMade? 53
static example
Keep track of the number of babies that
have been made.
57
public class Counter {
int myCount = 0;
static int ourCount = 0;
void increment () {
myCount++;
ourCount++;
}
public static void main(String[] args) {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
counter2.increment();
System.out.println(“Counter 1: “+counter1.myCount+” “+
counter1.ourCount);
System.out.println(“Counter 2: “+counter2.myCount+” “+
counter2.ourCount);
}
58
}
public class Counter {
int myCount = 0;
static int ourCount = 0; Fields
void increment () {
myCount++; Method
ourCount++;
}
public static void main(String[] args) {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
counter2.increment();
System.out.println(“Counter 1: “+counter1.myCount+” “+
counter1.ourCount);
System.out.println(“Counter 2: “+counter2.myCount+” “+
counter2.ourCount);
}
} 59
Class Counter
Object counter1
ourCount = 0
myCount = 0
60
Class Counter
Object counter1 Object counter2
ourCount = 0
myCount = 0 myCount = 0
61
Class Counter
Object counter1 Object counter2
ourCount = 0
1
myCount = 0 myCount = 0
1
62
Class Counter
Object counter1 Object counter2
ourCount = 0
1
2 myCount = 0 myCount = 0
1
2
66
Public vs. Private
Public: others can use this
Private: only the class can use this
67
Access Control
public class CreditCard {
String cardNumber;
double expenses;
void charge(double amount){
expenses = expenses + amount;
}
String getCardNumber(String password) {
if (password.equals(“SECRET!3*!”)) {
return cardNumber;
}
return “jerkface”;
}
}
68
Access Control DONE RIGHT
public class CreditCard {
private String cardNumber;
private double expenses;
public void charge(double amount){
expenses = expenses + amount;
}
public String getCardNumber(String password) {
if (password.equals(“SECRET!3*!”)) {
return cardNumber;
}
return “jerkface”;
}
}
69
Why Access Control
Protect private information (sorta)
Clarify how others should use your class
Keep implementation separate from
interface
70
Scope Review
public class ScopeReview{
void scopeMethod(int var1){
String var2;
if (var1 > 0) {
var2 = “above 0”;
} else {
var2 = “less than or equal to 0”;
}
System.out.println(var2);
}
}
71
Scope Review
public class ScopeReview{
private int var3;
void scopeMethod(int var1){
var3 = var1;
String var2;
if (var1 > 0) {
var2 = “above 0”;
} else {
var2 = “less than or equal to 0”;
}
System.out.println(var2);
}
}
72
Scope Review
public class ScopeReview{
private int var3;
void scopeMethod(int var1){
var3 = var1;
String var2;
if (var1 > 0) {
var2 = “above 0”;
} else {
var2 = “less than or equal to 0”;
}
System.out.println(var2);
}
}
73
Only method level servings is
updated
public class Baby {
int servings;
void feed(int servings) {
servings = servings + servings;
}
void poop() {
System.out.println("All better!");
servings = 0; }
}
74
“this” Keyword
Clarifies scope
Means ‘my object’
Usage:
class Example{
int membVariable;
void setVariable(int newVal) {
this.membvariable += newVal;
}}
75
Only method level servings is
updated
public class Baby {
int servings;
void feed(int servings) {
servings = servings + servings;
}
void poop() {
System.out.println("All better!");
servings = 0; }
}
76
Object level “Servings” is updated
public class Baby {
int servings;
void feed(int servings) {
this.servings =
this.servings + servings;
}
void poop() {
System.out.println("All better!");
servings = 0; }
}
77
Packages
Each class belongs to a package
Classes in the same package serve a
similar purpose
Packages are just directories
Classes in other packages need to be
imported
78
79
80
package adult;
import parenttools.Baby;
import parenttools.BabyFood;
public class Parent {
public static void main(String[] args) {
Baby baby = new Baby();
baby.feed(new BabyFood());
81
}
Why Packages
Combine similar functionality
org.boston.libraries.Library
org.boston.libraries.Book
Separate similar names
shopping.List
packing.List
82
Special Packages
All classes “see” classes in the same
package (no import needed)
All classes “see” classes in java.lang
Example:
java.lang.String;
java.lang.System
83
Overview
• Review
• Access Control
• Class Scope
• Packages
• Java API
84
Java API
Java includes lots of packages/classes
http://java.sun.com/javase/6/docs/api/
85
Arrays with items
Create the array bigger than you need
Track the next “available” slot
Book[] books = new Book[10];
int nextIndex = 0;
books[nextIndex] = b;
nextIndex = nextIndex + 1
87
88
import java.util.ArrayList;
class ArrayListExample {
public static void main(String[] arguments)
{ArrayList<String> strings = new
ArrayList<String>();
strings.add("Evan");
strings.add("Eugene");
strings.add("Adam");
System.out.println(strings.size());
System.out.println(strings.get(0));
System.out.println(strings.get(1));
strings.set(0, "Goodbye");
strings.remove(1);
for(int i = 0; i < strings.size(); i++) {
System.out.println(strings.get (i));
for (String s : strings){ System.out.println(s); } } }
89
Sets
Like an ArrayList, but
Only one copy of each object, and
No array index
Features
Add objects to the set
Remove objects from the set
Is an object in the set?
TreeSet: Sorted (lowest to highest)
HashSet: Unordered (pseudo-random)
90
import java.util.TreeSet;
class SetExample {
public static void main(String[] arguments)
{ TreeSet<String> strings = new
TreeSet<String>(); strings.add("Evan");
strings.add("Eugene");
strings.add("Adam");
System.out.println(strings.size());
System.out.println(strings.first());
System.out.println(strings.last());
strings.remove("Eugene");
for (String s : strings){
System.out.println(s); } } }
91
Maps
Stores a (key, value) pair of objects
Look up the key, get back the value
Example: Address Book
.
Map from names to email addresses
TreeMap: Sorted (lowest to highest)
HashMap: Unordered (pseudo-random)
92
public static void main(String[] arguments)
{ HashMap<String, String> strings = new
HashMap<String, String>();
strings.put("Evan", "[email protected]");
strings.put("Eugene", "[email protected]");
strings.put("Adam", "[email protected]”);
System.out.println(strings.size());
strings.remove("Evan");
System.out.println(strings.get("Eugene"));
for (String s : strings.keySet()) {
System.out.println(s);
}
for (String s : strings.values()) {
System.out.println(s);
}
for (Map.Entry<String, String> pairs : strings.entrySet()) {
System.out.println(pairs); } }
93
Warnings
Using TreeSet/TreeMap?
Read about Comparable interface
Using HashSet/HashMap?
Read about equals, hashCode methods
Note: This only matters for classes you
build, not for java built-in types.
94
Summary
Review
Access Control
Class Scope
Packages
Java API
95
Assignments
96
97
Assignment 4
Modeling Book and Libraries
class Book {}
class Library{}
Books can be
Borrowed
Returned
Library
Keeps track of books
Hint: use Book[]
98
99