Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 212 Object-Oriented Programming and Java Part 2.

Similar presentations


Presentation on theme: "CSC 212 Object-Oriented Programming and Java Part 2."— Presentation transcript:

1 CSC 212 Object-Oriented Programming and Java Part 2

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

3 Student Class public class Student { // declare the fields // define the constructors // define the methods }

4 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

5 Constructors for Student Constructors 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++; }

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

7 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

8 public void setId(String newId) { studentID = newId; } Set and Get Methods Provide set and get methods for each field  Controlling access to fields  Limits errors and problems (or amount of searching when debugging)  Common design pattern public String getId() { return(studentID); }

9 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

10 Naming Conventions Variables start with a lower case letter  When name includes multiple words, combine words and use intermediate caps  int xLoc, yLoc;  char choice; Classes begin with an upper case letter  String strVal;  Car bob; No name can match a Java keyword

11 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-sensitive  out, Out, OUt, OUT are all different

12 Primitive Types NameTypeRangeDefault boolean true or falseFalse charcharactersany character\0 intinteger-2 31 – 2 31 -10 longlong integer-2 63 – 2 63 -10 floatreal-3.4E38 – 3.4E38 0.0 doubleextended real-1.7E308 – 1.7E308 0.0

13 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)

14 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.

15 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

16 toString() Methods Generates representations of objects  Not required, but really useful debugging tool  For example, the Student class could define: public String toString() { return “[Student ” + name + “; ” + studentID + “; GPA=” + Float.toString(gpa) + “]”; }

17 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] == 3 float[][] reals = new float[8][10]; // reals is an array of float arrays

18 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;

19 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.

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

21 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

22 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?

23 while vs. do-while loop What is the advantage of one over the other?

24 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

25 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

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

27 Explicit Control of Execution break [ ] Exit from any block Can exit multiple blocks using form Unlabeled - terminate innermost Labeled - terminate the appropriate block

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

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

30 Explicit Control of Execution continue [ ] Skip to end of loop body; evaluate loop control conditional Can exit multiple levels using form Only in while, do-while, & for loops Unlabeled - continue innermost loop Labeled - continue to an outer loop

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

32 Explicit Control of Execution return [ ]; 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

33 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.


Download ppt "CSC 212 Object-Oriented Programming and Java Part 2."

Similar presentations


Ads by Google