Lecture 10: More on Methods and Scope

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

Written by: Dr. JJ Shepherd
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 12 / 04 / 2006 Instructor: Michael Eckmann.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Introduction to Computers and Programming Lecture 14: User defined methods (cont) Professor: Evan Korth New York University.
Object-Oriented Programming in C++
Procedural programming in Java Methods, parameters and return values.
Java Basics.  To checkout, use: svn co scb07f12/UTORid  Before starting coding always use: svn update.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Method Parameters and Overloading Version 1.0. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.
Written by: Dr. JJ Shepherd
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
CSC 142 F 1 CSC 142 References and Primitives. CSC 142 F 2 Review: references and primitives  Reference: the name of an object. The type of the object.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Chapter 9 Introduction to Arrays Fundamentals of Java.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
Function Parameters and Overloading Version 1.0. Topics Call-by-value Call-by-reference Call-by-address Constant parameters Function overloading Default.
Computer Organization and Design Pointers, Arrays and Strings in C
Concepts of Object Oriented Programming
Chapter 7 User-Defined Methods.
Lecture 3 Linear Search and Binary Search ArrayLists
Selenium WebDriver Web Test Tool Training
Chapter 5 Functions DDC 2133 Programming II.
Method Parameters and Overloading
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
CS Programming I Jim Williams, PhD.
Lecture 11 B Methods and Data Passing
Methods and Parameters
Static and non-Static Chapter 5.
More Object Oriented Programming
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Building Java Programs
Object Oriented Programming (OOP) LAB # 8
Lecture 11 C Parameters Richard Gesick.
Object Oriented Programming COP3330 / CGS5409
March 29th Odds & Ends CS 239.
Chapter 5 Function Basics
CMSC202 Computer Science II for Majors Lecture 04 – Pointers
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
IFS410 Advanced Analysis and Design
Defining methods and more arrays
Java Lesson 36 Mr. Kalmes.
Chapter 6 Methods.
Methods and Data Passing
slides created by Ethan Apter
Week 4 Lecture-2 Chapter 6 (Methods).
Variables and Computer Memory
Happy October Exam Review 10/01/2014.
Methods and Data Passing
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Lecture 10: More on Methods and Scope CS201

Value and Reference So far, parameters (with one exception) have been passed by value The calling method makes a copy of the value and sends it to the called method The called method sets up a variable, assigns the parameter value to it, and, presumably, uses it. If the parameter was a variable, its value in the calling method does not change This is how primitive data types, like int, double, and char are passed to and from methods

Value and Reference With a primitive data type, if you want to change the value of the variable in a calling method but it is not in scope in the called method, you can return the correct data type from the called method and assign the return value to the variable: x = getNewX(); Note the difference between this and the situation with myInt in MethodScopeDemo from the last lecture

Value and Reference Sounds pretty easy so far, right? Not any more! The demos in the last lecture used primitive types like int and double It’s more complicated when you pass an object, such as a String This material is complicated but very important. There will certainly be problems on the quizzes and final exam that require you to understand it thoroughly.

Reference In Java, a reference to an object in memory is the memory address where the object can be found. A variable of a primitive data type holds the actual value int myInt = 1; A variable whose type is a class, like Scanner or String, holds a reference to the object.

Value and Reference Consider this code: StringBuilder sb = “Hi, Mom”; All parameters are passed by value as described above BUT objects are not passed. Instead, we pass-by-value variables that contain references to objects Consider this code: StringBuilder sb = “Hi, Mom”; sb is a reference to the StringBuilder, not a copy of the StringBuilder itself. We need to “dereference” the reference to get the actual StringBuilder.

Value and Reference Other languages (eg Visual Basic) use the concept “pass by reference” Some languages, like C, allow the programmer to choose whether to pass by value or by reference In Java, objects can’t be passed In Java we conventionally say we are passing the reference variable by value. Its value is the reference, so it still pass by value. In Java terminology, this is called passing a reference by value.

Reference It will be easier to remember this if you think about the reasons for it. Primitive data types consume predictable and manageable amounts of memory 4 bytes for an int, 8 bytes for a double It is easy to make copies of these to send back and forth Objects, instances of classes, are, in principle, unbounded in size and may be very large. A String may contain no characters at all, but it might also contain the text of the Bible. The expense of copying an object to send to a method is unpredictable and may be very large.

Value and Reference If the method that receives a reference-type variable as a parameter changes the object, we will see the changes from anywhere where the object is in scope No need to return the new value Remember that this is how we pass objects, instances of classes like String or Scanner.

Value and Reference public class NoPassByReferenceDemo{ public static void main(String[] args) { StringBuilder tagLine = new StringBuilder("Ah, Satan sees Natasha"); System.out.println(tagLine); otherMethod(tagLine); } public static void otherMethod(StringBuilder myStringBuilder) { myStringBuilder.reverse();

Value and Reference Here is what happened in the code above: We passed the reference variable to otherMethod() Then we used it to find the object and changed the object, but not the reference variable After that, the value of the reference is still the same – it shows where to find the object. But, the object has changed We see the new state of the object when we access it from wherever it is in scope This point is difficult but very important! If you don’t understand it after this lecture, study the last few slides carefully. If you still don’t understand it, come to my office hours.

Pass By Value Passing a primitive data type by value is like making a copy of the value and handing it to the called method

Pass A Reference By Value Passing a reference to an object is like telling the called method where to find the object

Copying Variables of Primitive Data Types and Object Types

Method Overloading Scary-sounding term for a very simple concept You can’t have two methods in the same class with the same name and same method signature But you can have two methods with the same name and different signatures

Method Overloading Scary term for a very simple concept You can’t have two methods in the same class with the same name and same method signature But you can have two methods with the same name and different signatures

import javax.swing.JOptionPane; public class Overload{ public static void main(String[] args){ int x = 0; x = getInt(); JOptionPane.showMessageDialog(null, "You chose " + x); int min = 2; int max = 10; x = getInt(min, max); } public static int getInt(){ int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer")); return x; public static int getInt(int low, int high){ int val = low -1; do{ val = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer between " + low + " and " + high)); } while(val < low || val > high); return val;

Lurking Troll Principle Never write a method with more code than you can see on the screen all at once. What you can’t see will hurt you.

Stacks A stack is a way of ordering data so that the last value you add to the stack is the first one you use from it. Like a stack of plates in a cafeteria Last In, First Out (LIFO)

Stacks Stacks have many uses in programming The one that concerns us in this class is that this is how the JVM keeps track of method calls

Call Stacks

i is declared and initialized animation Trace Call Stack i is declared and initialized

j is declared and initialized animation Trace Call Stack j is declared and initialized

animation Trace Call Stack Declare k

animation Trace Call Stack Invoke max(i, j)

pass the values of i and j to num1 and num2 animation Trace Call Stack pass the values of i and j to num1 and num2

pass the values of i and j to num1 and num2 animation Trace Call Stack pass the values of i and j to num1 and num2

animation Trace Call Stack (num1 > num2) is true

animation Trace Call Stack Assign num1 to result

Return result and assign it to k animation Trace Call Stack Return result and assign it to k

The Stevie Wonder Principle When you believe in things that you don't understand, then you suffer. You should be able to explain any method you write in one sentence. If you can't, break it down into two methods. Repeat this process until all your methods are easy to understand.