Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 3: Methods, Classes, and Objects Tami Meredith.

Similar presentations


Presentation on theme: "Lecture 3: Methods, Classes, and Objects Tami Meredith."— Presentation transcript:

1 Lecture 3: Methods, Classes, and Objects Tami Meredith

2 Overview printf Arrays Methods Hierarchies Classes, objects, and instances

3 Exercise Write method named gcd that takes two integers as parameters and returns the greatest common divisor of those two integers Note: a divisor is a number that divides both, evenly, without any remainder

4 Solution // Find the gcd of two ints public int gcd (int x, int y) { int i, min = (x < y) ? x : y; for (i = min; i > 0; i--) { if (((x%i)==0) && ((y%i)==0)) return (i); } return (1); // dead code } // end gcd()

5 printf printf ( format-string,... values... ) There must be one value for every specifier in the format string format specifiers begin with a % and are placed in the format string E.g. printf("Hello %s!", name); In this example %s means, put a string here, and name is used to provide the string Same as print("Hello " + name + "!"); There might not be any values! E.g., printf("Hello!"); is the same as print("Hello!");

6 Format Specifiers %c – a character %s – a string %d – an integer %f – a floating point number We can modify the values to have a minimum and a maximum size, left or right justify numbers, pad with leading/trailing zeros, create columns, etc. E.g., %5d – an integer with 5 digits (spaces added if needed) See: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

7 Examples System.out.printf ("%d * %d = %d\n", 3, 4, 3*4); System.out.println(3 + " * " + 4 + " = " + (3*4)); System.out.print (3 + " * " + 4 + " = " + (3*4) + "\n"); 3 * 4 = 12 System.out.printf ("%s\n%s\n", "Tami", "Meredith"); System.out.println("Tami\nMeredith"); System.out.print ("Tami\nMeredith\n"); Tami Meredith

8 Arrays 4 integers stored (somewhere) in memory int a, b, c, d; An array named "e" that stores 4 integers int[] e = new int[4]; a dcb e[0]e[1]e[2]e[3]

9 Array Syntax: Definition int[] e = new int[4]; type [] name = new type [ number-of-elements ]; type tells us how big each slot needs to be and what it will hold name is what the entire array is called new is a special instruction that means "assign memory" and is always followed by an indicator of how much memory to get (in this case, enough for 4 integers)

10 Array Syntax: Assignment int[] coords = new int[2]; coords[0] = 3; coords[1] = 5; 0 and 1 are referred to as array indices Arrays are indexed from 0 because the index identifies how many slots we are from the front of the array An index is not a count into the array! (Its actually an offset) coords[0]coords[1] 35

11 new 1. int x; 2. x = 4; 1. int[] y; 2. y = new int[4]; 3. y[0] = 1; y[1] = 2; y[2] = 4; y[3] = 8; Arrays add the extra step of indicating how many values the array needs to store (and getting the memory for it at that time using new ). x 4 [0][1][2][3] 1248 y reference

12 References Java has a few Primitive Types e.g., int, double, boolean, char, void Everything else is an Object An array is an object (with some special features) A String is an array of char we just hide the new, but its really there! ALL Objects use references References are just memory addresses/locations Variables that store Strings, Arrays, Objects all store REFERENCES

13 Exercise public class someCode { public static void main (String[] args) { int[] nums = {1,2,4,8,16,32,64,128,256}; int[] copy = nums; } } // end class someCode What does copy contain? How do we create a copy of an array? Write a method called numCopy() that takes an array of integers as its argument and returns a copy of the array. E.g.: int[] copy = numCopy(nums);

14 Solution public class someCode { public static int[] numCopy (int[] in) { int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return (out); } public static void main (String[] args) { int[] nums = {1,2,4,8,16,32,64,128,256}; int[] copy = numCopy(nums); } } // end class someCode

15 Hierarchies Programs can get big! Windows 50+ Million LOC Need ways to break things down into manageable chunks Use hierarchies! We know one hierarchy already – the disk file system Directories contain subdirectories which contain more subdirectories and so on

16 A Program Hierarchy class myProgram Program myProgram method getInput method main statement class myData class myInterface method doSetup

17 The Java Model A Program is a set of (co-operating) classes A Class is a set of (co-operating) methods and their data A Method is a set of statements to accomplish a goal or sub-goal The parts must work together Problem solving is breaking complex things into smaller and simpler parts! Programs → Classes → Methods → Statements

18 Methods Simply, a method is a block of code with a name This is why we put all the code for main inside { and } We have to have one method called main because this is where the program begins Rather than telling the computer where to begin, the process is simplified by always beginning at the start of the method called main main (apart from being the starting point) is really just the same as any other method

19 The Duality of Methods Methods allow a block of code to be reused by naming the code Methods have two different aspects 1. The method definition is where we assign the name to the code 2. A method call is where we use the block of code that we named (i.e., we "call" the method) We can define a method and not use it (which is kind of a waste of time) We MUST define a method that we use/call We can use/call a method more than once!

20 Example public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } public static void main (String[] args) { // call the method printStuff printStuff(); } } // end class test

21 Control Flow Explanation 1 Idea: jump to the body when a method is called public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } public static void main (String[] args) { // call the method printStuff printStuff(); System.out.println("Done"); } } // end class test

22 Control Flow Explanation 2 Control Flow Explanation 2 Idea: substitute the body for the call public class test { // define the method printStuff public static void printStuff () { System.out.println("Hi there!"); } public static void main (String[] args) { // printStuff();  Put a "copy" of the body here { System.out.println("Hi there!"); } // printStuff();  Put another "copy" of the body here { System.out.println("Hi there!"); } System.out.println("Done"); } // end main() } // end class test

23 Data: In and Out Some methods require data to operate The data that is needed are called "parameters" Some methods generate new data that they wish to "give back" when they are done The data that is generated is called the "return value" Method input = parameters Method output = return value

24 Example public class doubleIt { // define the method timesTwo public static int timesTwo (int v) { return (2 * v); } public static void main (String[] args) { // call the method we just defined int x = timesTwo(10); System.out.println("Two times 10 is " + twice); } } // end class doubleIt PARAMETERS RETURN VALUE

25 Data Flow Call int x = timesTwo(10); Definition public static int timesTwo(int v) { return(2*v); } Return int x = timesTwo(10);

26 Example public class annotated { public static int timesTwo (int v) { return (2 * v); } public static void main (String[] args) { int x = timesTwo(10); System.out.println("Two times 10 is " + x); } } // end class annotated 1. Execution starts at main 4. result, 20, is calculated and returned 3. Body of timesTwo executes, v has the value 10 2. 10 gets copied into location called v 5. return value of timesTwo, 20, is stored in location x 6. println looks up x and locates the value, 20, and prints it 7. end of main is reached, execution ends

27 Method Definitions Always have a "visibility" indicator (e.g., public) May be declared as "static" (e.g., inheritance modifier) Always have a return type (which is "void" if the method returns nothing) Always have a name Always have a list of parameters in parentheses (but the list might be empty) Always have a block of code public static void main (String[] a) { System.out.println("Hello World!"); } Think: void  main  String[]

28 Returns return causes a method to end return usually has a value in parentheses after it, e.g., return(0); the type of the value must match the "return type" of the method if the method returns void, return doesn't need the parentheses, e.g., return;

29 Example public class initials { public char first (String s) { return (s.charAt(0)); } public char second (String s) { int i = indexOf(" "); return (s.charAt(i+1)); } public void inits (String name) { char c1 = first(name); char c2 = second(name); System.out.printf("%c%c\n", c1, c2); } public static void main (String[] args) { String me = "Tami Meredith"; inits(me); } } // end class test inits() second()first() main() printf() 1 7 8 543 2 6

30 return return means: leave this method now and go back to the method that called me! As part of the process, a value is moved back to the original method that made the call return modifies control flow and moves a value to cause data flow if a method has no return it returns when it hits the end of its code block this kind of method must have a return type of void

31 Exiting a program There are 3 ways to exit a program Execution ends normally when the end of main is reached Execution ends any time there is a return inside main Execution ends any time, in any method, when System.exit( n ) occurs ; n is the integer exit code ( 0 if all is OK, other values for different errors)

32 Why Methods? Methods permit us to reuse a block of code Methods permit us to simplify code by replacing a complicated part with a meaningful name Methods permit us to break difficult things into smaller (named) parts Methods permit us to hide the details of something

33 Exercise Write a method called firstCap that takes as its parameter an array of Strings and returns the first string in the array that begins with a capital letter String[] n = {"hi", "there", "Joe"}; String f = firstCap(n); f now contains "Joe"

34 Solution 1 // Find the first string in words // that is capitalised public String firstCap(String[] words) { int i, numWords = words.length; for (i = 0; i < numWords; i++) { String s = words[i]; char first = s.charAt(0); if (('A' <= first) && (first <= 'Z')) return (s); } return (""); } // end firstCap()

35 Solution 2 // Find the first string in words // that is capitalised public String firstCap(String[] words) { for (int i = 0; i < words.length; i++) { if (Character.isUpper(words[i].charAt(0))) return (words[i]); } return (""); } // end firstCap() Now: Write a program to call (i.e., use) firstCap()

36 Solution public class useMethod { // Our method public String firstCap(String[] words) {... as before... } // end firstCap() public static void main (String[] args) { String[] text = {"some", "Words", "to", "use"}; System.out.printf("First cap is %s\n", firstCap(text)); } } // end class useMethod

37 Classes Classes group methods Classes can also contain data The data should be used by the methods in the class We try to create self-contained classes that capture an idea or a concept Classes often model things

38 A Simple Example public class Doll { // data String name; // Doll's name char sex; // 'f' or 'm' int year; // Year we got doll // methods public void display() { System.out.printf("Name: %s\n", name); System.out.printf("Sex: %smale\n", (sex == 'f') ? "fe" : ""); System.out.printf("Age: %d\n", 2013-year); } } // end of class Doll

39 Types int[] data = new int[10]; Scanner keyboard = new Scanner(System.in); Doll barbie = new Doll(); data is a variable of type int[] keyboard is a variable of type Scanner barbie is a variable of type Doll Scanner is a library class, Doll is a user defined class A class is a type!

40 Instantiation Instantiation is when we define an instance of a type int x; instantiates x as a variable of type int We must instantiate classes as well Classes are instantiated using the keyword new Thus Scanner keyboard = new Scanner(System.in); Instantiates keyboard as a variable of type Scanner new makes a new copy of Scanner and stores the location of that copy into keyboard

41 Object Types (Summary) A "class" is the "type" of an object An "object" is an instance of the class/type Doll barbie = new Doll(); 1. Doll is a class 2. The variable barbie is an instance of the class Doll 3. barbie is of type Doll 4. barbie contains a reference to a memory location big enough to hold all the data for a Doll 5. Classes/types are templates – they describe something but have no memory

42 Using a Class public class barbies { public static void main (String[] a) { Doll d1 = new Doll(); Doll d2 = new Doll(); d1.name = "Barbie"; d1.sex = 'f'; d1.year = 2000; d2.name = "Ken"; d2.sex = 'm'; d2.year = 2010; d1.display(); d2.display(); } // end main } // end class barbies d1 ref. d2 ref. namesexyeardisplay Barbief2000{...} namesexyeardisplay Kenm2010{...} new gets memory for the object causes a whole COPY of the class to occur

43 Objects An object is an instance of a class Every object is a unique "copy" of the class Even the methods are copied! The methods use the data for their own copy There is a way to stop the copy and share data and that is to make the data (or method) static

44 Instance and Class Variables public class Doll { // Class variables – shared by all Dolls static int now; // Instance variables – each Doll has these String name; // Doll's name char sex; // 'f' or 'm' int year; // Year we got doll // methods public void display() { System.out.printf("Name: %s\n", name); System.out.printf("Sex: %smale\n", (sex == 'f') ? "fe" : ""); System.out.printf("Age: %d\n", now - year); } } // end of class Doll

45 Using a Class 2 public class barbies { public static void main (String[] a) { Doll.now = 2013; // now is static (i.e., shared), access via CLASS Doll d1 = new Doll(); Doll d2 = new Doll(); d1.name = "Barbie"; d1.sex = 'f'; d1.year = 2000; d2.name = "Ken"; d2.sex = 'm'; d2.year = 2010; d1.display(); d2.display(); } // end main // name,sex,year,display NOT static, access via instance } // end class barbies d1 ref. d2 nownamesexyeardisplay 2013 Barbief2000{...} Kenm2010{...} nownamesexyeardisplay

46 And they all lived happily ever after …

47 To Do Read chapters 5 and 6 in detail until you start to understand them We will go over this material more next class


Download ppt "Lecture 3: Methods, Classes, and Objects Tami Meredith."

Similar presentations


Ads by Google