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

Click here to load reader

  • date post

  • Category


  • view

  • download


Embed Size (px)

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

  • JAVA & MEMORYWhat did I just say this topic was about ?

  • 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

  • Resources:Java & Memory

    Lambert Comprehensive Lecture p. 9 14

    C++ Chapter 1 Class Notes

    Big Java Chapter 7 p.290-291

  • Handouts:


  • 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.

  • 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 (!)

  • CPU --- central processing unit Reads in bits of data from memoryReads 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 registersRegisters are memory cells that are used to hold memory addresses and intermediate results

  • 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).

  • CPU --- central processing unit

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

  • RAM --- Random Access Memory

    Gas in the tank to engine analogyLinear array of bits for storing informationByte = a group of 8 bits640K 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

  • 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

  • Computer memory

    Each computer memory location holds 8 bits or 1 byte because it takes a combination Of 8 0s and 1s to represent a character (ASCII)

    Because each byte of memory Can hold exactly 1 character: 8 bits = 1 byte

  • Computer memory

    256 characters is 2 to the 8th powerex/ A = 01000001 or ACSII value 65bit = 0 or 1 state of electricity8 bits = 1 byte1 byte = 1 character2 bytes = a computer word of memory

  • Computer memory

    a BYTE counts bits from right to left7 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]

  • Computer memory

    Binary (base 2 ) numbering system

    000010001 in base 2 or binary = 17 in base 1011111111 in base 2 or binary = 255 in dec

  • Computer memory

    Refer to The Handout and discuss:

    Binary Math


  • Dynamic Storage Management ---

    Global and STATIC variables are stored in Static Storage

    SPVMs variables are stored in the RUNTIME STACK along with any Static functions variables

  • Dynamic Storage Management ---

    Dynamically allocated memory, requested by the NEW function, resides in The memory HEAPNEW also invokes the class/objects constructor

    New provides us with a REFERENCE to the actual HEAP location of an Object

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

  • Memory Allocation:LIntDoits stack Main()s stack Static stack Ref to myStringLintGlobals


    myString stateful propertiesStack Growth

  • 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( );

  • 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

  • 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

  • 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

  • Example:SPVMint a, b = 21;a = myClassInstance.callAMethod( b );CLASSpublic integer callAMethod( int x){ int z = 0; x++; z += x; return z;}

  • 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

  • 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.

  • 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

  • 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

  • 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.

  • 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

  • Example:SPVM// imported is the dateclass as used in last // years midterm dateClass.javadate 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());

  • Example:

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

  • 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

  • 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...


  • TPS:1.Illustrate this by using the Memory diagram2.Write a simple date class consisting of:m, d, y class level attributesappropriate gets and setsdefault constructor setting valies to 12 1 1900overloaded constructor that accepts m,d,y3.Create a wrapper class and import your date class4.Add in a function that accepts & modifies a date object (reference)5.In SPVM create an instance of the date class and call the function6.Print out the states of the states of the objectWhy does or why CAN the function mutate SPVMs local object ?

  • However, if you CHANGE the reference of the passed argument to point to a new objects reference, the ORIGINAL object will remain UNCHANGED


  • 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;}

  • 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

  • Hence the output from WITHIN the function

    local date var d After reassigned 12-200