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

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Introduction to C Programming
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
© 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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Procedural programming in Java Methods, parameters and return values.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Working With Objects Tonga Institute of Higher Education.
Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Lecture 9: Bits and Pieces, Part 2 Tami Meredith.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
Lecture 4: Methods, Classes, and Objects Tami Meredith.
Lecture 4: Looping Tami Meredith. Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Lecture 7: Arrays Tami Meredith. Roadmap Variables Arrays Array indices & Using arrays Array size versus length Two dimensional arrays Sorting an array.
Lecture 2: 1226 Review II Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Lecture 10: Object Oriented Programming Tami Meredith.
Lecture 5: Methods Tami Meredith. Roadmap The new material this week is predominantly from Chapter 5 (and Section 6.2 on static ) You should try and read.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
User-Written Functions
Chapter 2 Basic Computation
Chapter 2 - Introduction to C Programming
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Classes, Objects, and Methods
INPUT & OUTPUT scanf & printf.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to Java Applications
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Presentation transcript:

Lecture 3: Methods, Classes, and Objects Tami Meredith

Overview printf Arrays Methods Hierarchies Classes, objects, and instances

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

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

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!");

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:

Examples System.out.printf ("%d * %d = %d\n", 3, 4, 3*4); System.out.println(3 + " * " " = " + (3*4)); System.out.print (3 + " * " " = " + (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

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]

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)

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

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

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

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

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

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

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

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

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

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!

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

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

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

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

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

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

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

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[]

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;

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

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

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)

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

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"

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

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

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

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

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

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!

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

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

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

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

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

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

And they all lived happily ever after …

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