0% found this document useful (0 votes)
54 views

CSC201 Lecture 1

This document provides an overview of a computer programming course (CSC 201) and discusses several common programming concepts and issues. It covers topics like array indexing vs values, using curly braces with control structures, variable initialization, debugging techniques, and an introduction to object-oriented programming concepts like defining classes, creating class instances, accessing fields and methods, and the difference between primitive values and object references.

Uploaded by

Wariz Omoniyi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

CSC201 Lecture 1

This document provides an overview of a computer programming course (CSC 201) and discusses several common programming concepts and issues. It covers topics like array indexing vs values, using curly braces with control structures, variable initialization, debugging techniques, and an introduction to object-oriented programming concepts like defining classes, creating class instances, accessing fields and methods, and the difference between primitive values and object references.

Uploaded by

Wariz Omoniyi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

CSC 201: Computer Programming I

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

for(int i= 0; i< 5; i++)


System.out.println(“Hi”);
System.out.println(“Bye”);

What does this print?

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

int minIdx = getMin(vals)


int secondIdx = 0;
for (int i = 0; i < vals.length; i++) {
if (i == minIdx) continue;
if (vals[i] < vals[secondIdx])
secondIdx = i;
}
 What if vals = {0, 1, 2}?
 See solutions to last assignment

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

for ( int i=0; i< vals.length; i++) {


if ( vals[i] < minVal) {
System.out.println(“cur min: ” + minVal);
System.out.println(“new min: ” + vals[i]);
minVal = vals[i];
}
}
8
Debugging Notes 2
 Formatting
Ctrl-shift-f is your friend

for (int i = 0; i < vals.length; i++) {


if (vals[i] < vals[minIdx]) {
minIdx=i;
}
return minIdx;
}
 Is there a bug? Who knows! Hard to read

9
Today’s Topics

Object oriented programming


Defining Classes
Using Classes
References vs Values
Static types and methods

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?

// little baby alex


String nameAlex;
double weightAlex;
// little baby david
String nameDavid;
double weightDavid;
// little baby david
String nameDavid2; David2
double weightDavid2; Terrible
500 babies ??????
13
Why use classes?

Name
Weight
Sex

Baby 1

14
Why use classes?
Name Name Name Name
Weight Weight Weight Weight
Sex Sex Sex Sex
… … … …

Baby 1 Baby Baby 3 Baby


2 4

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

Baby myBaby = new Baby(); (Class instance)

22
Let’s declare a baby!
Public class Baby {

}
23
Note
 Class names are Capitalized

 1 Class = 1 file

 Having a main method means the class


can be run

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!

Baby ourBaby = new Baby();

But what about it’s name? it’s sex?

28
Constructors
public class CLASSNAME{
CLASSNAME ( ) {
}
CLASSNAME ([ARGUMENTS]) {
}
}

CLASSNAME obj1 = new CLASSNAME();


CLASSNAME obj2 = new
CLASSNAME([ARGUMENTS])
29
Constructors
 Constructor name == the class name
 No return type – never returns anything
 Usually initialize fields
 All classes need at least one constructor
 If you don’t write one, defaults to
CLASSNAME () {
}

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

Baby lamidi = new Baby(“Lamidi


Mundundu”,true)

System.out.println(lamidi.name);
System.out.println(lamidi.numPoops);

37
Calling Methods
Object.METHODNAME([ARGUMENTS])

Baby lamidi = new Baby(“Lamidi Mundundu”,


true)
lamidi.sayHi(); // “Hi, my name is ...”
lamidi.eat(1);

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

 Reference types are arrays and objects


 String, int[], Baby, …

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

Baby dende1 = new Baby(“Dende”);


Baby dende2 = new Baby(“Dende”);

Does shiloh1 == shiloh2?

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.

public class Baby {


int numBabiesMade = 0;
Baby() {
numBabiesMade += 1;
}
}
54
static example
 Keep track of the number of babies that
have been made.

public class Baby {


static int numBabiesMade = 0;
Baby() {
numBabiesMade += 1;
}
}
55
static notes
 Non-static methods can reference static
methods, but not the other way around
 Why?
public class Baby {
String name = “DMX”;
static void whoami() {
System.out.println(name);
}
}
56
main
 Why is main static?

public static void main(String[] arguments)


{
}

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

Counter counter1 = new Counter();

60
Class Counter
Object counter1 Object counter2
ourCount = 0

myCount = 0 myCount = 0

Counter counter1 = new Counter();


Counter counter2 = new Counter();

61
Class Counter
Object counter1 Object counter2
ourCount = 0
1
myCount = 0 myCount = 0
1

Counter counter1 = new Counter();


Counter counter2 = new Counter();
counter1.increment();

62
Class Counter
Object counter1 Object counter2
ourCount = 0
1
2 myCount = 0 myCount = 0
1
2

Counter counter1 = new Counter();


Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
63
Class Counter
Object counter1 Object counter2
ourCount = 0
1
2 myCount = 0 myCount = 0
3 1 1
2

Counter counter1 = new Counter();


Counter counter2 = new Counter();
counter1.increment();
counter1.increment();
counter2.increment(); 64
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”;
}
}
65
Mr. MeanGuy

public class Malicious;


public static void main(String[] args){
maliciousMethod(new CreditCard());
}
static void maliciousMethod(CreditCard Card) {
card.expenses = 0;
System.out.println(card.cardNumber);
}
}

66
Public vs. Private
Public: others can use this
Private: only the class can use this

public/private applies to any


field or method

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

 Reuse classes to avoid extra work

 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

What if library expands?


86
ArrayList
 Modifiable list
 Internally implemented with arrays
 Features
 Get/put items by index
 Add items
 Delete items
 Loop over all items

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

You might also like