1 JAVA & MEMORY What did I just say this topic was about ?

Slides:



Advertisements
Similar presentations
Chapter 16 Java Virtual Machine. To compile a java program in Simple.java, enter javac Simple.java javac outputs Simple.class, a file that contains bytecode.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Room: E-3-31 Phone: Dr Masri Ayob TK 2123 COMPUTER ORGANISATION & ARCHITECTURE Lecture 5: CPU and Memory.
VBA Modules, Functions, Variables, and Constants
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
CSCE 121, Sec 200, 507, 508 Fall 2010 Prof. Jennifer L. Welch.
Chapter 4 Processor Technology and Architecture. Chapter goals Describe CPU instruction and execution cycles Explain how primitive CPU instructions are.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Names and Bindings Introduction Names Variables The concept of binding Chapter 5-a.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter 7 Objects and Memory. Structure of memory The fundamental unit of memory is called a bit, either 0 or 1. In most modern architectures, the smallest.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
IT253: Computer Organization Lecture 4: Instruction Set Architecture Tonga Institute of Higher Education.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Mason Vail.  A data type definition – “blueprint for objects”  Includes properties and/or methods ◦ “instance” data / methods – specific to one object.
Compiler Construction
The Central Processing Unit: What Goes on Inside the Computer
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Advanced topic - variable.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
More C++ Features True object initialisation
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Object Oriented Software Development 4. C# data types, objects and references.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Variables and memory addresses
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Hello world !!! ASCII representation of hello.c.
Operating Systems A Biswas, Dept. of Information Technology.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
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.
Stack and Heap Memory Stack resident variables include:
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Java Review: Reference Types
Introduction to Data Structure
Information Representation: Machine Instructions
References Revisted (Ch 5)
Classes and Objects Object Creation
SPL – PS2 C++ Memory Handling.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

1 JAVA & MEMORY What did I just say this topic was about ?

2 Purpose: In this lecture series we will learn the following: How Java works with the memory of the computer system How Java primitives and class objects are treated when used as arguments Returning objects from functions and methods

3 Resources:Java & Memory Lambert Comprehensive Lecture p. 9 – 14 C++ Chapter 1 Class Notes Big Java Chapter 7 p

4 Handouts: 1.PassingAnObjrectExample.java 2.dateClass.java

5 Intro: In this lecture Java & Memory, understanding how java handles computer memory is important when allocating and modifying instances of classes. Also, the concept of passing by value when dealing with primitives versus references is a critical concept to grasp.

6 Java and Memory: John Von Neumann --- Princeton Mathematician developed the idea that a computer program can reside in memory in the form of CPU instructions. Most computers are based on the Von Neuman Architecture. Reasoned that all arithmetic operations can be reduced to 3 simple Logical operations: and(&&), or (||), not (!)

7 CPU --- central processing unit Reads in “bits” of data from memory Reads in and processes one instruction at a time --- fetches the next instruction from Memory, interprets its code, performs the operation. Consists of an instruction set and internal registers Registers are memory cells that are used to hold memory addresses and intermediate results

8 CPU --- central processing unit Instruction sets include instructions for loading CPU registers from memory, logical and arithmetic operations, altering the sequence of operations Internal CLOCK and the CPU speed depends on the frequency of the clock (MHZ --- megahertz or million pulses per second).

9 CPU --- central processing unit Bus --- parallel lines connecting the CPU to memory. Computer performance is dependant on Bus speed and width.

10 RAM --- Random Access Memory Gas in the tank to engine analogy Linear array of bits for storing information Byte = a group of 8 bits 640K was thought of as enough. Segment registers were added to get memory to 1MEG. 32-bit memory that allows up to 4 gig of memory

11 Computer memory Each memory location holds one byte or a single character of information. 1 Byte(8 bits) Kilobyte (1024 or 2 to the 10th power) Megabyte (1,024,000 or 2 to the 20th power) Gig (1,073,741,824 bytes of 2 to the 30th power), Terabyte

12 Computer memory Each computer memory location holds 8 bits or 1 byte because it takes a combination Of 8 0’s and 1’s to represent a character (ASCII) Because each byte of memory Can hold exactly 1 character: 8 bits = 1 byte

13 Computer memory 256 characters is 2 to the 8th power ex/ A = or ACSII value 65 bit = 0 or 1 state of electricity 8 bits = 1 byte 1 byte = 1 character 2 bytes = a computer word of memory

14 Computer memory a BYTE counts bits from right to left is least significant bit/ low order bit [2 to 0 power] 7 is most significant/ high order bit [2 to 7 power]

15 Computer memory Binary (base 2 ) numbering system in base 2 or binary = 17 in base in base 2 or binary = 255 in dec

16 Computer memory Refer to The Handout and discuss: Binary Math Hexidecimal

17 Dynamic Storage Management --- Global and STATIC variables are stored in Static Storage SPVM’s variables are stored in the RUNTIME STACK along with any Static functions’ variables

18 Dynamic Storage Management --- Dynamically allocated memory, requested by the NEW function, resides in The memory HEAP NEW – also invokes the class/objects constructor New provides us with a REFERENCE to the actual HEAP location of an Object

19 SPVM // last function to exit { int Lint; doit(); } public static void doit() { int Lint; String myString = new String; }

20 Memory Allocation: LInt Doit’s stack  Main()’s stack  Static stack  Ref to myString Lint Globals HEAP “NEW” myString stateful properties Stack Growth

21 Memory Allocation: Last function called is the first to exit “UNWINDING THE STACK” JAVA performs garbage collection for heap memory that goes out of scope (no longer used). You can request garbage collection with System.gc( );

22 TPS: Given the code Handout, draw the appropriate Memory Stack. Be sure to allocate In the correct scope. Illustrate how the stack will eventually “Unwind”

23 Passing Arguments: Value VS Reference Arguments to class methods or static functions are Always passed by value Even references to objects are passed by value By “value” we mean a COPY of the argument is passed

24 How this works with primitive data types: That is, when you pass a primitive data type as an argument to a method, a “copy” of that variable is passed. The method called is passed the value in the argument and it becomes, in effect, a local variable of that method. This is called “Call by Value”

25 Example: SPVM… int a, b = 21; a = myClassInstance.callAMethod( b ); CLASS… public integer callAMethod( int x) { int z = 0; x++; z += x; return z; }

26 NOTE: the class method increments the variable x, however the variable x is LOCAL to the method and therefore the integer passed in SPVM, b, IS NOT modified There is NO WAY in Java to explicitly pass a primitive data type to a function or method BY REFERENCE as they ARE ALWAYS passed BY VALUE

27 TPS:See how this fits into the Memory diagram (note local primitives have a defined scope and can not be mutated from outside that scope) Write a similar program and see if you can in any way get the original primitive mutated by Calling a function & passing it as an argument. Use System.out to display the primitive throughout the process.

28 How this works with OBJECTS: Instances of Objects passed as arguments to class methods or functions are also passed BY VALUE However, there is a major difference when dealing with Instances of Objects Remember that objects (implicitly as with Strings or explicitly as with your own classes) are DYNAMICALLY ALLOCATED via the NEW operator

29 How this works with OBJECTS: When you dynamically allocate an instance of an Object as a class level attribute or as a local variable you get a REFERENCE (their memory address) to that instances / objects ACTUAL memory location in the HEAP

30 For Example: Button b = new Button(); The variable b is NOT an object, it is simply a REFERENCE to an object of type Button, hence the term “reference variable” b is defined in the runtime stack and simply POINTS to the place in the heap where the ACTUAL Object is stored.

31 So when you pass an object instance as an argument you are actually passing A COPY OF THAT REFERENCE (memory address) Because the called method or function now has the address of the actual OBJECT INSTANCE the ORIGINAL object instance can have its stateful properties modified in the called routine

32 Example: SPVM… // imported is the dateclass as used in last // years midterm dateClass.java date myDate = new date(); System.out.println(myDate.toString()); System.out.println("and now the same instancce AFTER the function call..."); changeDate(myDate); System.out.println(myDate.toString());

33 Example: static public void changeDate(date d) { d.setYear(2003); return; }

34 See that in SPVM we created an instance of the class dateClass The variable myDate became a reference to the actual object (stateful properties ) and this object resides in the heap Because we are passing a reference to an object this argument is passing a copy of the ACTUAL reference location of the actual object

35 Therefore, when we call a set method for this reference we ARE ACTUALLY MODIFYING the original object !!! Hence the output… And now the same instance AFTER the function call

36 TPS: 1.Illustrate this by using the Memory diagram 2.Write a simple date class consisting of: m, d, y class level attributes appropriate gets and sets default constructor setting valies to overloaded constructor that accepts m,d,y 3.Create a wrapper class and import your date class 4.Add in a function that accepts & modifies a date object (reference) 5.In SPVM create an instance of the date class and call the function 6.Print out the states of the states of the object Why does or why CAN the function mutate SPVM’s local object ?

37 However, if you CHANGE the reference of the passed argument to point to a new object’s reference, the ORIGINAL object will remain UNCHANGED Example…

38 static public void changeDate(date d) { d.setYear(2003); // now assign to a new date object and make a change // since d will now refer to a different object // any changes made to d will NOT BE REFLECTED in the // original reference (in SPVM) date localDate = new date(12,31,2001); d = localDate; System.out.println("local date var d After reassigned " + localDate.toString()); return; }

39 In this example we assign the local reference to a different instance of the date class By doing so, we have ONLY modified the local reference and NOT THE original reference in SPVM Therefore, any modifications made to the local reference d are local to the changeDate function

40 Hence the output from WITHIN the function… local date var d After reassigned However, the following statement from SPVM will show it’s date variable “d” is still System.out.println(myDate.toString());

41 TPS: 1.Illustrate this by using the Memory diagram 2.Add in a function that accepts a date object (reference) and assigns a local instance of the date class 3.Print out the states of the states of the object Why can’t the function mutate SPVM’s local object anymore ?

42 Things are a little different when dealing with Strings: When dealing with the String class, there are no methods that mutate the state of the string

43 Because Strings are immutable there is no way to modify a string parameter passed to a function or method (as can be done with other objects) Think of this as using the date class but REMOVING the set methods !!!

44 TPS: Comment out the date class set methods and see if you are able to mutate the SPVM object from A function

45 String myString = new String(); // you can also say: String myString = new String(“Hello”); myString = “Hello “; changeString(myString); System.out.println(myString); static public void changeString(String s) { s += " World"; System.out.println(s); s = new String("xyz"); System.out.println(s); return; }

46 However, because objects' references are passed by value, if we were to change the reference of the object variable this change IS NOT REFLECTED in the called instance object as the reference s is a COPY of the original and when we say s += " World" WE ARE ACTUALLY doing s = s + “ World”

47 In so doing the RVALUE uses the initial state of s, Hello, and adds World to a temporary reference when the assignment, =, is made the reference s is overwritten to point to a new string reference

48 Because of this, the reference to s as was initially passed in as an argument is NO LONGER pointing to the original. The original remains unchanged. This is because the String is IMMUTABLE !!!

49 The console will display “Hello World” as the function changeString is passed the address of / reference to instance of the object String, myString Therefore, this function can call any of the instance methods and modify accessible stateful properties

50 This illustrates the fact that, in Java, a method can change the state of an object reference parameter, but it can not replace the object reference with another Hence the output for this is… Hello World xyz Hello

51 TPS:Try this with strings (add to your current program)

52 You can also return an instance of an object (you are returning a REFERENCE to that instance) from a method or function: Example:

53 // return an object reference date newDate = new date(returnReference()); System.out.println(newDate); // implicit // call to the date classes toString() // method static public date returnReference() { date localDate = new date(04,15,2002); return localDate; }

54 In this example, we are calling a function that builds and returns a reference to a new date object We can do this because the date class has an overloaded constructor that accepts as an argument an instance of the date class Hence the output:

55 Lets take a closer look at this example by also examining the date class code: public date(date d) { this.setMonth(d.getMonth()); // could also say: this.month = // d.month; this.setYear(d.getYear()); this.setDay(d.getDay()); }

56 This example uses several concepts that need to be reviewed

57 First, note that in SPVM we say System.out.println(newDate); We can do this because, by default, any classes toString( ) method is implicitly called when NO OTHER method is invoked

58 Second, within the date class constructor we see that the this reference is used this refers to the instance of the class itself, in our case it refers to the object referred to by the reference variable newDate The date argument passed in, d, refers to the localDate created within the returnReference( ) function

59 Also, if you were careful enough to read the comment in the overloaded date constructor you would See that we could have simply assigned the class level attributes directly !!! The question that you should have is, how can this be possible when these attributes are PRIVATE and as such the attributes of the object passed in to the constructor SHOULD NOT BE AVAILABLE Outside the class

60 Well, they are not actually OUTSIDE the class Since we are dealing with two instances of the SAME class, WITHIN the methods of the class ANY instance can access the private attributes of any other instance !!!

61 TPS: Modify your date class to contain an overloaded constructor that takes an instance of itself as an argument. Try out the various ways to accomplish the copying of the stateful properties. Use this

62 What are the implications of passing references to methods or functions ? You can not protect or encapsulate an object instance once it is passed to a method In C++, you have the option of passing arguments by value, by reference or by constant reference

63 Projects:  Identify Arguments in MBS  Design Part of Tic-Tac-Toe  Object Based Bubble Sort

64 TEST IS THE DAY AFTER THE PROJECT IS DUE !!!