Presentation is loading. Please wait.

Presentation is loading. Please wait.

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Strings, Parameters Lecture 6, Mon Jan 18.

Similar presentations


Presentation on theme: "University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Strings, Parameters Lecture 6, Mon Jan 18."— Presentation transcript:

1 University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Strings, Parameters Lecture 6, Mon Jan 18 2010 http://www.cs.ubc.ca/~tmm/courses/111-10 borrowing from slides by Kurt Eiselt

2 2 News n CS dept announcements n Undergraduate Summer Research Award (USRA) n applications due Feb 26 n see Guiliana for more details

3 3 Department of Computer Science Undergraduate Events Events this week Drop-in Resume/Cover Letter Editing Date: Tues., Jan 19 Time: 12:30 – 2 pm Location: Rm 255, ICICS/CS Bldg. Interview Skills Workshop Date: Thurs., Jan 21 Time: 12:30 – 2 pm Location: DMP 201 Registration: Email dianejoh@cs.ubc.ca Project Management Workshop Speaker: David Hunter (ex-VP, SAP) Date: Thurs., Jan 21 Time: 5:30 – 7 pm Location: DMP 110 CSSS Laser Tag Date: Sun., Jan 24 Time: 7 – 9 pm Location: Planet Laser @ 100 Braid St., New Westminster Event next week Public Speaking 101 Date: Mon., Jan 25 Time: 5 – 6 pm Location: DMP 101

4 4 Resources n Demco Learning Center: drop by if you have any questions! n ICICS/CS x150 n Normal schedule starts today n 10 am - 6 pm M-Th, 10 am - 4 pm F n Staffed by TAs from all 1st year courses, see schedule at http://www.cs.ubc.ca/ugrad/current/resources/cslearning.shtml

5 5 More Resources n WebCT discussion groups n Monitored by TAs/instructor, use to ask questions n don’t forget to check web page first/often! n lecture slides, handouts, schedule, links,.... n http://www.cs.ubc.ca/~tmm/courses/111-10 http://www.cs.ubc.ca/~tmm/courses/111-10

6 6 Yet More Resources n reminder: my office hours Mondays 4-5pm, starting today n office location is X661 (tall wing of ICICS/CS bldg) this elevator to X6 me! Xwing entrances facing Dempster

7 7 Followup n Q: identifiers - what about “.”? n System.out.println(“hey, what’s the story?”); n A: not allowed in simple identifiers n qualified identifiers: sequence of simple identifiers, separated by “.” n stay tuned for more on scope, namespace and packages

8 8 Reading This Week n Rest of Chap 2 n 2.3-4, 2.6-2.10 n Rest of Chap 4 n 4.3-4.7

9 9 Recap: Declaration and Assignment n Variable declaration is instruction to compiler n reserve block of main memory large enough to store data type specified in declaration n Variable name is specified by identifier n Syntax: n typeName variableName; n typeName variableName = value; n can declare and assign in one step n Java first computes value on right side n Then assigns value to variable given on left side x = 4 + 7;

10 10 Recap: Assignment Statements n Here’s an occasional point of confusion: n Draw and fill in boxes for your variables at each time step if you’re confused a = 7; // what’s in a? b = a; // what’s in b? // what’s in a now??? System.out.println(“a is “ + a + “b is “ +b); a = 8; System.out.println(“a is “ + a + “b is “ +b);

11 11 Recap: Expressions n expression is combination of n one or more operators and operands n operator examples: +, *, /,... n operand examples: numbers, variables,... n precedence: multiply/divide higher than add/subtract

12 12 Recap: Converting Between Types n Doubles can simply be assigned ints n double socks = 1; n ints are subset of doubles n Casting: convert from one type to another with information loss n Converting from real to integer n int shoes = (int) 1.5; n Truncation: fractional part thrown away n int shoes = (int) 1.75; n Rounding: must be done explicitly n shoes = Math.round(1.99);

13 13 Recap: Primitive Data Types: Numbers n Primary primitives are int and double n three other integer types n one other real type TypeSizeMinMax byte 1 byte-128127 short 2 bytes-32,76832,767 int 4 bytes-2,147,483,6482,147,483,647 long 8 bytes -9,223,372,036,854,775,8089,223,372,036,854,775,807 float 4 bytes approx -3.4E38 (7 sig.digits)approx 3.4E38 (7 sig.digits) double 8 bytes approx -1.7E308 (15 sig. digits) approx 1.7E308 (15 sig. digits)

14 14 Recap: Primitives: Non-numeric n Character type n named char n Java uses the Unicode character set so each char occupies 2 bytes of memory. n Boolean type n named boolean n variables of type boolean have only two valid values n true and false n often represents whether particular condition is true n more generally represents any data that has two states n yes/no, on/off

15 15 Recap: Constants n Things that do not vary n unlike variables n will never change n Syntax: n final typeName variableName; n final typeName variableName = value; n Constant names in all upper case n Java convention, not compiler/syntax requirement

16 16 Recap: Avoiding Magic Numbers n magic numbers: numeric constants directly in code n almost always bad idea! n hard to understand code n hard to make changes n typos possible n use constants instead

17 17 Programming n Programming is all about specifiying n data that is to be manipulated or acted upon n operations that can act upon data n order in which operations are applied to data n So far: specify data using primitive data types n come with pre-defined operations like +, -, *, and /

18 18 Programming with Classes n What if data we want to work with is more complex these few primitive data types?

19 19 Programming with Classes n What if data we want to work with is more complex these few primitive data types? n We can make our own data type: create a class n specifies nature of data we want to work with n operations that can be performed on that kind of data n Operations defined within a class called methods

20 20 Programming with Classes n Can have multiple variables of primitive types (int, double) n each has different name n each can have a different value int x = 5; int y = 17; n Similar for classes: can have multiple instances of class String n each has different name n each can have different value String name = “Tamara Munzner”; String computerName = “pangolin”;

21 21 Programming with Objects n Object: specific instance of a class n Classes are templates for objects n programmers define classes n objects created from classes

22 22 Object Example public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String (“Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

23 23 Object Example n Declare two different String objects n one called firstname and one called lastname public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String ("Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

24 24 Object Example n Variable declaration does not create objects ! public class StringTest { public static void main (String[] args) { String firstname; String lastname;

25 25 Object Example n Variable declaration does not create objects! n just tells compiler to set aside spaces in memory with these names n Spaces will not actually hold the whole objects n will hold references: pointers to or addresses of objects n objects themselves will be somewhere else in memory public class StringTest { public static void main (String[] args) { String firstname; String lastname;

26 26 Object Example n So firstname and lastname will not contain String objects n contain references to String objects public class StringTest { public static void main (String[] args) { String firstname; String lastname; public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String ("Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

27 27 Constructors n Constructor: method with same name as class n always used with new n actually creates object n typically initializes with data firstname = new String (“Kermit");

28 28 Object Example n Now create new instance of the String class n String object with data “Kermit” n Puts object somewhere in memory n puts address of the object’s location in firstname: firstname holds reference to String object with data “Kermit” public class StringTest { public static void main (String[] args) { String firstname; String lastname; public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String (“Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

29 29 Object Example n New operator and String constructor method instantiate (create) new instance of String class (a new String object) public class StringTest { public static void main (String[] args) { String firstname; String lastname; public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String (“Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

30 30 Object Example firstname

31 31 Object Example firstname String object “Kermit” expression on right side of assignment operator

32 32 Object Example firstname String object “Kermit” bind variable to expression on right side of assignment operator

33 33 Object Example n And so on public class StringTest { public static void main (String[] args) { String firstname; String lastname; public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String (“Kermit"); lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

34 34 Object Example n Can consolidate declaration, assignment n just like with primitive data types public class StringTest { public static void main (String[] args) { String firstname = new String (“Kermit"); String lastname = new String (“theFrog"); System.out.println("I am not " + firstname + " " + lastname); }

35 35 Objects vs. Primitives n references int favoriteNum Frog object Frog favoriteFrog 42 int famousNum 42 Frog famousFrog vs. direct storage boolean isMuppet true String frogName String object “Kermit”

36 36 Objects vs. Primitives n references int favoriteNum Frog object Frog favoriteFrog 999 int famousNum 42 Frog famousFrog vs. direct storage boolean isMuppet false String frogName String object “Kermit”

37 37 Class Libraries n Before making new class yourself, check to see if someone else did it already n libraries written by other programmers n many built into Java n Example n Java has single-character primitive data type n what if want to work with sequence of characters n String class already exists

38 38 API Documentation n Online Java library documentation at http://java.sun.com/javase/6/docs/api/ http://java.sun.com/javase/6/docs/api/ n textbook alone is only part of the story n let’s take a look! n Everything we need to know: critical details n and often many things far beyond current need n Classes in libraries are often referred to as Application Programming Interfaces n or just API

39 39 Some Available String Methods public String toUpperCase(); Returns a new String object identical to this object but with all the characters converted to upper case. public int length(); Returns the number of characters in this String object. public boolean equals( String otherString ); Returns true if this String object is the same as otherString and false otherwise. public char charAt( int index ); Returns the character at the given index. Note that the first character in the string is at index 0.

40 40 More String Methods public String replace(char oldChar, char newChar); Returns a new String object where all instances of oldChar have been changed into newChar. public String substring(int beginIndex); Returns new String object starting from beginIndex position public String substring( int beginIndex, int endIndex ); Returns new String object starting from beginIndex position and ending at endIndex position Hello KermitFrog 0123456789111012131415 substring(4, 7) “o K” up to but not including endIndex char:

41 41 Questions?

42 42 public class StringTest { public static void main (String[] args) { String firstname = new String ("Kermit"); String lastname = new String ("theFrog"); firstname = firstname.toUpperCase(); System.out.println("I am not " + firstname + " " + lastname); } String Method Example n invoking methods n objectName.methodName(); n remember (simple) identifiers can't have. in them

43 43 String firstname = "Alphonse"; char thirdchar = firstname.charAt(2); object Methods and Parameters n Class definition says what kinds of data and methods make up object n object is specific instance of class

44 44 String firstname = "Alphonse"; char thirdchar = firstname.charAt(2); object method Methods and Parameters n Class definition says what kinds of data and methods make up object n object is specific instance of class n methods are how objects are manipulated

45 45 String firstname = "Alphonse"; char thirdchar = firstname.charAt(2); object method parameter Methods and Parameters n Class definition says what kinds of data and methods make up object n object is specific instance of class n methods are how objects are manipulated n pass information to methods with parameters n inputs to method call n tell charAt method which character in the String object we're interested in

46 46 Parameters n Methods can have multiple parameters n API specifies how many, and what type public String replace(char oldChar, char newChar); String animal = "mole"; animal.replace('m', 'v'); public String substring( int beginIndex, int endIndex ); animal = "aardwolf"; String newanimal = animal.substring(4,8); System.out.println(newanimal); // wolf

47 47 Explicit vs. Implicit Parameters n Explicit parameters given between parentheses n Implicit parameter is object itself n Example: substring method needs n beginIndex, endIndex n but also the string itself! animal = "aardwolf"; System.out.println(animal); // aardwolf String newanimal = animal.substring(4,8); System.out.println(newanimal); // wolf n All methods have single implicit parameters n can have any number of explicit parameters n none, one, two, many…

48 48 Parameters n Most of the time we'll just say parameters, meaning the explicit ones

49 49 Return Values n Methods can have return values n Example: charAt method result n return value, the character 'n', is stored in thirdchar String firstname = "kangaroo"; char thirdchar = firstname.charAt(2); return value object method parameter

50 50 Return Values n Methods can have return values n Example: charAt method result n return value, the character 'n', is stored in thirdchar String firstname = "kangaroo"; char thirdchar = firstname.charAt(2); n Not all methods have return values n Example: println method does not return anything n prints character 'n' on the monitor, but does not return that value n printing value and returning it are not the same thing! System.out.println(thirdchar); return value object method parameter

51 51 Return Values n Again, API docs tell you n how many explicit parameters n whether method has return value n what return value is, if so n No return value indicated as void

52 52 Constructors and Parameters n Many classes have more than one constructor, taking different parameters n use API docs to pick which one to use based on what initial data you have animal = new String(); animal = new String("kangaroo");

53 53 Accessors and Mutators n Method that only retrieves data is accessor n read-only access to the value n example: charAt method of String class n Method that changes data values internally is mutator n Stay tuned for examples of mutators, we haven't seen any yet n String class has no mutator methods n Accessor often called getters n Mutators often called setters n names often begin with get and set, as in getWhatever and setWhatever


Download ppt "University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Strings, Parameters Lecture 6, Mon Jan 18."

Similar presentations


Ads by Google