Using final We use the notion of constant data to represent data that cannot be changed. public class Test { static final int someInt = 10; static final.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

1 Value vs. reference semantics. Recall: Value semantics value semantics: Behavior where variables are copied when assigned to each other or passed as.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Java Software Solutions
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Rounding Out Classes The objectives of this chapter are: To discuss issues surrounding passing parameters to methods What is "this"? To introduce class.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1. 2 Introduction to Methods  Type of Variables  Static variables  Static & Instance Methods  The toString  equals methods  Memory Model  Parameter.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Static Class Members Wrapper Classes Autoboxing Unboxing.
Arrays. Arrays  When a value is to be used in a program, a variable is declared to hold that value  What about storing the results of exams for a large.
Lecture 3. 2 Introduction Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 7 Objects and Memory. Structure of memory The fundamental unit of memory is called a bit, either 0 or 1. In most modern architectures, the smallest.
class Box { Box is new data type of the class. double width;
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Objects and Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
List Interface and Linked List Mrs. Furman March 25, 2010.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CSE 1201 Object Oriented Programming ArrayList 1.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Memory Management.
Java Review: Reference Types
Introduction to Data Structure
OO Programming Concepts
Classes and Objects Object Creation
Chapter 7 Objects and Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Using final We use the notion of constant data to represent data that cannot be changed. public class Test { static final int someInt = 10; static final int someInt = 10; //… //… someInt = 9; // ERROR someInt = 9; // ERROR //… //…}

Using final What happens when we want a constant object? public class Circle { private double radius; private double radius; public Circle(double r) { public Circle(double r) { radius = r; radius = r; } public void setRadius(double r) { public void setRadius(double r) { radius = r; radius = r; } public double getRadius() { public double getRadius() { return radius; return radius; }}

Using Final public class FinalTest { private static final Circle wheel = new Circle(5.0); private static final Circle wheel = new Circle(5.0); public static void main(String[] args) { public static void main(String[] args) { System.out.println(“radius is “ + wheel.getRadius()); System.out.println(“radius is “ + wheel.getRadius()); wheel.setRadius(7.4); wheel.setRadius(7.4); System.out.println(“now the radius is “ + System.out.println(“now the radius is “ + wheel.getRadius()); wheel.getRadius()); }}

Using Final The output of the code is: radius is 5.0 now the radius is 7.4 How can the wheel object change values when we specifically declared it final??? We did not change the value of the variable wheel. We changed the content of the object that wheel references.

Using final What if we try the following code: public class FinalTest { private static final Circle wheel = new Circle(5.0); private static final Circle wheel = new Circle(5.0); public static void main(String[] args) { public static void main(String[] args) { System.out.println(“radius is “ + wheel.getRadius()); System.out.println(“radius is “ + wheel.getRadius()); wheel = new Circle(7.4) ; wheel = new Circle(7.4) ; System.out.println(“now the radius is “ + System.out.println(“now the radius is “ + wheel.getRadius()); wheel.getRadius()); }}

Using Final Compiling this code results in what we expect: FinalTest.java:9: Can’t assign a value to a final variable: wheel wheel = new Circle(7.4); wheel = new Circle(7.4); ^ 1 error There is an error because we are attempting to modify the reference which was defined as final. The reference is final and thus immutable. The reference is final and thus immutable. The object itself is not affect and thus is mutable. The object itself is not affect and thus is mutable.

Arrays vs. Vectors Java provides two constructs, an array and a Vector, Java provides two constructs, an array and a Vector, which appear to be similar. which appear to be similar. In fact, the array and Vector are altogether different. In fact, the array and Vector are altogether different. It is important to understand the differences between It is important to understand the differences between the two, in order to write efficient code. the two, in order to write efficient code.

Arrays summary Arrays have fixed size - after creating an array, you cannot add more elements than its maximum size. If you do, you will get an ArrayIndexOutOfBoundsException Arrays have fixed size - after creating an array, you cannot add more elements than its maximum size. If you do, you will get an ArrayIndexOutOfBoundsException In Java, arrays are objects, so any methods contained in java.lang.Object can be invoked on them. In Java, arrays are objects, so any methods contained in java.lang.Object can be invoked on them. In order to find the length of the array, use the public variable length. In order to find the length of the array, use the public variable length. int[] ia = new int[N]; int[] ia = new int[N]; System.out.println(“ia length is “ + ia.length); System.out.println(“ia length is “ + ia.length);

Arrays summary Arrays can hold both primitive types and object Arrays can hold both primitive types and object references. references. Default values are used for each entry, based on its type. Default values are used for each entry, based on its type. Type Default value booleanfalse char‘\u0000’ short0 int0 long0 float0.0 double0.0 object reference null

Vectors summary An Vector grow its size dynamically when more An Vector grow its size dynamically when more elements are added than its current size can elements are added than its current size can accommodate. accommodate. As elements get deleted, each element with an index As elements get deleted, each element with an index greater than the index being removed is shifted greater than the index being removed is shifted downward. downward. Unlike arrays, you call a method on a Vector to Unlike arrays, you call a method on a Vector to determine its size. determine its size. Vector v = new Vector(); Vector v = new Vector(); System.out.println(“v length is “ + v.size()); System.out.println(“v length is “ + v.size());

Vectors summary The Vector’s size measures the number of elements it The Vector’s size measures the number of elements it holds. holds. Thus, the Vector’s size may vary, unlike the array’s Thus, the Vector’s size may vary, unlike the array’s size which is fixed. size which is fixed. A vector is implemented in terms of an array of A vector is implemented in terms of an array of java.lang.Object. java.lang.Object. That is, when it grows, or shrinks, the entire array That is, when it grows, or shrinks, the entire array must be reallocated and copied. must be reallocated and copied. This may cause performance problems if Vectors are This may cause performance problems if Vectors are not used properly. not used properly.

Vectors summary Finally, a Vector may contain only object references an Finally, a Vector may contain only object references an not primitive types. not primitive types. Vector v = new Vector(); Vector v = new Vector(); v.add(new Turtle()); // OK v.add(new Turtle()); // OK v.add(5); // ERROR v.add(5); // ERROR Integer i = new Integer(5); Integer i = new Integer(5); v.add(i);// OK v.add(i);// OK

Arrays vs. Vectors If you are working with a primitive type, consider using an array instead of Vector. Support for primitive types Support for objects Auto size fast ArrayYesYesNoYes VectorNoYesYesNo

Memory Management Java provides an automatic memory management with its garbage collection. For this reason, free and delete are unnecessary. This may lead some programmers to ignore memory issues. The garbage collector frees memory held by an object only if the object is no longer being referenced. Turtle one = new Turtle(); Turtle two = one; onetwo one = null; two = null; Oops, killing turtles is against the law

15 Memory Management There are many implementation for the garbage collection algorithm as there are numerous JVMs. Multiple invocations might be needed to reclaim an unreferenced object. Runtime rt = Runtime.getRuntime(); long mem = rt.freeMemory(); System.out.println(“Free memory is: “ + mem); //… System.gc(); //… mem = rt.freeMemory(); System.out.println(“Free memory is now: “ + mem);

16 Memory Management Problems can arise when objects contain instance variables that is initialized in the constructor and consumes large amounts of memory: public class Customers { private int[] cusIdArray; public Customers(String filename) { int num = // read amount from file cusIdArray = new int[num]; for (int i=0; i<num; i++) cusIdArray[i] = // value from the file }

Memory Management Suppose we want to display all the ids to the screen: public class Display { public static void main(String[] args) { Customers cust = new Customers(); // display the ids to the screen // Customers object is no longer needed. //… // the rest of the application } Assume there are 20,000 different customers !!!

Memory Management One solution is to set the local variable cust to null, after it is used. public class Display { public static void main(String[] args) { Customers cust = new Customers(); // display the ids to the screen // Customers object is no longer needed. //… cust = null; // the rest of the application }

Memory Management What if you need to keep the cust object, but have limited use for the cusIdArray, after it is displayed ? The solution above works, but has a potential negative implications. We may need to handle the case that the array is needed but no longer valid. public class Customers { // … same code as above public void resetCust() { cusIdArray = null; } public static void main(String[] args) { Customers cust = new Customers(); // display the ids to the screen // Customers object is no longer needed. //… cust.resetCust(); // the rest of the application }

Objects and Equality Java provides two different types: reference types and primitives. In addition wrapper classes are provided for each primitive type. Primitive Type Wrapper class booleanBoolean charCharacter byteByte shortShort intInteger longLong floatFloat doubleDouble

Objects and Equality References and primitives behave altogether differently and have different semantics. int i = 5; Integer j = new Integer(10); Both primitives and references are stored and manipulated on the Java operand stack. Objects are stored in memory heap. j 5 // i’s value stackheap Integer 10

Objects and Equality Using a primitive type eliminates the need to call new and create an object - this saves time and space. Mixing primitives and objects can also create unexpected results with regard to assignment. int a = 1; int b = 2; Point x = new Point(0,0); Point y = new Point(1,1); System.out.println(“a is “ + a); System.out.println(“b is “ + b); System.out.println(“x is “ + x); System.out.println(“y is “ + y);

Objects and Equality // performing assignment and setLocation a = b; a++; x = y; x.setLocation(5,5); System.out.println(“a is “ + a); System.out.println(“b is “ + b); System.out.println(“x is “ + x); System.out.println(“y is “ + y);

Objects and Equality The output for the code is: a is 1 b is 2 x is java.awt.Point[x=0,y=0] y is java.awt.Point[x=1,y=1] a is 3 b is 2 x is java.awt.Point[x=5,y=5] y is java.awt.Point[x=5,y=5] y has also changed!

Objects and Equality Point (0,0) Point (1,1) x y Point x = new Point(0,0); Point y = new Point(1,1); Point (0,0) Point (1,1) x y x = y; Point (0,0) Point (5,5) x y x.setLocation(5,5);

Differentiate between == and equals What is the difference between the == operator and the equals method? Isn’t == good enough? Public class Test { public static void main(String[] args) { int a = 10; int b = 10; System.out.println(“a==b is “ + (a==b)); Integer ia = new Integer(10); Integer ib = new Integer(10); System.out.println(“ia==ib is “ + (ia==ib)); }

Differentiate between == and equals The output for this code is: a==b is true ia==ib is false What went wrong? a and b are of type int, and as such, they are of primitive type. ia and ib are object references and reference Integer objects.

Differentiate between == and equals a and b have the same value of 10. The object references, ia and ib are really references to two different Java Integer Objects that have the value 10. The values of ia and ib are not 10 but rather unique values that represent the two objects. The == operator tests for equality. Is the thing on the left-hand side of the == the same as the thing on the right-hand side? How do you test to see whether the values referenced by ia and ib are equal? This is where you use the equals method.