Docsity

Classes and Objects - Introduction to Programming in Java - Lecture Slides, Slides of Java Programming

Partial preview of the text

Download Classes and Objects - Introduction to Programming in Java - Lecture Slides and more Slides Java Programming in PDF only on Docsity!

Lecture 4

Classes and Objects

Review

Solutions 2

public static int getSecondMinIndex(int[] values) {

int secondIdx = -1;int minIdx= getMinIndex(values); for(int i=0; i<values.length; i++) {

if (i == minIdx)

continue; if (secondIdx == -1 ||

values[i] < values[secondIdx])^ secondIdx = i;

} return secondIdx; } •^ What happens if values = {0}? values = {0, 0}? values = {0,1}?

Popular Issues 1

•^ Array Index vs Array Value^ int[] values = {99, 100, 101};System.out.println(values[0] );

// 99

Values

Indexes

2 Docsity.com

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] } } }

Problem?

•^ What if

vals = {1,2,3}

•^ Set

min = Integer.MAX_VALUE

or

vals[0]Docsity.com

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

Debugging Notes 1

•^ Use System.out.println throughout your codeto 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]; } }

Docsity.com

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

Today’s Topics

Object oriented programming

Defining ClassesUsing ClassesReferences vs Values

Static types and methods

Object oriented programming

•^ Represent the real world

Baby

Object Oriented Programming

•^ Objects group together^ –

Primitives (int, double, char, etc..) – Objects (String, etc…)

Baby

String nameboolean isMaledouble weightdouble decibelsint numPoops

Why use classes?

•^ Why not just primitives?

// little baby alex String nameAlex;double weightAlex; // little baby david String nameDavid;double weightDavid;

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;double weightDavid2;

David2?Terrible

500 Babies?

That Sucks!

Docsity.com

Why use classes?

NameWeightSex… Baby