Chapter 3 Spring 2005 CS 101 Aaron Bloomfield

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

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input Lecture 5, Thu Jan
03 Data types1June Data types CE : Fundamental Programming Techniques.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
Using Objects CS 101-E Aaron Bloomfield. Announcements Midterm 1 is a week from this Wednesday Midterm 1 is a week from this Wednesday TESTS ARE IN CHM.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
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;
1 Using Objects Chapter 3 Fall 2005 CS 101 Aaron Bloomfield.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
COMP 110 Spring Announcements Computers in class on Friday: Lab Office Hours: Monday 12-2 New students see me after class Administrative Changes.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
1 Using Objects Chapter 2 (part 2 of 2) Spring 2007 CS 101 Aaron Bloomfield.
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 Using Objects Chapter 3 Fall 2006 CS 101 Aaron Bloomfield.
1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+
Introduction to Java Java Translation Program Structure
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Objects. Getting classy Your current job –Gain experience creating and manipulating objects from the standard Java types Why –Prepares you for defining.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
1 Using Objects Chapter 3 Spring 2006 CS 101 Aaron Bloomfield.
1 Review for exam 1 CS 101 Aaron Bloomfield. 2 Today’s lecture An overview of the “review” sections of chapters 1-3 Stop me if you want me to go over.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
1 Review for exam 1 CS 101-E Aaron Bloomfield. 2 Announcements Exam this Wed Exam this Wed In CHM 402 (NOT in Clark G004) In CHM 402 (NOT in Clark G004)
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Review for exam 1 CS 101 Aaron Bloomfield. 2 Today’s lecture An overview of the “review” sections of chapters 1- 3 and 5 Stop me if you want me to go.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
COMP Review of Chapter 1 & 2
Chapter 2 Basic Computation
Objects.
Elementary Programming
Building Java Programs
Introduction to Computer Science / Procedural – 67130
Object Oriented Programming
Data types and variables
Permutations and Combinations
Java basics – part 3.
Arrays in C.
Java Programming: From Problem Analysis to Program Design, 4e
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
AP Java Unit 3 Strings & Arrays.
Review for Exam 1 Spring 2007 CS 101/CS 101-E.
Fundamentals 2.
CS 200 Primitives and Expressions
CS 200 Primitives and Expressions
Chapter 3 Spring 2006 CS 101 Aaron Bloomfield
Overloading functions
Building Java Programs
Java Programming Language
Outline Creating Objects The String Class The Random and Math Classes
Announcements & Review
CS Week 2 Jim Williams, PhD.
Objects.
CS31 Discussion 1H Fall18: week 7
Visibilities and Static-ness
Instructor: Alexander Stoytchev
Review for Midterm 3.
More on iterations using
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Chapter 3 Spring 2005 CS 101 Aaron Bloomfield Using Objects Chapter 3 Spring 2005 CS 101 Aaron Bloomfield

About the assignment statement Assign the value 5 to the variable x int x; x = 5; 5 = x; NOT VALID! This is not a mathematical equals It’s a Java assignment The variable you want to copy the value to MUST be on the left The value you want to copy MUST be on the right Assignment copies the value on the right to the variable on the left

Getting classy Purpose of this chapter Gain experience creating and manipulating objects from the standard Java types Why Prepares you for defining your own classes and creating and manipulating the objects of those classes

Values versus objects Numbers Have values but they do not have behaviors Objects Have attributes and behaviors System.in References an InputStream Attribute: keyboard Behaviors: reading System.out References an OutputStream Attribute: monitor Behaviors: printing Java treats object variables differently. Although an object variable is the symbolic name for a memory location being used by the program, the memory location for an object variable does not store a value of that object type. Instead the value in the memory location tells the program where to find a value (object) of that type. We say that an object variable references or points to an object of the object type. Thus, a String variable references a memory location that holds a value of type String. Similarly, a BufferedReader variable references a memory location holding a BufferedReader value.

Java and variables Consider: int x = 7; double d; char c = ‘x’; The variable name is the actual spot in memory where the value is stored 7 int x - double d ‘x’ char c

What is a reference A reference is a memory address References are like pointers in C/C++ But they are not the exact same thing! C++ has references also (in addition to pointers) You may her me call them pointers instead of references All objects in Java are declared as references

Note that there is no “new” here References 1 Consider: int j = 5; String s = “Hello world”; Java translates that last line into: String s = new String (“Hello world”); (Not really, but close enough for this lecture) Note that there is no “new” here

References 2 What’s happening in memory int j = 5; String s = “Hello world”; Primitive types are never references; only objects int j = 5; String s = “Hello world”; String s 0x0d4fe1a8 Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory 5 int j At memory location 0x0d4fe1a8 Takes up 12 bytes of memory Hello world

Quick survey I understand those slides on references… I think so I need some more review Not really Reference what?

An old prediction of the future…

Other Java object types String Rectangle Color JFrame

Representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“ message + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... String - text = "Don't look behind the door!" - length = 27 - ... peasPerPod

Representation String s = “I love CS 101”; int l = s.length(); char c = s.charAt (3); String t = s.subString(1,2); int t = s.indexOf (t, 0); message + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... String - text = "Don't look behind the door!" - length = 27 - ...

Shorthand representation Statements int peasPerPod = 8; String message = "Don't look behind the door!“

Examples Consider String a = "excellence“; String b = a; What is the representation?

Uninitialized versus null Consider String dayOfWeek; Scanner inStream; What is the representation?

Uninitialized versus null Consider String fontName = null; Scanner fileStream = null; What is the representation? fontName fileStream null fontName fileStream OR

The null reference Sometimes you want a reference to point to nothing Use the null reference: String s = null; The null reference is equivalent to a memory address of zero (0x00000000) No user program can exist there

The null reference Consider: String s = “Hello world”; System.out.println (s.length()); What happens? Java prints out 11 s + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... String - text = “Hello world" - length = 11 - ...

The null reference Consider: String s = null; System.out.println (s.length()); This is called accessing (or following) a null pointer/reference What happens? Java: java.lang.NullPointerException C/C++: Segmentation fault (core dumped) Windows: …

What happens in Windows…

So what is a null reference good for? Let’s say you had a method that returned a String when passed some parameters Normally it returns a valid String But what if it can’t? How to deal with that? Return a null reference

Quick survey I understand null references… Pretty much Once I read the text, I’ll be good Not really What’s a reference again?

A bit of humor…

References and memory Most modern computers are 32-bit computers This means that a reference takes up 32 bits 232 = 4 Gb This means that a 32-bit machine cannot access more than 4 Gb of memory! Well, without doing some “tricks”, at least Most machines come with 1 Gb memory these days Will come with 4 Gb in a year or so 64-bit machines will have a maximum of 16 exabytes of memory Giga, Tera, Peta, Exa That’s 16 billion Gb!

References 4 What happens to this? Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); What happens to this? String s1 length = 12 “first string” “second string” length = 13 String s2

Java’s garbage collection If an object in memory does not have a reference pointing to it, Java will automagically delete the object This is really cool! In C/C++, you had to do this by yourself

Assignment Consider String word1 = "luminous"; String word2 = "graceful"; Word1 = word2; Initial representation Garbage collection time! word1 "graceful" word2 "luminous"

Using objects Consider Scanner stdin = new Scanner(System.in); System.out.print("Enter your account name: "); String response = stdin.next(); Suppose the user interaction is Enter your account name: artiste "artiste" reponse Scanner: stdin

String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; Standard shorthand representation Truer representation Another useful String member method is charAt(). This method expects a single index as its parameter and returns the value of the character at that position in its String. While such behavior seems relatively natural given the method name and its parameter, what is not natural is that in Java, as in several other programming languages, the first character of a String is located at index 0.

String representation Consider String alphabet = "abcdefghijklmnopqrstuvwxyz"; char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2); What are the values of c1, c2, and c3? Why? Another useful String member method is charAt(). This method expects a single index as its parameter and returns the value of the character at that position in its String. While such behavior seems relatively natural given the method name and its parameter, what is not natural is that in Java, as in several other programming languages, the first character of a String is located at index 0.

Program WordLength.java public class WordLength { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter a word: "); String word = stdin.next(); int wordLength = word.length(); System.out.println("Word " + word + " has length " + wordLength + "."); }

More String methods Consider String weddingDate = "August 21, 1976"; String month = weddingDate.substring(0, 6); System.out.println("Month is " + month + "."); What is the output? Month is August.

More String methods Consider String fruit = "banana"; String searchString = "an"; int n1 = fruit.indexOf(searchString, 0); int n2 = fruit.indexOf(searchString, n1 + 1); int n3 = fruit.indexOf(searchString, n2 + 1); System.out.println("First search: " + n1); System.out.println("Second search: " + n2); System.out.println("Third search: " + n3); What is the output? First search: 1 Second search: 3 Third search: -1

Quick survey I understand how one selects methods from an object. Absolutely! Kind of Not really What’s an object again?

Today’s dose of demotivators

End of lecture on 2 February 2005

Variables vs. Types The type is the recipe or template for how to create a variable Examples: int, double, char, boolean, etc. There are only 8 primitive types There are only two things you can do with a type: Declare a variable int x; Use it as a cast x = (int) 3.5; There is only one of each type The variable is the actual instance of a type in memory It’s a spot in memory where you store a value You choose the name: width, x, thatThemThereValue, etc. You can have as may variables as you want Like the difference between a recipe and a bunch of cookies

Quick survey I understand the difference between variables and types Very well With some review, I’ll be good Not really Not at all

Classes vs. Objects A class is a user-defined “thing” Examples: String, Scanner, Rectangle, etc. We’ll start defining our own classes next chapter Classes are more complex than the primitive types A class is analogous to a type It’s just more complex and user-defined There can be only one class of each name An object is an instance of a class There is only one String class, but you can have 100 String objects A object is analogous to a variable It just is a reference instead A class is a “template” used for creating objects

More on classes vs. objects

Quick survey I understand the difference between classes and objects Very well With some review, I’ll be good Not really Not at all

More String methods Consider int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); int v1 = -12; double v2 = 3.14; char v3 = 'a'; String s1 = String.valueOf(v1); String s2 = String.valueOf(v2); String s3 = String.valueOf(v3); v1 -12 v2 3.14 v3 ‘a’ "-12" s1 "3.14" s2 "a" s3

Final variables Consider final String POEM_TITLE = “Appearance of Brown"; final String WARNING = “Weather ball is black"; What is the representation? In Chapter we used modifier final to define primitive type constants. We can also use this modifier to define object constants. However, when an object constant is defined—be it String or any other object type—we are specifying only that the reference cannot be changed. That is, the constant must always refer to the same memory location. Although an object constant must always refer to the same memory location, it does not mean necessarily that the value stored at that location cannot be modified through its member methods.

Final variables The reference cannot be modified once it is established In general, these attributes can be modified through member methods Value object type constant In Chapter we used modifier final to define primitive type constants. We can also use this modifier to define object constants. However, when an object constant is defined—be it String or any other object type—we are specifying only that the reference cannot be changed. That is, the constant must always refer to the same memory location. Although an object constant must always refer to the same memory location, it does not mean necessarily that the value stored at that location cannot be modified through its member methods.

Rectangle int x = 3; y = 4; The upper-left-hand width = 5; height = 2; Rectangle r = new Rectangle(x, y, width, height); The upper-left-hand corner of the new Rectangle The dimensions of the new Rectangle

Final variables Consider final String LANGUAGE = "Java"; The reference cannot be modified once it is established "Java" LANGUAGE

Rectangle final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); Consider final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK.setLocation(1, 4); BLOCK.resize(8, 3); In Chapter we used modifier final to define primitive type constants. We can also use this modifier to define object constants. However, when an object constant is defined—be it String or any other object type—we are specifying only that the reference cannot be changed. That is, the constant must always refer to the same memory location. Although an object constant must always refer to the same memory location, it does not mean necessarily that the value stored at that location cannot be modified through its member methods.

String method usage String s = "Halloween"; x 10 y 4 String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; Consider: String s = "Halloween"; String t = "Groundhog Day"; String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; “Hallow" v + length () : int + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + indexOf ( String s ) : int + ... String - ... - text = “Halloween" - length = 9 - text = “May Day" - length = 7 - text = “Groundhog Day" - length = 13 s “Halloween" t “Groundhog Day" u “May Day"

String method usage Java error: cannot assign a value to final x 10 y 4 Consider: String s = "Halloween"; String t = "Groundhog Day"; final String u = "May Day"; String v = s.substring(0,6); int x = t.indexOf ("Day", 0); int y = u.indexOf ("Day"); s = t; u = null; s = t; u = null; “Hallow" v Java error: cannot assign a value to final variable u s “Halloween" t “Groundhog Day" u “May Day"

Rectangle method usage + setWidth ( int w ) + setHeight ( int wh ) + setX ( int x ) + setY ( int y ) + ... Rectangle Consider: Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15); Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (1, 2, 3, 4); r.setWidth(5); r.setHeight(6); s.setWidth (7); r = new Rectangle (8,9,10,11); s = new Rectangle (12,13,14,15); - width = 1 - height = 2 - x = 3 - y = 4 - width = 7 - height = 2 - x = 3 - y = 4 s r + setWidth ( int w ) + setHeight ( int wh ) + setX ( int x ) + setY ( int y ) + ... Rectangle - width = 5 - height = 6 - x = 0 - y = 0 - width = 5 - height = 0 - x = 0 - y = 0 - width = 0 - height = 0 - x = 0 - y = 0 + setWidth ( int w ) + setHeight ( int wh ) + setX ( int x ) + setY ( int y ) + ... Rectangle - width = 8 - height = 9 - x = 10 - y = 11

Scanner review To initialize a Scanner object: Scanner stdin = new Scanner (System.in); Scanner stdin = Scanner.create (System.in); This one will not work! To read an int from the keyboard: stdin.nextInt(); To read a double from the keyboard: stdin.nextDouble(); To read a String from the keyboard: stdin.next();

Scanner usage examples Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next(); Consider: Scanner stdin = new Scanner (System.in); int x = stdin.nextInt(); double d = stdin.nextDouble(); String s = stdin.next(); Scanner: stdin x 5 d 3.5 “hello world” s

Quick survey I felt I understood the material in this slide set… Very well With some review, I’ll be good Not really Not at all

Quick survey The pace of the lecture for this slide set was… Fast About right A little slow Too slow

Quick survey How interesting was the material in this slide set? Be honest! Wow! That was SOOOOOOO cool! Somewhat interesting Rather boring Zzzzzzzzzzz

A bit of humor…