Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 1 Stack and Heap

2 2 “Stack” Stack – a linear data structure in which items are added and removed in last-in, first-out order. Definition: context – the region of the stack that provides the execution environment of a particular call to a function

3 3 “Stack” Calling program  Push arguments & return address onto stack  After return, pop result off stack Called routine  Push registers and return address onto stack  Push temporary storage space onto stack  Pop registers and temporary storage off stack  Leave result on stack  Return to address left by calling routine

4 4 Stack Implementation  Usually, a linear piece of memory and a stack pointer contained in a (designated) register  Occasionally, a linked list Recursion  Stack discipline allows multiple contexts for the same function in the stack at the same time

5 5 Heap A place for allocating memory that is not part of last-in, first-out discipline I.e., dynamically allocated data structures that survive function calls  E.g., strings in C  new objects in C++, Java, etc.

6 6 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

7 7 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 0x00122155 ?? 0x00122155

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

9 9 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

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

11 11 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

12 12 The Stack and Heap String s = new String (“hello”); s “hello” java.lang.String Objects live on the Heap new creates an Object on the Heap Local variables live on the Stack Point to objects on the Heap String is a type in the Java API for representing sequences of characters

13 13 String s = new String (“hello”); s “hello” java.lang.String String t = s; t

14 14 String s = new String (“hello”); s “hello” java.lang.String String t = s; t s = new String (“goodbye”); “goodbye” java.lang.String

15 15 String s = new String (“hello”); s “hello” java.lang.String String t = s; t int i = 201; i 201 int j = i; j 201 How can we see the difference between primitive types and objects?

16 16 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? */

17 17 Primitive Types Not everything in Java is an Object Some types are primitive types  boolean, byte, char, double, float, int, long, short Values of primitive types are stored directly on the stack

18 18 Equality x == y Object Types: same objects Primitive Types: same value x.equals (y) Object Types: method that compares values of objects Primitive Types: doesn’t exist

19 Packages: Putting Classes Together 19

20 20 Introduction The main feature of OOP is its ability to support the reuse of code: The features in basic form limited to reusing the classes within a program. What if we need to use classes from other programs without physically copying them into the program under development ? In Java, this is achieved by using what is known as “packages”, a concept similar to “class libraries” in other languages.

21 Packages 21 Packages are Java’s way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as “containers” for classes. The benefits of organising classes into packages are:  The classes contained in the packages of other programs/applications can be reused.  In packages classes can be unique compared with classes in other packages. That two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name.  Classes in packages can be hidden if we don’t want other packages to access them.  Packages also provide a way for separating “design” from coding.

22 Package built in Package user- define 22

23 Java Foundation Packages 23 Java provides a large number of classes groped into different packages based on their functionality. The six foundation Java packages are:  java.lang  Contains classes for primitive types, strings, math functions, threads, and exception  java.util  Contains classes such as vectors, hash tables, date etc.  java.io  Stream classes for I/O  java.awt  Classes for implementing GUI – windows, buttons, menus etc.  java.net  Classes for networking  java.applet  Classes for creating and implementing applets

24 Using System Packages 24 The packages are organised in a hierarchical structure. For example, a package named “java” contains the package “awt”, which in turn contains various classes required for implementing GUI (graphical user interface). Graphics Font java Image … awt lang “java” Package containing “lang”, “awt”,.. packages; Can also contain classes. awt Package containing classes Classes containing methods

25 java.lang Package Basic class to enlarge the function of Java Provide classes according to primitive type (wrapper class)  Integer class, Double class,... 25

26 java.lang Class Object Number Integer Long Float Double Character System String StringBuffer Boolean Wrapper Class 26

27 Object Class Super class of all classes All classes are to inherit the methods of Object class Method  Object clone() : To copy the object equally  boolean equals(Object obj) :  Compare the object as parameter with the object which calls this method  int hashCode() : Calculate the hash code value of the object  Class getClass() : To get Class object corresponding to object  String toString() : Convert the object into string  wait(), notify() : To control the status of thread 27

28 Accessing Classes from Packages 28 There are two ways of accessing the classes stored in packages:  Using fully qualified class name  java.lang.Math.sqrt(x);  Import package and use class name directly.  import java.lang.Math  Math.sqrt(x); Selected or all classes in packages can be imported: Implicit in all programs: import java.lang.*; package statement(s) must appear first import package.class; import package.*;

29 Creating Packages 29 Java supports a keyword called “package” for creating user-defined packages. The package statement must be the first statement in a Java source file (except comments and white spaces) followed by one or more classes. Package name is “myPackage” and classes are considred as part of this package; The code is saved in a file called “ClassA.java” and located in a directory called “myPackage”. package myPackage; public class ClassA { // class body } class ClassB { // class body }

30 Creating Sub Packages 30 Classes in one ore more source files can be part of the same packages. As packages in Java are organised hierarchically, sub-packages can be created as follows:  package myPackage.Math  package myPackage.secondPakage.thirdPackage Store “thirdPackage” in a subdirectory named “myPackage\secondPackage”. Store “secondPackage” and “Math” class in a subdirectory “myPackage”.

31 Accessing a Package 31 As indicated earlier, classes in packages can be accessed using a fully qualified name or using a short-cut as long as we import a corresponding package. The general form of importing package is:  import package1[.package2][…].classname  Example:  import myPackage.ClassA;  import myPackage.secondPackage  All classes/packages from higher-level package can be imported as follows:  import myPackage.*;

32 Compiling and Running 32 When ClassX.java is compiled, the compiler compiles it and places.class file in current directly. If.class of ClassA in subdirectory “myPackage” is not found, it comples ClassA also. Note: It does not include code of ClassA into ClassX When the program ClassX is run, java loader looks for ClassA.class file in a package called “myPackage” and loads it.

33 Using a Package 33 Let us store the code listing below in a file named “ClassA.java” within subdirectory named “secondPackage” within the current directory (say “abc”). package secondPackage; public class ClassC { // class body public void display() { System.out.println("Hello, I am ClassC"); }

34 Using a Package 34 Within the current directory (“abc”) store the following code in a file named “ClassX.java” import myPackage.ClassA; import secondPackage.ClassC; public class ClassY { public static void main(String args[]) { ClassA objA = new ClassA(); ClassC objC = new ClassC(); objA.display(); objC.display(); }

35 Using a Package 35 Let us store the code listing below in a file named “ClassA.java” within subdirectory named “myPackage” within the current directory (say “abc”). package myPackage; public class ClassA { // class body public void display() { System.out.println("Hello, I am ClassA"); } class ClassB { // class body }

36 Using a Package 36 Within the current directory (“abc”) store the following code in a file named “ClassX.java” import myPackage.ClassA; public class ClassX { public static void main(String args[]) { ClassA objA = new ClassA(); objA.display(); }


Download ppt "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."

Similar presentations


Ads by Google