Download presentation
Presentation is loading. Please wait.
Published byChrystal Allen Modified over 9 years ago
1
1 JAVA & MEMORY What did I just say this topic was about ?
2
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
3 Resources:Java & Memory Lambert Comprehensive Lecture p. 9 – 14 C++ Chapter 1 Class Notes Big Java Chapter 7 p.290-291
4
4 Handouts: 1.PassingAnObjrectExample.java 2.dateClass.java
5
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
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
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
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
9 CPU --- central processing unit Bus --- parallel lines connecting the CPU to memory. Computer performance is dependant on Bus speed and width.
10
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
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
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
13 Computer memory 256 characters is 2 to the 8th power ex/ A = 01000001 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
14 Computer memory a BYTE counts bits from right to left 7 6 5 4 3 2 1 0 ---- 0 is least significant bit/ low order bit [2 to 0 power] 7 is most significant/ high order bit [2 to 7 power]
15
15 Computer memory Binary (base 2 ) numbering system 000010001 in base 2 or binary = 17 in base 10 11111111 in base 2 or binary = 255 in dec
16
16 Computer memory Refer to The Handout and discuss: Binary Math Hexidecimal
17
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
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
19 SPVM // last function to exit { int Lint; doit(); } public static void doit() { int Lint; String myString = new String; }
20
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
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
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
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
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
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
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
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
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
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
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
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
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
33 Example: static public void changeDate(date d) { d.setYear(2003); return; }
34
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
35 Therefore, when we call a set method for this reference we ARE ACTUALLY MODIFYING the original object !!! Hence the output…. 12-1900 And now the same instance AFTER the function call... 12-2003
36
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 12 1 1900 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
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
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
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
40 Hence the output from WITHIN the function… local date var d After reassigned 12-2001 However, the following statement from SPVM will show it’s date variable “d” is still 12-2003 System.out.println(myDate.toString());
41
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
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
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
44 TPS: Comment out the date class set methods and see if you are able to mutate the SPVM object from A function
45
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
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
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
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
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
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
51 TPS:Try this with strings (add to your current program)
52
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
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
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: 04-2002
55
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
56 This example uses several concepts that need to be reviewed
57
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
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
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
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
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
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
63 Projects: Identify Arguments in MBS Design Part of Tic-Tac-Toe Object Based Bubble Sort
64
64 TEST IS THE DAY AFTER THE PROJECT IS DUE !!!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.