1 Value vs. reference semantics. Recall: Value semantics value semantics: Behavior where variables are copied when assigned to each other or passed as.

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
1 Various Methods of Populating Arrays Randomly generated integers.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Java Software Solutions
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
Fundamental Programming Structures in Java: Strings.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 8 Characters and Strings.
Static Class Members Wrapper Classes Autoboxing Unboxing.
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
1 CIS 2168 Data Structures and Algorithms in JAVA Brief Introduction to JAVA.
Objects.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Chapter 7: Characters, Strings, and the StringBuilder.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
1 Fencepost loops suggested reading: The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
CSC 142 Computer Science II Zhen Jiang West Chester University
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Object - CIS 1068 Program Design and Abstraction
“Interview coding is not the same skill as coding in real life where you have Stack Overflow, reference materials, and an editor. ”
Java Primer 1: Types, Classes and Operators
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
Array traversals, text processing
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.
Defining Classes II.
March 29th Odds & Ends CS 239.
CSC240 Computer Science III
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 6 – Methods Topics are:
Why did the programmer quit his job?
Building Java Programs
Lecture 14: Strings and Recursion AP Computer Science Principles
Building Java Programs
The structure of programming
Suggested self-checks: Section 7.11 #1-11
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 6: References and linked nodes reading: 16.1
Presentation transcript:

1 Value vs. reference semantics

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); 3 8y:y:3x:x: p1

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); p2 y:y:x:x: p1 12

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. 6 8 p2 y:y:3x:x: p1 -4y:y:2x:x: p3

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 + ")"); Output: (7, -3)‏ p2 y:y:3x:x: p1 y:y:x:x: 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); } 9 p1 y:y:x:x: p

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 Two important methods in Wrapper classes:  parseInt(String s) (or parseDouble, parseLong …)  intValue() (or doubleValue(), longValue(), …) Important fields: MAX_VALUE, MIN_VALUE Primitive TypeWrapper Class intInteger longLong doubleDouble booleanBoolean charCharacter

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

19 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

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) { return true; } else { return false; } BAD

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) { return true; } else { return false; } BAD

Why so bad? Point p1 = new Point(7, 2); Point p2 = new Point(7, 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! p1: y:x: 72 p2: y:x: 72

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 typesPrimitive types Constructed with the new keywordValues don’t need to be constructed References to memory location that stores their data Store data directly in memory slot Can be null (have no data)Cannot be null Can cause NullPointerExceptionsCannot cause NullPointerExceptions Contain state and behaviorContain state only Use reference semanticsUse value semantics Use equals() methodUse ==, !=

String and char methods

28 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

29 String s and char s: 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

30 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. String s and char s: Exercises

31 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 + "."); }

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!