Stack vs. Heap. Introduction to Programming. How the Stack Works. Primitive vs. Reference Types. Stack



Similar documents
Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Variables, Constants, and Data Types

J a v a Quiz (Unit 3, Test 0 Practice)

Moving from CS 61A Scheme to CS 61B Java

CS 111 Classes I 1. Software Organization View to this point:

Basic Object-Oriented Programming in Java

Introduction to Java. CS 3: Computer Programming in Java

Java Interview Questions and Answers

Introduction to Java

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

Computer Programming I

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

C++ INTERVIEW QUESTIONS

CS106A, Stanford Handout #38. Strings and Chars

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

AP Computer Science Java Subset

Chapter 2: Elements of Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Visual Basic Programming. An Introduction

Example of a Java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

LAB4 Making Classes and Objects

CS 106 Introduction to Computer Science I

Java Basics: Data Types, Variables, and Loops

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Crash Course in Java

CmpSci 187: Programming with Data Structures Spring 2015

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

CMSC 202H. ArrayList, Multidimensional Arrays

CSC 551: Web Programming. Fall 2001

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

public static void main(string[] args) { System.out.println("hello, world"); } }

Lecture 5: Java Fundamentals III

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Monitors, Java, Threads and Processes

Pemrograman Dasar. Basic Elements Of Java

Chapter 7D The Java Virtual Machine

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Informatica e Sistemi in Tempo Reale

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter 2 Introduction to Java programming

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Sample CSE8A midterm Multiple Choice (circle one)

The C Programming Language course syllabus associate level

C++ Overloading, Constructors, Assignment operator

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Answers to Review Questions Chapter 7

Software Engineering Techniques

Explain the relationship between a class and an object. Which is general and which is specific?

Java CPD (I) Frans Coenen Department of Computer Science

Building Java Programs

Class 16: Function Parameters and Polymorphism

CS170 Lab 11 Abstract Data Types & Objects

WRITING DATA TO A BINARY FILE

Exercise 4 Learning Python language fundamentals

No no-argument constructor. No default constructor found

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

Beyond the Mouse A Short Course on Programming

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

The Java Virtual Machine (JVM) Pat Morin COMP 3002

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Chapter 5. Recursion. Data Structures and Algorithms in Java

Iteration CHAPTER 6. Topic Summary

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Basics of I/O Streams and File I/O

Basic Use of the TI-84 Plus

Web Programming Step by Step

Chapter 1 Java Program Design and Development

Building a Multi-Threaded Web Server

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Creating Database Tables in Microsoft SQL Server

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Part I. Multiple Choice Questions (2 points each):

Passing 1D arrays to functions.

LINKED DATA STRUCTURES

Stack Allocation. Run-Time Data Structures. Static Structures

Unit 6. Loop statements

Introduction to Data Structures

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Transcription:

Primitive vs. Reference Types Introduction to Programming with Java, for Beginners Primitive vs. References Type Stack vs. Heap Null Pointer Exception Keyword this Strings Has a Relationship We ve seen Java s 4 primitive types: int, double, boolean, char Types other than the primitive types are known as reference types Used for objects Examples of reference variables: Student s1; Counter c1; String name; Note: String is an object not primitive type 2 Stack vs. Heap Stack is section of computer s memory used to store temporary information E.g. Variable created inside a method Information ceases to exist after method finishes execution Objects (i.e. object s data) are stored in section of memory called heap Information exists as long as the program is not finished In Dr Java s interaction pane storage information exists as long as RESET button is not clicked 3 How the Stack Works DrJava Interaction (same applies for methods) > int x = 0; > x = ; double min = 0.; boolean done = false; Stack Note: Variables are added in the order they are declared 4 1

Reference Type The term reference is used because it refers to a memory location where the object lives The variable of reference type is used to access the object The value of variable of reference type is either null or a heap address null means currently not pointing at any location Null Pointer Exception null is a legal value for any kind of object i.e. Person p, Counter c; Player mario null can be assigned, tested, and printed But if you try to use a field or method of null, you get a nullpointerexception i.e. you try to access some object that has not been created p.getname() mario.getstrength() 6 Value of a Reference Variable Example: > Counter c1; null = new Counter(); Counter@e0ad6 e0ad6 is location in memory where object that c1 is pointing resides e0ad6 hexadecimal (base 16) number This location will different on your computer We don t have to (and can t) deal with these hex numbers directly Convenience of using variables How the Heap Works DrJava Interactions > int x = 99; > Counter c1; null = new Counter(); Counter@2f996f.incrementCount(); > Counter c2 = new Counter(); > c2 Counter@4a0ac Stack and Heap 7 8 2

Aliases Two or more references can point to the same object These references are then known as aliases Example (In Dr Java Interactions Pane) > Student s1= new Student( Lisa", ); > s1 Student@83d8be > Student s2 = s1; > s2 Student@83d8be > s1.getage() > s2.getage() Scope Issues with variables public class Dot{ private int x; private int y; public Dot(int x, int y){ x = x; // problem!! y = y; Solution Local variable x & y shadows the instance variable x & y public class Dot{ private int x; private int y; public Dot(int x, int y){ this.x = x; // fixed!! this.y = y; 9 10 Keyword this this is a reference (a variable) to the current object The object whose method or constructor is being called The value of this is an object s heap address Can be passed as argument or input to a method Can be returned as value Cannot be modified (i.e. it is final) Used to Differentiate objects & avoid scope issued with instance variable & local variable names String A sequence of characters A String is a built-in Java object type Java provides this type because it s used so frequently Examples of fstring creation: > String s1 = new String("hello"); > String s2 = "hello"; // commonly used shortcut > s2 + " you!" "hello you!" > s2 = "The result is " + 100; > System.out.println(s2); "The result is 100" 11 12 3

String (contd..) Comparing Strings DrJava Interactions > String c1 = new String( Hill ); > String c1 = new String ("Hill ); "Hill Stack and Heap Note: We do not get heap address of String reference Later, it will be clear why this case.. 13 If the == operator is used Java compares the addresses where the String objects are stored, not the letters in the String For example: >Stringa="hi"; > String b = "hi"; > a == b >false Use the String class' equals method to compare two Strings for equality > a.equals(b) true > b.equalsignorecase( HI ) true Just like the Math class, String class is part of Java Language & hence directly used 14 Has a Relationship An object of type A has an instance variable which is an object whose type is B. (A has a B.) E.g: A Freshman object whose room is of reference type DormRoom DormRoom Code > room.getlocation() The UML diagrams below show instance variables and methods of Freshman and DormRoom object: UML(Universal Modeling Lanaguage) industry standard used to describe classes in OOP 1 public class DormRoom{ private int num; private String bldgname; public DormRoom(int n, String b){ num = n; bldgname = b; public String getlocation(){ return num + " " + bldgname; 16 4

A DormRoom on the Heap Freshman Code > Freshman f = new Freshman("jo", room); > f.getname() "jo" g > room.getlocation() 17 public class Freshman{ private String name; private DormRoom room; public Freshman(String n, DormRoom r){ name = n; room = r; public String getname(){ return name; public DormRoom getroom(){ return room; 18 A Freshman on the Heap More methods to Freshman > Freshman f = new Freshman("jo", room); > f.getname() "jo" public class Freshman{ public void changeroom(dormroom r){ room = r; public String address(){ return room.getlocation(); public boolean hasaroom(){ if(room!= null) return true; else return false; 19 20

More Interactions > Freshman f = new Freshman("jo", room); > f.getname() "jo" "208 Hill > DormRoom r = new DormRoom(176, "McNair"); > f.changeroom(r); "176 McNair" > f.address() "176 McNair > f.hasaroom() true > DormRoom rr; //rr is null > f.changeroom(rr); > f.hasaroom() false // Error Why? 21 6