CSC 212 Object-Oriented Programming and Java Part 2

Preview:

Citation preview

CSC 212

Object-Oriented Object-Oriented Programming and JavaProgramming and Java

Part 2Part 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).

Student Class

public class Student {

// declare the fields

// define the constructors

// define the methods

}

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

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++; }

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++; }

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

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);}

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

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

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

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

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)

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.

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

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) + “]”;

}

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

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;

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.

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

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

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?

while vs. do-while loop

What is the advantage of one over the other?

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

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

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”);}

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

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;

}}

}

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;

}}

}

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

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)); }

}}

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

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.

Recommended