Value vs. reference semantics

Similar documents
! Theoretical examples: ! Examples from Java: ! data type: A category of data values. " Example: integer, real number, string

Text processing. Readings: 4.4

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

PIC 20A Number, Autoboxing, and Unboxing

Building Java Programs

H212 Introduction to Software Systems Honors

CSC Java Programming, Fall Java Data Types and Control Constructs

Creating Strings. String Length

Parameters. Repetitive figures. A solution? Parameterization. Declaring parameterized methods. Generalizing methods. Readings: 3.1

COMP-202: Foundations of Programming

MODULE 02: BASIC COMPUTATION IN JAVA

Lecture 5. Assignments. Arithmetic Operations. Arithmetic Operations -Summary 1/24/18. Lab 3: Variables and operations. Read Sections

Programming Basics. Digital Urban Visualization. People as Flows. ia

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Java Classes: Math, Integer A C S L E C T U R E 8

JAVA OPERATORS GENERAL

Lecture 11: Intro to Classes

More types, Methods, Conditionals. ARCS Lab.

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lab Assignment Three

String is a Class; Quoted Text is an Object

Building Java Programs

Chapter 3: Operators, Expressions and Type Conversion

Lecture Notes for CS 150 Fall 2009; Version 0.5

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

t 1 =2 t n =3t n 1 1,n 1

Getting started with Java

Research Group. 2: More types, Methods, Conditionals

Computer Science II (20082) Week 1: Review and Inheritance

Visual Programming. Lecture 2: More types, Methods, Conditionals

Lecture 8: The String Class and Boolean Zen

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Primitive vs Reference

CS251L REVIEW Derek Trumbo UNM

Zheng-Liang Lu Java Programming 45 / 79

1B1b Classes in Java Part I

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Introduction to Programming Using Java (98-388)

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

CS 231 Data Structures and Algorithms, Fall 2016

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

STRINGS AND STRINGBUILDERS. Spring 2019

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Java Basic Programming Constructs

PROGRAMMING FUNDAMENTALS

Introduction to Java

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Program Fundamentals

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Mr. Monroe s Guide to Mastering Java Syntax

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

More on variables and methods

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

Chapter 10: Text Processing and More about Wrapper Classes

Programming with Java

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Index COPYRIGHTED MATERIAL

W09 CPSC 219 Midterm Exam Page 1 of 7

Spring 2018 Mentoring 3: February 7, Switcheroo. The Golden Rule of Equals says:

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

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

JAVA WRAPPER CLASSES

DATA TYPES AND EXPRESSIONS

Chapter 1 Introduction to java

COMP-202 Unit 5: Basics of Using Objects

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Chapter 10. Object-Oriented Thinking

CT 229 Fundamentals of Java Syntax

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Java Simple Data Types

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

C08c: A Few Classes in the Java Library (II)

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Sierpinski Valentine. q Our journey of introducing conditionals

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

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

Building Java Programs

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Introduction to Programming (Java) 4/12

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

CS 1301 Ch 8, Part A

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Review of Java. or maybe not

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSCI 355 Lab #2 Spring 2007

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

CSCI 355 LAB #2 Spring 2004

Transcription:

Value vs. reference semantics 1

Recall: Value semantics! value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. " Primitive types in Java use value semantics. " Modifying the value of one variable does not affect other.! Example: int x = 5; int y = x; // x = 5, y = 5 y = 17; // x = 5, y = 17 x = 8; // x = 8, y = 17 2

Reference semantics! reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters. " Object types in Java use reference semantics. " Object variables do not store an object; they store the address of an object's location in the computer memory. We graphically represent addresses as arrows.! Example: Point p1 = new Point(3, 8); p1 x: 3 y: 8 3

Reference semantics! If two object variables are assigned the same object, the object is NOT copied; instead, the object!s address is copied. " As a result, both variables will point to the same object. " Calling a method on either variable will modify the same object.! Example: Point p1 = new Point(3, 8); Point p2 = p1; p2.setlocation(1, 2); p1 x: 13 y: 28 p2 4

Reference semantics: Why?! Objects have reference semantics for several reasons: " efficiency: Objects can be large and bulky. Having to copy them every time they are passed as parameters would slow down the program. " sharing: Since objects hold important state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object. 5

Reference semantics: Example Point p1 = new Point(3, 8); Point p2 = new Point(2, -4); Point p3 = p2;! How many unique objects are there? How do you know that? " Two, because objects are only created with the new keyword.! If we change p3, will p2 be affected and vice versa? " Yes. p1 x: 3 y: 8 p2 x: 2 y: -4 p3 6

Reference semantics: Example! If two variables refer to the same object, modifying one of them will also make a change in the other: p3.translate(5, 1); System.out.println("(" + p2.x + " " + p2.y + ")"); p1 x: 3 y: 8 p2 x: 72 y: -3-4 Output:!)3-,7( p3 7

Objects as parameters! When an object is passed as a parameter, the object is not copied. The same object is referred to by both the original variable and the method's parameter. " If a method is called on the parameter, it will affect the original object that was passed to the method. 8

Objects as parameters: Example! Example: public static void main(string[] args) { Point p1 = new Point(2, 3); move(p1); public static void move(point p) { p.setlocation(-1, -2); p1 x: -1 2 y: -2 3 p 9

Program mystery! What does this code do? public static void main(string[] args) { int a = 7; int b = 35; System.out.println(a + " " + b); int temp = a; a = b; b = temp; System.out.println(a + " " + b); 10

Swapping values! Swapping is a common operation, so we might want to make it into a method. public static void main(string[] args) { int a = 7; int b = 35; System.out.println(a + " " + b); // swap a with b swap(a, b); System.out.println(a + " " + b); public static void swap(int a, int b) { int temp = a; a = b; b = temp;! Does this work? Why or why not? 11

Let s try swapping objects public static void main(string[] args) { Point p1 = new Point(1, -1); Point p2 = new Point(2, 0); System.out.println(p1 + " " + p2); // swap a with b swap(p1, p2); System.out.println(p1 + " " + p2); public static void swap(point a, Point b) { Point temp = a; a = b; b = temp;! Does this work? Why or why not?

A solution for swapping Point objects public static void main(string[] args) { Point p1 = new Point(1, -1); Point p2 = new Point(2, 0); System.out.println(p1 + " " + p2); // swap a with b swap(p1, p2); System.out.println(p1 + " " + p2); public static void swap(point a, Point b) { Point temp = new Point(); temp.setlocation(a.getx(), a.gety()); a.setlocation(b.getx(), b.gety()); b.setlocation(temp.getx(), temp.gety());

Wrapper Classes

Wrapper classes! Wrapper classes are object types that correspond to each primitive type int long double boolean char Primitive Type Integer Long Double Boolean Character Wrapper Class! Two important methods in Wrapper classes: " parseint(string s) (or parsedouble, parselong!) " intvalue() (or doublevalue(), longvalue(),!)! Important fields: MAX_VALUE, MIN_VALUE

Converting between primitive and Wrapper types! You can wrap a int in an Integer by assignment: int x = 17; Integer wrapx = new Integer(x); Integer wrapx2 = x; // shorthand! To get an int value out of an Integer object: Integer x = new Integer(17); int unwrappedx = x.intvalue(); int unwrappedx2 = x; // shorthand

Wrapper classes for swapping ints public static void main(string[] args) { Integer a = 7; Integer b = 35; System.out.println(a + " " + b); // swap a with b swap(a, b); System.out.println(a + " " + b); public static void swap(integer a, Integer b) { Integer temp = a; a = b; b = temp;! What s wrong with this version?

Mutable and Immutable objects! Definition: An immutable object is an object whose state cannot be modified after it is created.! The String class and all the wrapper classes are immutable in Java. " As a result, we can t use the wrapper classes to solve the swap problem for primitive types. " We ll come back to swapping primitive objects later.! Point objects are mutable (ie, not immutable) " setlocation and translate change their state " We can use this fact to make the swap method work

Madness to the method! The methods that appear to modify a string (substring, tolowercase, touppercase, etc.) actually create and return a new string. String s = "lil bow wow"; s.touppercase(); System.out.println(s); // output: lil bow wow vs. String s = "lil bow wow"; s = s.touppercase(); System.out.println(s); // output: LIL BOW WOW 19

Exercises! Write a method to determine the slope of the line that passes between two points.! Write a method to compute the dot-product (or inner product) of two points.! Write a method to return a point s mirror image across the x axis.! Given an int called scale, write a method to magnify a point so that its distance from the origin is multiplied by scale.

Operators and object types

How not test equality of objects! DO NOT DO THIS: public static boolean testequals(point p1, Point p2) { if(p1==p2) { BAD return true; else { return false;

How not test equality of objects! Objects store references, or addresses.! Comparing two objects with == will test if they have the same address.! This is NOT what you want. public static boolean testequals(point p1, Point p2) { if(p1==p2) { BAD return true; else { return false;

Why so bad? Point p1 = new Point(7, 2); Point p2 = new Point(7, 2); p1: x: 7 y: 2 p2: x: 7 y: 2 Is p1==p2 true or false? It s false: they point to different spots in memory. So they store different addresses. But we want it to be true, obviously!

The equals method! All classes in Java have a built-in equals method! For the Point class: p1.equals(p2)! This returns true if p1 and p2 have the same data! It doesn t matter if they reference different locations in memory! Likewise, use!p1.equals(p2) instead of p1!=p2

Object and primitive types: a comparison (so far) Object types Constructed with the new keyword References to memory location that stores their data Can be null (have no data) Can cause NullPointerExceptions Contain state and behavior Use reference semantics Primitive types Values don t need to be constructed Store data directly in memory slot Cannot be null Cannot cause NullPointerExceptions Contain state only Use value semantics Use equals() method Use ==,!=

String and char methods

Text processing: Example // Returns the count of occurrences of c in s. public static int count(string s, char c) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charat(i) == c) { count++; return count;! For instance, count("mississippi", 'i') returns 4 28

Strings and chars: Exercises! Write a method named piglatinword that accepts a String as a parameter and outputs that word in simplified Pig Latin, by placing the word's first letter at the end followed by the suffix ay. " piglatinword("hello") prints ello-hay " piglatinword("goodbye") prints oodbye-gay! Write methods named encode and decode that accept a String as a parameter and outputs that String with each of its letters increased or decreased by 1. " encode("hello") prints ifmmp " decode("ifmmp") prints hello 29

Strings and chars: Exercises! Write a method printname that accepts a full name as a parameter, and prints the last name followed by a comma, followed by the first name and middle initial. printname("alexander Pieter Yates"); would output: Yates, Alexander P. 30

printname: One possible solution public static void printname(string fullname) { int firstblankindex = fullname.indexof(" "); String uptomiddleinitial = fullname.substring(0, firstblankindex + 2); String middleandlastname = fullname.substring(firstblankindex + 1, fullname.length()); int secondblankindex = middleandlastname.indexof(" "); // Notice that "secondblankindex" is used with "middleandlastname" and NOT // "fullname". If you said // // fullname.substring(secondblankindex + 1, fullname.length())! // // you wouldn't get the last name properly. Make sure you understand // why. String lastname = middleandlastname.substring(secondblankindex + 1, middleandlastname.length()); System.out.println(lastName + ", " + uptomiddleinitial + "."); 31

Exercise: String Conversions! Write a method that has a String argument that contains an int (eg, 123 ) and returns a String containing the next number (eg, 124 ).! Write a method that converts a String to an int without using Integer.parseInt(). Use a loop!