Compsc sci 201 201 Classe sses, s, Arrays, s, A APIs State - - PowerPoint PPT Presentation

compsc sci 201 201 classe sses s arrays s a apis
SMART_READER_LITE
LIVE PREVIEW

Compsc sci 201 201 Classe sses, s, Arrays, s, A APIs State - - PowerPoint PPT Presentation

Compsc sci 201 201 Classe sses, s, Arrays, s, A APIs State Constructor Susan Rodger January 17, 2020 Methods (behavior) 1/17/2020 Compsci 201, Spring 2020 1 Be in the know Add yourself elf t to compsci@ ci@duk uke.edu


slide-1
SLIDE 1

Compsc sci 201 201 Classe sses, s, Arrays, s, A APIs

1/17/2020 Compsci 201, Spring 2020 1

Susan Rodger January 17, 2020

State Constructor Methods (behavior)

slide-2
SLIDE 2

Be in the know …

  • Add yourself

elf t to compsci@ ci@duk uke.edu

  • Duke University mailing lists – add yourself

https://lists.duke.edu/sympa

  • Compsci related events, jobs, research
  • pportunities
  • Appl

Apply fo for Dat ata+, CS+, Code+ e+

  • summer research at Duke, paid, hire lots of 1st

year students, 2cd year, etc.

  • Apply in January!

https://www.cs.duke.edu/undergrad/summer_research

1/17/2020 Compsci 201, Spring 2020 2

slide-3
SLIDE 3

C is for …

  • Class
  • Framework for creating objects
  • Collections and Collection
  • See java.util.* for details
  • Collaboration
  • Review the policy

1/17/2020 Compsci 201, Spring 2020 3

slide-4
SLIDE 4

Plan for the Day

  • Revie

iew Obj bject t concept: t: c classes, P P0

  • What is a class, object, instance variable
  • Revie

iew arrays in J Java: m meth thods ds and c d concepts ts

  • Required for APTs due next week
  • Move toward ArrayList and other collections
  • Codin

ing a and h d helpe lper f functio tions

  • Efficient programming and not efficient programs

1/17/2020 Compsci 201, Spring 2020 4

slide-5
SLIDE 5

Strings: Example from last time

  • You

u can an’t m modif ify a a string, alw always crea eate ne new S String

String s = new String(“joy"); String t = s; s = t + t; // contents of boxes the same

1/15/2020 Compsci 201, Spring 2020 5

slide-6
SLIDE 6

Class

  • Adject

ctiv ive, n noun, c n, close t to a verb

  • Show some ___ you're in a great ___, that's a

___ act, let's ___-ify that

  • Fundam

ament ental p al part o

  • f object

ct-ori riented p pro rogra grammi mming

  • All Java code is in a class, alas the primitives
  • In Python int is a class, has no upper bound
  • In Java int is a primitive, 231-1 maximal value

1/17/2020 Compsci 201, Spring 2020 9

slide-7
SLIDE 7

Class encapsulates state and behavior

  • Class i

is a templa late, o , object ect h has c char aract cter eris istics ics

  • Dogs have fur, speed, temperament, size, …
  • Typic

icall lly w we e don’t us use ex exam amples lik like t thi his, b but ut t the hey can an help help b build uild int intuition and and und understanding

  • Class dog, retriever extends dog, method bark()

1/17/2020 Compsci 201, Spring 2020 10

slide-8
SLIDE 8

Class and Object

  • If w

we e had had a R a Retriever class we c e coul uld instant ntia iate a an instance nce o

  • f the c

e class, i. , i.e., ., c create a e an o

  • bject

ct

Retriever ks = new Retriever("kelsey");

  • Cla

lass is is an an object f t factory, c , calling ling new create tes a s a ne new o

  • bjec

ect t tha hat is is an an ins instance o

  • f the

he c cla lass

  • We could call a method: ks.bark()

1/17/2020 Compsci 201, Spring 2020 11

slide-9
SLIDE 9

Classes in Java

  • Define class Foo in

Foo.java

  • Create object by calling

new Foo(..)

  • Access object by calling

methods:

  • bj.doSomething()
  • Some methods return a

value, use it!

1/17/2020 Compsci 201, Spring 2020 12

State Constructor Methods (behavior)

slide-10
SLIDE 10

Classes in Java

  • State: instance

variables: private

  • Constru

ructors rs: initialize instance variables

  • Met

etho hods: functions aka behavior

  • Docum

ument entatio ion: Javadoc and other comments

1/17/2020 Compsci 201, Spring 2020 13

slide-11
SLIDE 11

Work-Flow for Assignments

  • Wha

hat is is the he work-flo low f for P0 and A Assig ignm nment nts?

  • Login to gitlab
  • Code URL to P0 in gitlab
  • Fork it (makes a copy in the cloud)
  • Clone with ssh

1/17/2020 Compsci 201, Spring 2020 15

slide-12
SLIDE 12

Using a shell

  • Place t

ace to type s shell c ell command nds

  • On

n Mac ac us use T Ter erminal, W Wind indows us use B e Bash G Git it

  • Wha

hat is is thi his?

  • It’s a

a pat ath: h:

  • Folder named IdeaProjects
  • Folder named spring20

– May have other folders inside it

  • $

$ is is a p a prompt, rea eady for a s a shel hell co command

1/17/2020 Compsci 201, Spring 2020 16

slide-13
SLIDE 13

A few shell commands

  • pw

pwd – di displ play c current pa path

  • cd

d – cha hang nge i e into m main f n folder er/dir irect ectory

  • cd nam

name

  • - cha

hange int into f fold lder nam named nam name

  • cd ..

.. – cha hang nge e back i into p parent nt f folder

  • ls

ls

  • sho

how f file iles in in cur current f fold lder

  • Let’s s

see s some o

  • f those…

e….

1/17/2020 Compsci 201, Spring 2020 18

slide-14
SLIDE 14

Back to Work-Flow for Assignments

  • Clone

ne wit ith h ssh sh

  • Go
  • to
  • you
  • ur s

shell

  • cd (to folder you want to put your P0 in)
  • git clone (SSH URL you copied)
  • ls (will show your files)
  • Using

ng I IntelliJ elliJ c comple lete t the as assig ignm nment nt

  • Save code often to gitlab!

1/17/2020 Compsci 201, Spring 2020 19

slide-15
SLIDE 15

Work-Flow for Assignments (cont)

  • Send

d code de b back k to to gitl itlab (DO O OFTEN)

  • cd ( into project folder)
  • git add .
  • Puts code in staging area, tells git you want to update
  • git commit –m “comment on what you did”
  • Changes are recorded in local repo
  • git push
  • Uploads the changes to your gitlab repo
  • No

Now t w to Gradesc scop

  • pe and s

d submit bmit project ect

  • Don’t like results - fix code, push code, run on

Gradescope again

1/17/2020 Compsci 201, Spring 2020 20

slide-16
SLIDE 16

Classes and P0

  • How many

any P Per erson o

  • bjec

ects c created?

  • Each has a name and an age, different for each
  • instance. Thus: instance variables

1/17/2020 Compsci 201, Spring 2020 22

slide-17
SLIDE 17

Classes and P0

  • How many Person o
  • bjects cr

created?

  • Each has a name and an age, different for each
  • instance. Thus: instance variables
  • To cr

create? Call ne new w whi hich inv nvokes a a co constructor

  • No return type, initialize instance variables
  • Acces

ccess l level els: p private o e only w withi hin c n class, p public f c from

  • ther

her c classes es

  • Technically there is a package access, we ignore

1/17/2020 Compsci 201, Spring 2020 23

slide-18
SLIDE 18

1/17/2020 Compsci 201, Spring 2020 24

slide-19
SLIDE 19

Constructor

  • Sam

ame nam name a as c cla lass

  • No return type
  • Overlo

load ad with d differ erent ent p parameters

  • Each should initialize all instance variables
  • Fac

actor o

  • ut

ut c common co code int into help helper m method if if leng lengthy

  • Can call another constructor using this(…)

1/17/2020 Compsci 201, Spring 2020 25

slide-20
SLIDE 20

What is this?

  • An object

ct i instanc ance r ref efer ers t to itself elf

  • Method or constructor: object references itself
  • Every reference to an instance variable myVar

could be written as this.myVar

  • Code f

e for a an object ct t to pass i itself elf:

  • callMethod(this,"hello");
  • Construct

uctor c can c n call o ll other er construc uctor

  • this("hello");

1/17/2020 Compsci 201, Spring 2020 26

slide-21
SLIDE 21

Running a Java Program

  • On

n lap laptop/desktop la laun unch/run p point int is is t the m he main ain method in in any any c cla lass

  • Driver programs in P0, runs/drives the code
  • Method signature requir

uired to run program

1/17/2020 Compsci 201, Spring 2020 27

slide-22
SLIDE 22

WOTO (3 minutes)

http:// //bi bit.ly/2 /201spr pring20-01 0117 17-1

1/17/2020 Compsci 201, Spring 2020 28

slide-23
SLIDE 23

Luis von Ahn

  • Duke 2000, Math
  • Duke Honorary Degree 2017
  • CEO Duolingo
  • Macarthur Award, 2006
  • MIT-Lemelson Prize, 2018

1/17/2020 Compsci 201, Spring 2020 29

“It’s amazing how motivating it is to sit with somebody and say, ‘What you’re doing is really important.’ I use that a lot.”

slide-24
SLIDE 24

Arrays, APTs, and APIs

  • Why

hy is is alli alliteration im important in in writ iting?

  • Why are t

thes ese i e important nt i in program amming ing?

  • APIs c

crea eate p e possib ibilit ilitie ies

1/17/2020 Compsci 201, Spring 2020 30

slide-25
SLIDE 25

Array Details

  • Once a

ce array c created, it' t's siz ize i e is fixed, c can' n't g grow!

  • Indexable elements can be changed
  • Using

g a[k] we can r n read/w /writ ite va values ues

  • Instance variable a.length is size of array
  • No parentheses, hence not a method
  • Notice dot notation: object dot name

1/17/2020 Compsci 201, Spring 2020 31

slide-26
SLIDE 26

Indexing for loops and arrays

  • Constr

tructin ting and i d initi itiali lizing … … int[] a = new int[100]; for(int k=0; k < a.length; k += 1){ a[k] = 99; }

  • Let an A

n API-call ll f fill i ll in array: y: java.util.Arrays

  • Arrays.fill(a,99);
  • https://docs.oracle.com/en/java/javase/11/docs/api/

java.base/java/util/Arrays.html

1/17/2020 Compsci 201, Spring 2020 32

slide-27
SLIDE 27

For each loops and arrays

  • For each l

loop: no no ind ndex, no no cha changing w wha hat’s s stored int[] a = {1,2,3,4,5,6,7,8,9,10}; int sum1 = 0; int sum2 = 0; for(int k=0; k < a.length; k += 1){ sum1 += a[k]; } for(int value : a){ sum2 += value; } System.out.println(sum1 == sum2);

1/17/2020 Compsci 201, Spring 2020 33

slide-28
SLIDE 28

For Loop Summary

  • for(init; boolean guard; update) {…}
  • for(int k=0; k < a.length; k+=1) {…}
  • Initialization happens once, bef

efore g e guard check ecked ed f for t the f first t time, n , never er ag again ain

  • Initialization can introduce variables: loop
  • op s

scop

  • pe
  • Guard checked, if true loop body executes
  • After loop body, update executes, guard

checked

1/17/2020 Compsci 201, Spring 2020 34

slide-29
SLIDE 29

Control Construct Summary

  • if (boolean) {…}
  • Block executed when guard is true
  • {.} not needed for single statement, use anyway
  • if (boolean) {…} else {…}
  • Code in else block when negation true
  • while(boolean) {…}
  • Check boolean guard, execute body, repeat
  • Guard checked again after body executed

1/17/2020 Compsci 201, Spring 2020 35

slide-30
SLIDE 30

From Control to APIs

  • Lis

ist and and Arra rrayList simila ilar t to arr rray, b but …. ….

  • Grow as needed, can't use [k] to access
  • Powerful APIs, e.g., as follows

1/17/2020 Compsci 201, Spring 2020 36

slide-31
SLIDE 31

Solving an APT Together

  • Totalit

ality ( (see A APT pag age o e on course s e site) http:/ ://www.cs.d .duk uke.e .edu/ u/cs csed ed/ne newapt/t /totalit ality.ht html

  • Solve

e by h hand nd: : a = = { {20,30,40, ,30,40,50,60} 50,60} stype pe=“odd dd”

  • Use w

e wha hat y you u kno now, b but ut im implement in in Java

  • Che

heck id idea eas us using jshell ll (Java 9 9 and and la later)

  • Command line is your friend!

1/17/2020 Compsci 201, Spring 2020 38

slide-32
SLIDE 32

Think Before You Code

  • Solve b

e by hand nd … … Che heck ck y your understand anding ing o

  • f

ex exam amples … thi hink ab about ut s solution you’ u’ll w l writ ite ... ...

  • Then think before fingers on keys

1/17/2020 Compsci 201, Spring 2020 39

slide-33
SLIDE 33

Coding Interlude

  • Working

ing on Totalit ality APT i in I IntelliJ lliJ

  • Odd? Even?
  • Control: if, if-else, …

1/17/2020 Compsci 201, Spring 2020 40

slide-34
SLIDE 34

WOTO (3 minutes)

http:/ ://b /bit.l .ly/ y/20 201s 1spring20 20-01 0117 17-2

1/17/2020 Compsci 201, Spring 2020 41

slide-35
SLIDE 35

Josh Bloch

  • Led desig

ign o n of Java C a Collec lectio ions ns Frame mework rk

  • Former

erly J Java C a Chie ief A Archit chitec ect at at G Google le

  • Professor o
  • f the P

he Prac actice C CMU

1/17/2020 Compsci 201, Spring 2020 42

APIs should be easy to use and hard to misuse. It should be easy to do simple things; possible to do complex things; and impossible, or at least difficult, to do wrong things.

slide-36
SLIDE 36

Visualizations Help Understanding?

  • Javatutor to visua

uali lize c e code: : http:/ ://pytho hont ntut utor.co com/java. a.ht html

  • Using the java.awt.Color class
  • Both String and Color are immut

utab able le

  • Once created, cannot every change

1/17/2020 Compsci 201, Spring 2020 43

slide-37
SLIDE 37

Summary of Java-isms

  • Loop us

usin ing ind indexes o

  • ver

er an an ar array

  • The for-loop: initialize; guard/check; update
  • Totality: lo

loop over er o

  • dd ind

index exes o

  • nl

nly?

  • In some cases, …
  • How do we check

eck f for String ing e equalit lity?

  • .equals compared to ==
  • How

w do do we subm bmit a an APT APT?

  • Test, Grade, REFLECT
  • APTS – one grace day, NO LATE AFTER THAT

1/17/2020 Compsci 201, Spring 2020 44