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.

Slides:



Advertisements
Similar presentations
1 Packages: Putting Classes Together. 2 Introduction The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance)
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Stacks and HeapsCS-3013 A-term A Short Digression on Stacks and Heaps CS-3013 Operating Systems A-term 2008 (Slides include materials from Modern.
Digression on Stack and Heaps CS-502 (EMC) Fall A Short Digression on Stacks and Heaps CS-502, Operating Systems Fall 2009 (EMC) (Slides include.
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.
CS 3013 & CS 502 Summer 2006 Digressions:– Producer-Consumer and Stacks 1 Two Digressions Stacks Producer-Consumer models.
1 Lecture 2 Java Packages  What are Java packages?  Why do wee need packages?  How to create a Java package?  Some examples.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
CS 307 Fundamentals of Computer ScienceReferences and Object Variables 1 Topic 3 References and Object Variables "Thou shalt not follow the NULL pointer,
OOP Languages: Java vs C++
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Runtime Environments Compiler Construction Chapter 7.
Chapter 2: Everything is an Object ● C++ has many non object oriented features inherited from C. It is a hybrid language meaning that it support different.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
1 Comp 104: Operating Systems Concepts Java Development and Run-Time Store Organisation.
Compiler Construction
CPSC 388 – Compiler Design and Construction Runtime Environments.
2: Everything is an Object You Manipulate Objects Using References Primitives Arrays in Java Scoping You Never Destroy Objects Creating New Data Types:
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Basic Semantics Associating meaning with language entities.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Peyman Dodangeh Sharif University of Technology Fall 2013.
成都信息工程学院 计算机系 1 Java 程序设计 Java Programming Fall, 2010.
Class Libraries Chapter 1 1 Source Intro to Java Programming Y. Daniel Liang.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright Curt Hill Variables What are they? Why do we need them?
Data Types – Reference Types Objective To understand what reference types are The need to study reference types To understand Java standard packages To.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
JAVA INTRODUCTION. What is Java? 1. Java is a Pure Object – Oriented language 2. Java is developing by existing languages like C and C++. How Java Differs.
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Packages. The main feature of OOP is its ability to support the reuse of code: –Extending the classes –Extending interfaces The features in basic form.
Java Package Advantage of Java Package
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Data Types – Reference Types Objective To understand what reference types are The need to study reference types To understand Java standard packages To.
Object-Oriented Programming and Problem Solving Dr. Ramzi Saifan Introduction and basics of Java Slides adapted from Steven Roehrig.
RealTimeSystems Lab Jong-Koo, Lim
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Design issues for Object-Oriented Languages
Java Memory Management
“Packages in Java”.
Java Memory Management
Inheritance-Basics.
Packages When we name a program , we name it by class name…
Programming Language Concepts (CIS 635)
Outline for this evening
Object Oriented Programming
Applying OO Concepts Using Java
PACKAGES.
Object Oriented Programming in java
Corresponds with Chapter 5
Topic 2b ISA Support for High-Level Languages
Presentation transcript:

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 region of the stack that provides the execution environment of a particular call to a function

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

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 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 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 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 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 String s = new String (“hello”); s “hello” java.lang.String String t = s; t

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

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

Packages: Putting Classes Together 19

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.

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.

Package built in Package user- define 22

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

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

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

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

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

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.*;

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 }

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

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.*;

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.

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"); }

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

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 }

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