CS 307 Fundamentals of Computer Science 1 Java Basics – Pointers and Object Variables -Topic 3 ` Or else it doesn't, you know. The name of the song is.

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

SPL/2010 Pointers and Parameter Passing in C++ 1.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Road Map Introduction to object oriented programming. Classes
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
CS 536 Spring Run-time organization Lecture 19.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
CS 307 Fundamentals of Computer ScienceReferences and Object Variables 1 Topic 3 References and Object Variables "Thou shalt not follow the NULL pointer,
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Lesson 9 Pointers CS 1 Lesson 9 -- John Cole1. Pointers in Wonderland The name of the song is called ‘Haddock’s Eyes’.” “Oh, that’s the name of the song,
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Objects and Variables Local variables – Confined to single context: allocated on stack – Primitive types such as int or object references – Must be initialized.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Memory Management in Java Mr. Gerb Computer Science 4.
1 Stack and Heap. 2 “Stack” Stack – a linear data structure in which items are added and removed in last-in, first-out order. Definition: context – the.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Design issues for Object-Oriented Languages
Dynamic Allocation in C
Object Lifetime and Pointers
Dynamic Storage Allocation
Data Types In Text: Chapter 6.
Advanced Program Design with C++
Pointers Revisited What is variable address, name, value?
Dynamic Memory CSCE 121 J. Michael Moore.
Pointers and References
Dynamic Memory Allocation
Pointer Basics Psst… over there.
Object Oriented Programming COP3330 / CGS5409
Chapter 12 Pointers and Memory Management
Topic 1 - Java Review.
Truth or Consequences A Discussion of Java’s Memory Model
Pointer Basics Psst… over there.
Dynamic Memory CSCE 121.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CS 307 Fundamentals of Computer Science 1 Java Basics – Pointers and Object Variables -Topic 3 ` Or else it doesn't, you know. The name of the song is called "HADDOCKS' EYES." ' `Oh, that's the name of the song, is it?' Alice said, trying to feel interested. `No, you don't understand,' the Knight said, looking a little vexed. `That's what the name is CALLED. The name really IS "THE AGED AGED MAN."' `Then I ought to have said "That's what the SONG is called"?' Alice corrected herself. `No, you oughtn't: that's quite another thing! The SONG is called "WAYS AND MEANS": but that's only what it's CALLED, you know!' `Well, what IS the song, then?' said Alice, who was by this time completely bewildered. `I was coming to that,' the Knight said. `The song really IS "A-SITTING ON A GATE": and the tune's my own invention.' - Lewis Carroll, Through the Looking Glass

CS 307 Fundamentals of Computer Science 2 Object Variables  object variables are declared by stating the class name / data type and then the variable name –same as primitives –in Java there are hundreds of built in classes. –don't learn the classes, learn how to read and use a class interface (the users manual)  objects are complex variables. They have an internal state and various behaviors that can either change the state or simply tell something about the object public void objectVariables() {Rectangle rect1; Rectangle rect2; // 2 Rectangle objects exist?? // more code to follow }

CS 307 Fundamentals of Computer Science 3 Onto Object Variables  So now there are 2 Rectangle objects right?  Not so much.  Object variables in Java are actually references to objects, not the objects themselves! –object variables store the memory address of an object of the proper type not an object of the proper type. –contrast this with primitive variables public void objectVaraiables() {Rectangle rect1; Rectangle rect2; // 2 Rectangle objects exist?? // more code to follow }

CS 307 Fundamentals of Computer Science 4 The Pointer Sidetrack  A pointer is a variable that stores the memory address of where another variable is stored  In some languages you can have static variables (nothing to do with the static keyword) and dynamic variables of any type  Example C++, can have a, integer variable or a integer pointer (which is still a variable) int intVar; // a int var int * intPtr; //pointer to an int var

CS 307 Fundamentals of Computer Science 5 int intVar = 5; // a int var int * intPtr; //pointer to an int var intPtr = new int; /* dynamically allocate an space to store an int. intPtr holds the memory address of this space*/ Pointer Variables in C++ intVar 5 intPtr ?? space for an int in memory assume memory address 0x ?? 0x

CS 307 Fundamentals of Computer Science 6 Pointer Complications  C++ allows actual variables and pointers to variables of any type. Things get complicated and confusing very quickly  In C++ you can work directly with the memory address stored in intPtr –increment it, assign it other memory addresses, pointer “arithmetic” int intVar = 5; // a int var int * intPtr; //pointer to an int var intPtr = new int; // allocate memory *intPtr = 12; /* assign the integer being pointed to the value of 12. Must dereference the pointer. i.e. get to the thing being pointed at*/ cout << intPtr << "\t" << *intPtr << "\t" << &intPtr << endl; // 3 different ways of manipulating intPtr

CS 307 Fundamentals of Computer Science 7 Benefit of Pointers  Why have pointers?  To allow the sharing of a variable –If several variables(objects, records, structs) need access to another single variable two alternatives 1. keep multiple copies of variable. 2. share the data with each variable keeping a reference to the needed data shared variable sharer 2 sharer 1 ptr other data not shown other data not shown

CS 307 Fundamentals of Computer Science 8 More Benefits  Allow dynamic allocation of memory –get it only when needed (stack memory and heap memory)  Allow linked data structures such as linked lists and binary trees –incredibly useful for certain types of problems  Pointers are in fact necessary in a language like Java where polymorphism is so prevalent (more on this later)  Now the good news –In Java most of the complications and difficulties inherent with dealing with pointers are removed by some simplifications in the language

CS 307 Fundamentals of Computer Science 9 Dynamic Memory Allocation Your program has two chunks of memory to work with: Stack memory (or the runtime Stack) and Heap memory When a Java program starts it receives two chunks of memory one for the Stack and one for the Heap. Things that use Stack memory: local variables, parameters, and information about methods that are in progress. Things that use Heap memory: everything that is allocated using the new operator.

CS 307 Fundamentals of Computer Science 10 The Picture Stack MemoryHeap Memory void toyCodeForMemory(int x) { int y = 10; x += y; String s = new String("Hello"); System.out.println(x + " " + y + s); } x y s String Object myChars H e l l o

CS 307 Fundamentals of Computer Science 11 How Much Memory? How big is the Heap? System.out.println("Heap size is " + Runtime.getRuntime().totalMemory()); How much of the Heap is available? System.out.println("Available memory: " + Runtime.getRuntime().freeMemory());

CS 307 Fundamentals of Computer Science 12 Pointers in Java  In Java all primitive variables are value variables. (real, actual, direct?) –it is impossible to have an integer pointer or a pointer to any variable of one of the primitive data types  All object variables are actually reference variables (pointers, memory addresses) to objects. –it is impossible to have anything but pointers to objects. You can never have a plain object variable

CS 307 Fundamentals of Computer Science 13 Back to the Rectangle Objects  rect1 and rect2 are variables that store the memory addresses of Rectangle objects  right now they are uninitialized and since they are local, variables may not be used until they are given some value  null is used to indicate an object variable is not pointing / naming / referring to any Rectangle object. public void objectVaraiables() {Rectangle rect1; Rectangle rect2; // rect1 = 0; // syntax error, C++ style // rect1 = rect2; // syntax error, unitialized rect1 = null; // pointing at nothing rect2 = null; // pointing at nothing }

CS 307 Fundamentals of Computer Science 14 Creating Objects  Declaring object variables does not create objects. –It merely sets aside space to hold the memory address of an object. –The object must be created by using the new operator and calling a constructor for that object  For all objects, the memory needed to store the objects, is allocated dynamically using the new operator and a constructor call. (Strings are a special case.) –constructors are similar to methods, but they are used to initialize objects public void objectVaraiables() {Rectangle rect1; rect1 = new Rectangle(); Rectangle rect2 = new Rectangle(5,10,20,30); // (x, y, width, height) // rect1 and rect2 now refer to Rectangle objects }

CS 307 Fundamentals of Computer Science 15 The Yellow Sticky Analogy rect1 Rectangle Object x: 0 y: 0 width: 0 height: 0 rect2 Rectangle Object x: 5 y: 10 width: 20 height: 30

CS 307 Fundamentals of Computer Science 16 Pointers in Java  Is this easier? –primitives one thing, objects another?  can't get at the memory address the pointer stores as in C++ although try this: Object obj = new Object(); System.out.println( obj.toString() );  dereferencing occurs automatically  because of the consistency the distinction between an object and an object reference can be blurred –"pass an object to the method" versus "pass an object reference to the method  Need to be clear when dealing with memory address of object and when dealing with the object itself

CS 307 Fundamentals of Computer Science 17 Working with Objects  Once an object is created and an object variable points to it then Object may be manipulated via its methods  Use the dot operator to deference an object variable and invoke one of the objects behaviors  Available behaviors are spelled out in the class of the object, (the data type of the object) Rectangle r1 = new Rectangle(); r1.resize(100, 200); r1.setLocation(10, 20); int area = r1.getWidth() * r1.getHeight(); Rectangle r2 = null; r2.resize( r1.getWidth(), r1.getHeight() * 2 ); // uh-oh!

CS 307 Fundamentals of Computer Science 18 What's the Output? (Or, do you understand how object variables and pointers work?) public void objectVariables(String[] args) {Rectangle rect1 = new Rectangle(5, 10, 15, 20); Rectangle rect2 = new Rectangle(5, 10, 15, 20);; System.out.println("rect 1: " + rect1.toString() ); System.out.println("rect 2: " + rect2.toString() ); System.out.println("rect1 == rect2: " + (rect1 == rect2)); rect1 = rect2; rect2.setSize(50, 100); // (newWidth, newHeight) System.out.println("rect 1: " + rect1.toString() ); System.out.println("rect 2: " + rect2.toString() ); System.out.println("rect1 == rect2: " + (rect1 == rect2)); int x = 12; int y = 12; System.out.println("x == y: " + (x == y) ); x = 5; y = x; x = 10; System.out.println("x == y: " + (x == y) ); System.out.println("x value: " + x + "\ty value: " + y); }

CS 307 Fundamentals of Computer Science 19 Equality versus Identity  confusion over equality and identity  identity: two things are in fact the same thing  equality: two things are for all practical purposes alike, but not the exact same thing  == versus the.equals method –use the.equals method when you want to check the contents of the pointee, use == when you want to check memory addresses A man walks into a pizza parlor, sits down, and tells the waiter, "I'll have what that lady over there is eating." The waiter walks over to the indicated lady, picks up the pizza that is resting in front of her, and sets it back down in from of the man's table.

CS 307 Fundamentals of Computer Science 20 The Garbage Collector  If objects are allocated dynamically with new how are they deallocated? –delete in C++  If an object becomes isolated (no longer is in scope), that is has no references to it, it is garbage and the Java Virtual Machine garbage collector will reclaim this memory AUTOMATICALLY! Rectangle rect1 = new Rectangle(2,4,10,10); Rectangle rect2 = new Rectangle(5,10,20,30); // (x, y, width, height) rect1 = rect2; /*what happened to the Rectangle Object rect1 was pointing at? */

CS 307 Fundamentals of Computer Science 21 Objects as Parameters  All parameters in Java are value parameters  The method receives a copy of the parameter, not the actual variable passed  Makes it impossible to change a primitive parameter  implications for objects? (which are references) –behavior that is similar to a reference parameter, with a few minor, but crucial differences –"Reference parameter like behavior for the pointee."

CS 307 Fundamentals of Computer Science 22 Immutable Objects  Some classes create immutable objects  Once created these objects cannot be changed –note the difference between objects and object variables  Most immediate example is the String class  String objects are immutable  Why might this be useful? String name = "Mike"; String sameName = name; name += " " + "David" + " " + "Scott"; System.out.println( name ); System.out.println( sameName );