33
CSC 212 Object-Oriented Object-Oriented Programming and Java Programming and Java Part 2 Part 2

CSC 212 Object-Oriented Programming and Java Part 2

Embed Size (px)

Citation preview

Page 1: CSC 212 Object-Oriented Programming and Java Part 2

CSC 212

Object-Oriented Object-Oriented Programming and JavaProgramming and Java

Part 2Part 2

Page 2: CSC 212 Object-Oriented Programming and Java Part 2

Announcements

The end of the Java refresher is nigh! If you need more of a review, seek assistance immediately.

I have a cool office. Please drop by and see so for yourself (and ask me questions while you are there).

Page 3: CSC 212 Object-Oriented Programming and Java Part 2

Student Class

public class Student {

// declare the fields

// define the constructors

// define the methods

}

Page 4: CSC 212 Object-Oriented Programming and Java Part 2

The Student Variables

public class Student { protected String name, studentID; protected int years_attended; private float gpa, credits; protected static int total_enrollment; // define the constructors

// define the methods

} // end of class definition

Page 5: CSC 212 Object-Oriented Programming and Java Part 2

Constructors for StudentConstructors are special methods which create instances. Typically initialize fields values.(They can do more–later)

public Student (String sname, long ssn) { name = sname; studentID = Long.toString(ssn); years_attended = 0; gpa = credits = 0; total_enrollment = total_enrollment++; }

Page 6: CSC 212 Object-Oriented Programming and Java Part 2

Additional Constructors Classes can have several constructors

Must differ in parameter lists (signatures).

public Student (String sname, String id) { name = sname; studentID = id; years_attended = 0; gpa = credits = 0; total_enrollment++; }

public Student () { name = “J Doe”; studentID = “none”; years_attended = 0; gpa = credits = 0; total_enrollment++; }

Page 7: CSC 212 Object-Oriented Programming and Java Part 2

The Student Class public class Student {

protected String name, studentID;

protected int years_attended;

private float gpa;

protected static int total_enrollment;

public Student(String sname, long ssn)

{ …}

public Student(String sname, String id)

{ …}

public Student()

{ …}

// define the methods

} // end of class definition

Page 8: CSC 212 Object-Oriented Programming and Java Part 2

public void setId(String newId) {

studentID = newId;}

Set and Get Methods

Provide set and get methods for each fieldControlling access to fieldsLimits errors and problems (or amount

of searching when debugging) Common design pattern

public String getId() { return(studentID);}

Page 9: CSC 212 Object-Oriented Programming and Java Part 2

Rules of Thumb

Classes are public Fields are private

Outside access only using “get” and “set” methods

Constructors are public Get and set methods (if any) are public Other methods on a case-by-case basis

Page 10: CSC 212 Object-Oriented Programming and Java Part 2

Naming Conventions

Variables start with a lower case letterWhen name includes multiple words, combine

words and use intermediate caps int xLoc, yLoc;char choice;

Classes begin with an upper case letterString strVal;Car bob;

No name can match a Java keyword

Page 11: CSC 212 Object-Oriented Programming and Java Part 2

Things to Remember

{ } delimit logical blocks of statements

Two ways to define comments/* up to */ defines a block comment// defines a single line comment

Java is case-sensitiveout, Out, OUt, OUT are all different

Page 12: CSC 212 Object-Oriented Programming and Java Part 2

Primitive Types

Name Type Range Default

boolean

boolean true or false False

char characters any character

\0

int integer -231 – 231-1 0

long long integer -263 – 263-1 0

float real -3.4E38 – 3.4E38

0.0

double extended real

-1.7E308 – 1.7E308

0.0

Page 13: CSC 212 Object-Oriented Programming and Java Part 2

Java Operators

++ unary increment (k++ k = k + 1) -- unary decrement (k-- k = k-1) ! logical negation (!done) % remainder == != primitive equality/inequality test && logical and (done && valid) || logical or (done || flag) = assignment (x = a && b)

Page 14: CSC 212 Object-Oriented Programming and Java Part 2

Strings

String is used like a primitive, but really is a class

For example, one can create a string by:

String s = "This is a Java string"; Strings are stored as zero or more

Unicode characters.

Page 15: CSC 212 Object-Oriented Programming and Java Part 2

String Operators

Basic string operator is concatenation (+) Concatenation joins two strings together:

“Strings ” + “joined” “Strings joined” Numbers can be converted back and forth

with strings: int x = Integer.parseInt(“32”); x 32

float y = Float.parseFloat(“7.69”); y 7.69

Page 16: CSC 212 Object-Oriented Programming and Java Part 2

toString() Methods

Generates representations of objectsNot required, but really useful debugging toolFor example, the Student class could define:

public String toString() { return “[Student ” + name + “; ” +

studentID + “; GPA=” + Float.toString(gpa) + “]”;

}

Page 17: CSC 212 Object-Oriented Programming and Java Part 2

Arrays

Store fixed number of elements of the same type“length” field contains size of array

Student [] roommates = new Student[3];roommates[0] = new Student(“Al”,1000);roommates[1] = new Student(“Bob”,1050);roommates[2] = new Student(“Carl”, 2000);String name_list = " ";for (int n=0; n<roommates.length; n++) name_list = name_list + roommates[n].getName ()+ ";";

int[] numbers = {1, 2, 3}; // initialized with length 3; numbers[2] == 3float[][] reals = new float[8][10]; // reals is an array of float arrays

Page 18: CSC 212 Object-Oriented Programming and Java Part 2

Static members

Methods & fields can be declared static Static field is shared by all class objects

All objects see the same value Static methods and fields can be used

without creating an instance of the class with the new command.E.g., ClassName.staticMethod(); or

x = ClassName.staticField;

Page 19: CSC 212 Object-Oriented Programming and Java Part 2

Static members

Static methods cannot refer to non-static members of the same class directly.Like non-class objects, must specify which

instance of the class they are referring. Using non-static method or field inside a

static method is a common compiler error:Error: Can't make static reference to method

void print() in class test.

Page 20: CSC 212 Object-Oriented Programming and Java Part 2

if -- else if -- else if -- … -- elseif (a == b) { ...} else if (a < b) { ...} else { ...} Only boolean tests are allowed At most 1 branch followed

Page 21: CSC 212 Object-Oriented Programming and Java Part 2

while loop

while (v != b) {…

} Only boolean tests are legal Test occurs before loop is entered Loop continues until while test is false

“while (true) { }” loops forever“while (false) {}” never executes code in loop

Page 22: CSC 212 Object-Oriented Programming and Java Part 2

do – while loop

do { …} while (b < m); do-while performs test after the loop Guarantees loop executed at least

once Block bracing (“{“ & “}”) is required

Why?

Page 23: CSC 212 Object-Oriented Programming and Java Part 2

while vs. do-while loop

What is the advantage of one over the other?

Page 24: CSC 212 Object-Oriented Programming and Java Part 2

for loop

Just a while loop with aspirations Typical use: iterate (loop) over set of

instances for (initialization; test; modification)

{ block of code}

Executed before starting loop

Examined before every iteration

Executed after each pass through loop

Page 25: CSC 212 Object-Oriented Programming and Java Part 2

switch statements

int x = …;switch (x) { case 0: System.out.println(“x is 0”); break; case 1: System.out.println(“x is 1”); break; default: System.out.println(“x is not 0 or 1”);} Execution starts at first matching case

Stops at first break statement

Page 26: CSC 212 Object-Oriented Programming and Java Part 2

What will this code do?

int x = 0;…switch (x) { case 0: System.out.println(“x is 0”); case 1: System.out.println(“x is 1”); break; default: System.out.println(“x is not 0 or

1”);}

Page 27: CSC 212 Object-Oriented Programming and Java Part 2

Explicit Control of Execution

break [<label>] Exit from any block Can exit multiple blocks using

<label> form Unlabeled - terminate innermost Labeled - terminate the appropriate

block

Page 28: CSC 212 Object-Oriented Programming and Java Part 2

What will this code do?

outer: for (int i = 0; i < 10; i++) {

inner:for (int j = 0; j < I; j++) {

if (j == 5) {System.out.println(“i is ” + Integer.toString(i) + “and j

is ” + Integer.toString(j));break;

}}

}

Page 29: CSC 212 Object-Oriented Programming and Java Part 2

What will this code do?

outer: for (int i = 0; i < 10; i++) {

inner:for (int j = 0; j < I; j++) {

if (j == 5) {System.out.println(“i is ” + Integer.toString(i) + “and j

is ” + Integer.toString(j));break outer;

}}

}

Page 30: CSC 212 Object-Oriented Programming and Java Part 2

Explicit Control of Execution

continue [<label>] Skip to end of loop body; evaluate loop

control conditional Can exit multiple levels using <label>

form Only in while, do-while, & for loops Unlabeled - continue innermost loop Labeled - continue to an outer loop

Page 31: CSC 212 Object-Oriented Programming and Java Part 2

What will this code do?

outer: for (int i = 0; i < 10; i++) { inner: for (int j = 0; j < I; j++) { if (j + 2 == i) {

if (j == 5) continue inner;else System.out.println(“i is ” + Integer.toString(i) + “and j is ” +

Integer.toString(j)); }

}}

Page 32: CSC 212 Object-Oriented Programming and Java Part 2

Explicit Control of Execution

return [<expression>]; terminate execution and return to

invoker It is illegal in Java to have code after

a return statement!But only if the code can only be exected

after the return statement

Page 33: CSC 212 Object-Oriented Programming and Java Part 2

Daily Quiz

Do problem R-1.13 from the book (p. 52)

Write a Java function that takes an integer n and returns the sum of all odd integers smaller than n.