CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Similar documents
CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Creating Strings. String Length

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

Binghamton University. CS-140 Fall Data Types in Java

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination

Introduction to Programming (Java) 4/12

"Hello" " This " + "is String " + "concatenation"

CS 455 Midterm Exam 1 Fall 2017 [Bono] Thursday, Sep. 28, 2017

Lab 14 & 15: String Handling

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Using Objects. a first example of an object classes and objects in Java

More non-primitive types Lesson 06

Programming with Java

Intro to Computer Science II

Midterms Save the Dates!

Activity 9: Object-Oriented

Class. Chapter 6: Data Abstraction. Example. Class

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Activity 9: Object-Oriented

STUDENT LESSON A10 The String Class

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Letterkenny Institute of Technology

Selected Questions from by Nageshwara Rao

IS502052: Enterprise Systems Development Concepts Lab 1: Java Review

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Unit 4: Classes and Objects Notes

More on variables and methods

Building Strings and Exploring String Class:

We now start exploring some key elements of the Java programming language and ways of performing I/O

Lecture Notes K.Yellaswamy Assistant Professor K L University

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Lecture 11: Intro to Classes

SSE3052: Embedded Systems Practice

COMP-202 Unit 5: Basics of Using Objects

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2010) - All Sections Final Examination

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Express Yourself. Writing Your Own Classes

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Methods Summer 2010 Margaret Reid-Miller

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Manual for Basic Java

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Eng. Mohammed Abdualal

For this section, we will implement a class with only non-static features, that represents a rectangle

Computer Science II Data Structures

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Midterms Save the Dates!

Topics. Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2

52 Franck van Breugel and Hamzeh Roumani

appreciate the difference between a char and a string understand and use the String class methods

Introduction to Programming Using Java (98-388)

Using Java Classes Fall 2018 Margaret Reid-Miller

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Class Library java.lang Package. Bok, Jong Soon

Pace University. Fundamental Concepts of CS121 1

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CHAPTER 6 MOST COMMONLY USED LIBRARIES

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Ryerson University Department of Electrical & Computer Engineering COE618 Midterm Examination February 26, 2013

Programming Language Concepts: Lecture 1

Review: Array Initializer Lists

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

- Thus there is a String class (a large class)

Mathematics for Computer Graphics - Lecture 12

( &% class MyClass { }

Utilities (Part 2) Implementing static features

Programming Language Concepts: Lecture 2

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CS 231 Data Structures and Algorithms, Fall 2016

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

BM214E Object Oriented Programming Lecture 8

York University Fall 2001 / Test #1 Department of Computer Science

A Founda4on for Programming


CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS251L REVIEW Derek Trumbo UNM

Object Oriented Programming 2015/16. Final Exam June 28, 2016

Solutions to Quiz 1 (March 14, 2016)

Java String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace,

Java Strings Java, winter semester

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Lesson:9 Working with Array and String

Preview from Notesale.co.uk Page 9 of 108

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Transcription:

Methods There s a method in my madness. Sect. 3.3, 8.2 1

Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer ownership Move to a new location Repaint Delete a car 2

What s in a class? Fields The data used to describe an object in the class Methods The functions used to manipulate an object in the class 3

Terminology Method: A function in a class definition which implements an action that can be performed on an object Receiver: The object from which the method was invoked most typically, the object which the method acts on. Methods have an implicit parameter of this which refers to the receiver object. Argument: data passed to a method. Arguments are from the invocation point of view, as compared to parameters. Parameter: data passed to a method. Parameters are from the method s point of view, as compared to arguments 4

Method Syntax modifiers returntype name (parameters) throws { } body modifiers : public private static also: protected abstract final synchronize native strictfp returntype : Any primitive or reference type or void name : Any valid identifier 5

Parameters Comma separated list of things that look like variable declarations Each parameter is a positional place-holders to hold the values that are to be passed a method to allow it to complete its action The last parameter in the list may specify a variable length list of values. If so, it must be specified as type name where name is interpreted as an array within the method. 6

Example Method Headers public static void main(string[ ] args) { int factorial(int n) { public void println(string x) { Modifiers Return Type name Parameters public GridLayout(int rows, int cols, int hgap, int vgap) { public static int sum(int numbers) 7

Arguments The positional list of values or references passed in to a method (to be kept a a parameter) An argument may be an expression that evaluates to a value or a reference System.out.println("Hello"); factorial(10); panel.setlayout(new GridLayout(2, 2, 5, 5)); Arguments 8

static methods behave like C class XmpStat { } static int add3(int x) { return x+3; } class Tester { public static void main() { System.out.println( 20+3= + XmpStat.add3(20)); } } 9

Instance vs. Class Methods If a method is declared as static, it is a class method Invoked like a function not as an action on an object Class methods do not have a receiver object Class methods do not have a this implicit parameter main is a class method, not an instance method Constructors are invoked like a class method Most methods are instance methods methods which are invoked as actions on specific objects Note: Constructors are more like instance methods, even though they are not invoked as instance methods 10

Method Invocation Most often, a method is invoked by specifying an action to occur to an object DollarsAndCents mymoney = new DollarsAndCents(12,50); mymoney.upordown(1.05); Reference to an object in the DollarsAndCents class Action: Method from the DollarsAndCents class Argument to be passed to the upordown method 11

Rectangle Class Example Rectangles expressed as (left x, top y, width, height) Rectangle rect1 = new Rectangle(70,90,100,150); translate means move a shape without changing it rect1.translate(100, 80); moves rect1 to (170, 170, 100, 150) 12

Rectangle example continued public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); } There is only one copy of the code for the method translate, not one copy for each object How is that translate moves rect1 and not rect2? The code of translate has to receive a reference to the object it will read information from or modify See class web page example FirstGUI 13

No Code in Objects In section 2.3 of the text, there are diagrams like: Despite these pictures, there is no actual CODE stored in the object! The object ONLY contains the values of the fields for that object The code is stored in memory only once for the entire class 14

The Implicit Receiver Parameter The object that receives the action ( the object which the action is performed on) is called the receiver object. The receiver object is implicitly placed in the parameter list of the method, as if (but not actually) you had specified: class Rectangle { void translate(int dx, int dy) { } as if void translate(rectangle this, int dx, int dy) { } } 15

Constructor Methods Must be named the same as the class name! Implicit this parameter is the object being constructed A new object of this class with all non-final fields initialized to zero/null Implicit return parameter of this No return type specification in constructor methods 16

Implicit Parameter in the Stack Parameters are passed using an activation record on the program stack Local variable values are also kept in the activation record Using our rectangle example: public static void main(string[ ] args) { Rectangle rect1 = new Rectangle(70,90,100,150); Rectangle rect2 = new Rectangle(70,180,200,50); rect1.translate(100, 80); } 17

Why class methods? Enable main before any objects are available Enable functions methods which don t act on objects Alternative meaningless empty object which requires creation Enable factory methods methods which create new objects, but are not constructors 18

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; public Rectangle(int lx, int ty, int wid, int hgt) { this.leftx=lx; this.topy=ty; this.w=wid; this.h=hgt; } void translate(int dx,int dy) { this.leftx+=dx; this.topy+=dy; } } 19

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; } If field names are different than variable names, Java assumes this. public Rectangle(int lx, int ty, int wid, int hgt) { this.leftx=lx; this.topy=ty; this.w=wid; this.h=hgt; } void translate(int dx,int dy) { this.leftx+=dx; this.topy+=dy; } 20

Rectangle Class public class Rectangle { int leftx; int topy; int w; int h; } If field names are different than variable names, Java assumes this. public Rectangle(int lx, int ty, int wid, int hgt) { leftx=lx; topy=ty; w=wid; h=hgt; } void translate(int dx,int dy) { leftx+=dx; topy+=dy; } 21

main Binghamton Memory (at start of main) activation records Java Bytecode rect2 rect1 args Next, new will create a rectangle object, and invoke the Rectangle creator 22

main Rectangle.Rectangle Binghamton Memory (at start of rect1 constructor) Call Stack this lx=70 ty=90 wid=100 hgt=150 rect2 rect1 args Rectangle leftx 0 topy 0 w 0 h 0 Next, the Rectangle creator returns Java Bytecode 23

main Binghamton Memory (after rect1 constructor) Java Bytecode Call Stack rect2 rect1 args Rectangle leftx 70 topy 90 w 100 h 150 Next, rect2 is created similarly, and then the translate method is invoked 24

main Rectangle.translate Binghamton Memory (at start of translate method) Java Bytecode Call Stack this dx=100 dy=80 rect2 rect1 args Rectangle leftx 70 topy 90 w 100 h 150 Rectangle leftx 70 topy 180 w 200 h 50 25

Accessor vs. Mutator Methods Sect. 2.5 If a method changes the receiver object field values, it is called a mutator method. For example the translate method in Rectangle changes the value of leftx and topy it is a mutator method If a method does not change the receiver object field values, it is called an accessor method. For example the getwidth method in Rectangle does not change any of the fields in rectangle it is an accessor method. If all methods are accessor methods, the Class is called an immutable class For example the String class is immutable. 26

Example: Immutable String Class Strings are arrays of characters, so index starts at 0 int z = "CS 140".length( ); //gives z the value 6 String str = "CS 140"; String s1 = str.substring(0, 2); // s1 is CS char ch = str.charat(3); // gives ch the value '1 27

Substring Two methods can have the same name if they take different parameters String substring(int beginindex) : Returns a new string that is a substring of this. The substring begins with the character at the specified index and extends to the end of this. String substring(int beginindex, int endindex) : Returns a new string that is a substring of this. The substring begins at beginindex and extends to the character at (endindex 1). Thus the length of the substring is endindex-beginindex. Note that since String is immutable, this is not modified a new string is returned 28

Replace String replace(char oldchar, char newchar) : Returns a new string resulting from replacing all occurrences of oldchar in this string with newchar. String replace(charsequence target, CharSequence replacement) : Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. Note a CharSequence can be a String Note there is also replaceall, but it uses regular expressions 29

Changing Case String tolowercase() : Returns a new String that is this with all of the characters in this converted to lower case using the rules of the default locale. String touppercase() : Returns a new String that is this with all of the characters in this converted to upper case using the rules of the default locale. 30

Equality boolean equals(object anobject) : Compares this to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. boolean equalsignorecase(string anotherstring) : Compares this to another String, ignoring case considerations. 31

equals vs. == String str1= CS 140 ; String str2= CS 140 ; String str3= CS 220 ; String str4 = str1; str1.equals(str2)? str1.equals(str3)? str1==str2? str1==str4? strx==stry &&!strx.equals(stry)? 32

Searching in Strings int indexof(int ch): returns the index within this of the first occurrence of the specified character. int indexof(int ch, int fromindex): returns the index within this of the first occurrence of the specified character, starting the search at the specified index. int indexof(string str): returns the index within this of the first occurrence of the specified substring. int indexof(string str, int fromindex): returns the index within this of the first occurrence of the specified substring, starting at the specified index. 33