1 Review for Midterm 3 CS 101 Spring 2007. 2 Topic Coverage  Loops Chapter 4  Methods Chapter 5  Classes Chapter 6, Designing and creating classes.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS125 Exam Review Winter Some Exam Info Tuesday (22nd) at 4:00-6:30pm in the PAC CHECK YOUR SEAT!!! Read Final Exam Information on website –Practice.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CS 101E – Exam 2 Review Spring 2007 Michele Co. Announcements Review Session Tonight, 7/7:30 p.m., OLS 009 Will be announced via In-class Exam Wednesday.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Iteration. Java looping Options –while –do-while –for Allow programs to control how many times a statement list is executed.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Iteration Chapter 6 Fall 2005 CS 101 Aaron Bloomfield.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
OOP Basics Classes & Methods (c) IDMS/SQL News
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Arrays Chapter 7.
Java Primer 1: Types, Classes and Operators
Iteration.
Chapter 9 Inheritance and Polymorphism
Iteration.
Review for Midterm 3.
Review for Midterm 3.
Classes, Objects and Methods
Visibilities and Static-ness
Review for Midterm 3.
Presentation transcript:

1 Review for Midterm 3 CS 101 Spring 2007

2 Topic Coverage  Loops Chapter 4  Methods Chapter 5  Classes Chapter 6, Designing and creating classes Chapter 9, Static fields and methods, wrapper classes  Arrays Chapter 8

3 Classes Circle class

4 Circle class properties  What properties does a circle have? Radius PI = Color (if plotting in a graphics program) (x,y) location  These properties will become instance variables We are only going to play with the first two (radius and PI) in this example Thus, we are ignoring the color and location

5 Our Circle class public class Circle { double radius; double PI = ; } Note the fields are not static Note the radius field is not initialized by us We’re ignoring the public for now c Circle - radius = PI = … - … + …

6 Accessing our Circle object  Any variable or method in an object can be accessed by using a period The period means ‘follow the reference’ Example: System.in Example: System.out.println (c.radius); Example: c.PI = 4; This is bad – PI should have been declared final (this will be done later) c Circle - radius = PI = … - … + …

7 What’s the output? public class Circle { double radius; double PI = ; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (x); } }  When a variable is declared as part of a method, Java does not initialize it to a default value Java will give a “variable not initialized” error

8 What’s the output now? public class Circle { double radius; double PI = ; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (c.radius); } }  When a variable is declared as part of a class, Java does initialize it to a default value Java outputs 0.0!

9 What’s going on?  A (method) variable needs to be initialized before it is used Usually called a local variable  A instance variable is automatically initialized by Java All numbers are initialized to 0, booleans to false, etc.  This is a bit counter-intuitive…

10 Circle class behaviors  What do we want to do with (and to) our Circle class? Create circles Modify circles (mutators) Find out about our circles’ properties (accessors) Find the area of the circle Plot it on the screen (or printer) A few others…  These will be implemented as methods

11 Calling the Circle constructor  To create a Circle object: Circle c1 = new Circle();  This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with no parameters (the ‘default’ constructor)  The constructor is always the first method called when creating (or ‘constructing’) an object c1 Circle - radius = PI = … - … + Circle() + Circle (double r) + …

12 Calling the Circle constructor  To create a Circle object: Circle c1 = new Circle(2.0);  This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with 1 double parameters (the ‘specific’ constructor)  The constructor is always the first method called when creating (or ‘constructing’) an object c1 Circle - radius = PI = … - … + Circle() + Circle (double r) + …

13 Constructors  Remember, the purpose of the constructor is to initialize the instance variables PI is already set, so only radius needs setting public Circle() { this (1.0); } public Circle (double r) { radius = r; } Note there is no return type for constructors Note that the constructor name is the EXACT same as the class name Note that there are two “methods” with the same name!

14 What happens in memory  Consider: Circle c = new Circle();  A double takes up 8 bytes in memory  Thus, a Circle object takes up 16 bytes of memory As it contains two doubles c Circle - radius = PI = … + Circle() + Circle (double r) + … Circle - radius = PI = c Shorthand representation

15 Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); } }

16 What happens in memory  There are 4 Circle objects in memory Taking up a total of 4*16 = 64 bytes of memory Circle - radius = PI = c1 Circle - radius = PI = c2 Circle - radius = PI = c3 Circle - radius = PI = c4

17 Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); //... Circle c = new Circle(); } } This program creates 1 million Circle objects!

18 What happens in memory  There are 1 million Circle objects in memory Taking up a total of 1,000,000*16 ≈ 16 Mb of memory … Note that the final PI field is repeated 1 million times Circle - radius = PI = c1 Circle - radius = PI = c2 Circle - radius = PI = c

19 Total memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles) The use of static for fields  If a variable is static, then there is only ONE of that variable for ALL the objects That variable is shared by all the objects Total memory usage: 16 bytes (1+1=2 doubles) Total memory usage: 40 bytes (4+1=5 doubles) … Circle - radius = 1.0 c1 Circle - radius = 1.0 c2 c Circle - radius = 1.0 c3 c4 Circle - radius = 1.0 PI

20 More on static fields  What does the following print Note that PI is not final Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); c1.PI = 4.3; System.out.println (c2.PI);  It prints 4.3 Note you can refer to static fields by object.variable

21 Even more on static fields  There is only one copy of a static field no matter how many objects are declared in memory Even if there are zero objects declared! The one field is “common” to all the objects  Static variables are called class variables As there is one such variable for all the objects of the class Whereas non-static variables are called instance variables  Thus, you can refer to a static field by using the class name: Circle.PI

22 Even even more on static fields  This program also prints 4.3: Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); Circle.PI = 4.3; System.out.println (c2.PI);

23 Even even even more on static fields  We’ve seen static fields used with their class names: System.in(type: InputStream) System.out(type: OutputStream) Math.PI(type: double) Integer.MAX_VALUE(type: int)

24 What if we want the value of Pi?  Assume that PI is private, and that we need an getPi() method to get it’s value  Remember that is only 1 Pi field for all the Circle objects declared Even if there are none declared!  Consider a Circle object c: c.getRadius() directly accesses a specific object c.setRadius() directly modifies a specific object c.getPi() does not access a specific object c.setPi() (if there were such a method) does not modify a specific object  Methods that do not access or modify a specific object are called ‘class methods’

25 More on class methods  A class method does not care about any specific object Such as getPi()  It is declared as static: static double getPi () { return PI; }  Thus, they are often called static methods  Because Java knows that class methods don’t care about any specific object, it only allows them to access static variables (aka class variables)  Consider Math.sin() It doesn’t care about the ‘state’ of any object It only cares about the parameter passed in

26 static and non- static rules  Member/instance (i.e. non-static) fields and methods can ONLY be accessed by the object name  Class (i.e. static) fields and methods can be accessed by Either the class name or the object name  Non-static methods can refer to BOTH class (i.e. static) variables and member/instance (i.e. non-static) variables  Class (i.e. static) methods can ONLY access class (i.e. static) variables

27 Loops Chapter 4

28 Chapter 4: Iteration while loop syntax  While statements: while ( expression ) action Action is executed repeatedly while expression is true Once expression is false, program execution moves on to next statement Action can be a single statement or a block If expression is initially false, action is never executed

29 int valuesProcessed = 0; double valueSum = 0; // set up the input Scanner stdin = new Scanner (System.in); // prompt user for values System.out.println("Enter positive numbers 1 per line.\n" + "Indicate end of the list with a negative number."); // get first value double value = stdin.nextDouble(); // process values one-by-one while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble(); } // display result if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); } else { System.out.println("No list to average"); } Reading in values

30 Converting text to strictly lowercase public static void main(String[] args) { Scanner stdin = new Scanner (System.in); System.out.println("Enter input to be converted:"); String converted = ""; String currentLine = stdin.nextLine(); while (currentLine != null) { String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); currentLine = stdin.nextLine(); } System.out.println("\nConversion is:\n" + converted); }

31 Chapter 4: Iteration for loop syntax  For statements: for ( forinit; forexpression; forupdate ) action forinit is executed once only (before the loop starts the first time) Action is executed repeatedly while forexpression is true After action is executed at the end of each loop, forupdate is executed Once forexpression is false, program execution moves on to next statement Action can be a single statement or a block If expression is initially false, action is never executed

32 System.out.println("i is " + i); } System.out.println("all done"); System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 all done Execution Trace i 0 int i = 0;i < 3;++ifor () {int i = 0;i < 3;++i 123 Variable i has gone out of scope – it is local to the loop

33 for vs. while  An example when a for loop can be directly translated into a while loop: int count; for ( count = 0; count < 10; count++ ) { System.out.println (count); }  Translates to: int count; count = 0; while (count < 10) { System.out.println (count); count++; }

34 for vs. while  An example when a for loop CANNOT be directly translated into a while loop: for ( int count = 0; count < 10; count++ ) { System.out.println (count); }  Would (mostly) translate as: int count = 0; while (count < 10) { System.out.println (count); count++; } count IS defined here count is NOT defined here only difference

35 Chapter 4: Iteration Common pitfalls  Infinite loop: a loop whose test expression never evaluates to false  Be sure that your for loop starts and ends where you want it to For example, in an array of size n, it needs to start at 0 and end at n-1 Otherwise, it’s called an “off-by-one” error  Be sure your loop variable initialization is correct

36 Chapter 4: Iteration commands  break Immediately stops the execution of the current loop  continue Immediately starts execution of the next loop The for update is executed, then the condition is tested

37 Chapter 4: Iteration File access  Java provides the File class for file I/O Constructor takes in the file name as a String  A stream is a name for a input or output method System.out: output stream System.err: error output stream System.in: input stream File: file input or output stream  We are only concerned with the System.out printing methods in this course

38 Chapter 4: Iteration Scanner methods  The Scanner class can be initialized with an File object Scanner filein = new Scanner (new File (filename));  The Scanner class has a bunch of methods useful in loops: hasNextInt(): tells whether there is a next int hasNextDouble(): same idea, but with doubles  To retrieve a value from the Scanner: nextInt() nextDouble()

39 Classes Chapter 6

40 Variable scope rules public class Scope { int a; static int b; public void foo (int c) { int d = 0; System.out.println (c*d); int e = 0; } public void bar() { } int f; } a & b are visible anywhere within the class where is f visible? d is visible in the method after it is declared e is visible in the method after it is declared formal parameters are only visible in the method in which they are declared e is not visible here! what is visible here? local variables

41 Chapter 6: Methods and classes Instance methods vs. class methods  Instance (member) methods modify the state of the object That state can include instance (member) variables as well as class variables  Class methods do not modify the state of the object Examples: Math.sin(), Math.cos(), etc. Can only access class variables They are declared with the keyword static

42 Chapter 6: Methods and classes Instance variables vs. class variables  Instance (member) variables are one per object Can only be accessed by instance (member) methods  Class variables are one for the entire class The single class variable is common to all the objects of a class Can be accessed by both instance (member) methods and class methods

43 Chapter 6: Methods and classes Parameters  The values passed into the method call are called actual parameters foo (7); // 7 is the actual parameter  The parameter names within the method are called formal parameters void foo (int x ) {// x is the formal parameter  Java copies the values of the actual parameters to the formal parameters That copy is kept in a spot of memory called the “activation record” Any modifications in the method are modifications to the copy Note that if a object is passed in, the object’s reference is what is copied, not the object itself  Thus, the object can be modified, just not the reference

44 Chapter 6: Methods and classes Instance variables  Instance variables are normally declared private Modifications is through mutator methods Access is through accessor methods  Classes should use their own mutator/ accessor methods to change/access the fields of the class For mutators, it allows “checking” to be done when they are changed For accessors, it becomes more important when dealing with inheritance

45 Chapter 6: Methods and classes Blocks and scoping  A statement block is a number of statements within braces  A nested block is one block within another Note that the braces that enclose a class do not constitute a block!  A local variable is a variable defined within a block You can define as many local variables in each block as you want  However, there can’t be variables of the same name declared within the same block  Example: void public foo (int x) { double x = 0;

46 Chapter 6: Methods and classes Overloading  Method overloading is when there are multiple methods of the same name with different parameter lists Java will figure out which one you mean to call by which method’s parameter list best matches the actual parameters you supply

47 Chapter 6: Methods and classes Constructors and this  Keyword this references the object being operated within Is not valid within a class method, as you are not within an object! this, within the Circle class, getRadius() and this.getRadius() do the exact same thing  A constructor can invoke another constructor Needs to be at the beginning of the method  If you don’t provide any constructors, Java creates a default constructor for you This default constructor invokes the default constructor of the super class

48 Chapter 6: Methods and classes Specific methods and instances  All classes inherit certain methods, and should override them toString() clone() equals()  clone()’s return type must be Object  instanceof returns true if the object is an instance of the class Example: String s = “foo”; if ( s instanceof Object ) {

49 Chapter 6: Methods and classes equals()  equals() should have the following properties: Reflexivity: x.equals(x) should be true Symmetry: if x.equals(y) then y.equals(x) Transitivity: if x.equals(y) and y.equals(z) then x.equals(z) Consistency: x.equals(y) should always return the same value (provided x and y don’t change) Physicality: x.equals(null) should return false  You don’t have to remember the property names, though…

50 Arrays Chapter 8

51 Chapter 8: Arrays and collections Array basics  An array is an object Thus, it is actually a reference to a series of values somewhere in memory  The individual parts of an array are called elements Elements can be a primitive type or an object  All elements in the array must have the same type  An array is an object, with fields and methods The length is a field in the array object clone() is a method in the array object

52 Chapter 8: Arrays and collections Array declarations  There are two parts to creating an array Array declaration  int[] array;  This declared an uninitialized array reference! Array initialization  array = new int[10];  This creates an array of 10 ints each with value 0  Java gives default values to the elements: null, 0, or false  Can be combined int[] array = new int[10];  If declaring an array can declare specific elements: int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  Note that the int here could have been String, etc. If an object type, then the array holds references to those objects

53 More about how Java represents Arrays  Consider int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; a - b null cd int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c;

54 Chapter 8: Arrays and collections Array access  Retrieving a particular element from an array is called subscripting or indexing  Value passed in square brackets Can be any non-negative int expression  Java checks to see if you go past the end of an array IndexOutOfBounds exception is generated

55 Chapter 8: Arrays and collections Array size  Arrays can not be resized Use a Vector if you need to resize your collection  Array length is via the length field It’s public final, so it can’t be changed  Arrays are indexed from 0 So there are elements 0 to array.length-1

56 Chapter 8: Arrays and collections Array miscellaneous  The clone() method creates a shallow copy The references are copied The objects themselves are not duplicated  When passed as a parameter, the reference to the array is what is passed An array is an object, thus acts like other objects with respect to parameter passing  Java’s main method takes in an array: public static void main (String[] args) This array is the command line parameters, if any  The Collections class provides a number of useful methods for arrays and other collections (such as Vectors)

57 Chapter 8: Arrays and collections Sorting and such  A sort puts the elements of an array in a particular order  Selection sort is one method discussed Algorithm:  Select the smallest element, put it first  Then select the second smallest element, and put it second  Etc If there are n elements in the array, it requires n 2 comparisons  There are more efficient array sorting methods out there

58 Multidimensional array visualization  Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}};  Produces ragged array

59 Multidimensional array visualization  A multi-dimensional array declaration (either one): int[][] m = new int[3][4];  How we visualize it: or

60 Chapter 8: Arrays and collections Not on the exam  Collection interface