this keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.

Similar documents
COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

CSC Java Programming, Fall Java Data Types and Control Constructs

For more details on SUN Certifications, visit

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Selected Java Topics

Exceptions. What exceptional things might our programs run in to?

Chapter 4 Defining Classes I

School of Informatics, University of Edinburgh

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

COMP1008 Exceptions. Runtime Error

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Full file at Chapter 2 - Inheritance and Exception Handling

Java Fundamentals (II)

Selected Questions from by Nageshwara Rao

Programming II (CS300)

More on Exception Handling

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.)

Fall 2017 CISC124 10/1/2017

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

ITI Introduction to Computing II

ITI Introduction to Computing II

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Programming II (CS300)

Programming - 2. Common Errors

Internal Classes and Exceptions

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 8 Programmer. Version: Demo

1 Shyam sir JAVA Notes

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

PIC 20A The Basics of Java

C16b: Exception Handling

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

More on Exception Handling

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exceptions Handeling

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

BBM 102 Introduction to Programming II Spring Exceptions

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Brief Summary of Java

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

Java for Interfaces and Networks (DT3010, HT10)

ECE 122. Engineering Problem Solving with Java

Class, Variable, Constructor, Object, Method Questions

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exceptions and Design

Exceptions Handling Errors using Exceptions

Fundamentals of Object Oriented Programming

CH. 2 OBJECT-ORIENTED PROGRAMMING

Introduction to Programming Using Java (98-388)

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Review: Array Initializer Lists

/* Solve f(x) = x*x*x-5 = 0 f'(x) = 3x^2 */

Exceptions. Examples of code which shows the syntax and all that

Java Errors and Exceptions. Because Murphy s Law never fails

Types, Values and Variables (Chapter 4, JLS)

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

CS 3 Introduction to Software Engineering. 3: Exceptions

Pace University. Fundamental Concepts of CS121 1

ECE 122. Engineering Problem Solving with Java

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Java: introduction to object-oriented features

CS244 Advanced Programming Applications

EXCEPTIONS. Java Programming

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Computer Science II (20082) Week 1: Review and Inheritance

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Object Oriented Software Design

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Object Oriented Software Design

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

AP Computer Science A

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

Exceptions: When something goes wrong. Image from Wikipedia

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Java Programming Tutorial 1

WES-CS GROUP MEETING #9

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

CS 231 Data Structures and Algorithms, Fall 2016

Introduction Unit 4: Input, output and exceptions

The Proxy Pattern. Design Patterns In Java Bob Tarr

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Title. Java Just in Time. John Latham. February 8, February 8, 2018 Java Just in Time - John Latham Page 1(0/0)

CS 251 Intermediate Programming Java Basics

Index COPYRIGHTED MATERIAL

HST 952. Computing for Biomedical Scientists Lecture 8

Transcription:

topics: introduction to java, part 4 this references exception handling comparing objects vectors utility classes cisc3120 design and implementation of software applications I spring 2015 lecture # I.4 this keyword (1). this is a reference to the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. public class Coin { public Coin() { value = 0; public Coin(int value) { this.value = value; public void setvalue(int value) { this.value = value; this.value += 10; private int value; cisc3120-spring15-ozgelen-leci.4 1 cisc3120-spring15-ozgelen-leci.4 2 public static void main(string[] args) { Coin quarter = new Coin(); quarter.setvalue(15); In the above example, this refers to the quarter object and local variable value in setvalue holds 15. this with constructor (2). this keyword can be used to call another constructor in the same class. It is called an explicit constructor invocation public class Coin { // default constructor public Coin() { this(25); // overload constructor public Coin(int v) { value = v; flip(); cisc3120-spring15-ozgelen-leci.4 3 cisc3120-spring15-ozgelen-leci.4 4

references (1). references (2). when we declare a variable whose data type is a class, we are declaring an object reference variable that variable refers to the actual object stored in computer s memory an object reference variable and an object are two separate things declaration of an object reference variable: Coin x; creation of an object (also called construction, instantiation ): x = new Coin(); when you declare a variable as a primitive data type, the computer sets aside a fixed amount of memory, based on the size of the data type when you declare a variable of any other data type (i.e., a class), you are actually declaring a reference a reference is typically the size of an int or a long it stores information for the object, which the JVM uses to locate the address in the computer s memory, where the actual data will be kept you can think of it like a telephone book the phone book has a bunch of addresses in it but not the actual buildings just the locations of buildings cisc3120-spring15-ozgelen-leci.4 5 cisc3120-spring15-ozgelen-leci.4 6 references (3). references (4). here s how it works inside the computer given the following declarations: int i = 45; String s = "hello"; the memory looks something like this: i s 45 hello i is the label for the location in memory where the actual data is stored in this case the int 45 s is the label for the location in memory where the address is stored; the address is the location in memory where the actual data for s is stored in C, this is called a pointer we say that s points to or references the location in memory where the actual data for s is stored let s go back to the Coin example comment out the tostring() method and re-run the example here s the output now: i[0]=coin@73d6a5 i[1]=coin@111f71 i[2]=coin@273d3c i[3]=coin@256a7c i[4]=coin@720eeb i[5]=coin@3179c3 i[6]=coin@310d42 i[7]=coin@5d87b2 i[8]=coin@77d134 i[9]=coin@47e553 these are the references of the array elements we can see these reference values because we took out the tostring() method calling System.out.println(pocket[i]) automatically coerces its argument (pocket[i]) to a String so it can print it; if there is no explicit tostring() method in the class, then a reference is the closest String representation cisc3120-spring15-ozgelen-leci.4 7 cisc3120-spring15-ozgelen-leci.4 8

references (5). references (6). when an object reference variable has been declared but the object does not refer to an object, then the object reference variable is called a null reference for example: Coin[] x = new Coin[5]; x[0].flip(); will generate an error called a NullPointerException because the object which x[0] refers to has not been instantiated you can use a constant called null to check if an object reference variable is null for example: an alias is an object reference variable that refers to an object that was previously constructed and is already referred to by another object reference variable for example: Coin x = new Coin(); Coin y; y = x; y.flip(); y is called an alias of x (and vice versa) because they both refer to the same object in the computer s memory Coin[] x = new Coin[5]; if(x[0]!= null) { x[0].flip(); cisc3120-spring15-ozgelen-leci.4 9 cisc3120-spring15-ozgelen-leci.4 10 references (7). references (8). garbage collection is necessary when all references to an object are gone because when there are no object reference variables, then there is no way to know where in memory an object is located Java handles this for you automatically the JVM periodically invokes automatic garbage collection while it is running all the memory that is allocated to an application but is not being used is restored so that it can be re-allocated to the application later if you want to perform some garbage collection on a class that you create yourself, then you would write a method called finalize() and whenever the automatic garbage collection was invoked and cleaned up an object of your class type, then your finalize() method would be called in Java all method calls are call-by-value. so be careful about what changes! here s an example using two classes: Num ParameterTester cisc3120-spring15-ozgelen-leci.4 11 cisc3120-spring15-ozgelen-leci.4 12

references (9). references (10). public class Num { private int value; public Num(int update) { value = update; public void setvalue(int update) { value = update; public String tostring() { return value+""; public class ParameterTester { public static void main( String[] args ) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); System.out.println("before call: \ta1=" + a1 + ", \ta2=" + a2 + ", \ta3=" + a3); changevalues(a1, a2, a3); System.out.println("after call: \ta1=" + a1 + ", \ta2=" + a2 + ", \ta3=" + a3); public static void changevalues(int f1, Num n1, Num n2) { System.out.println("start call: \tf1=" + f1 + ", \tn1=" + n1 + ", \tn2=" + n2); f1 = 999; n1.setvalue(888); n2 = new Num(777); System.out.println("end call: \tf1=" + f1 + ", \tn1=" + n1 + ", \tn2=" + n2); cisc3120-spring15-ozgelen-leci.4 13 cisc3120-spring15-ozgelen-leci.4 14 references (11). references (12). sample output: before call: a1=111 a2=222 a3=333 start call: f1=111 f2=222 f3=333 end call: f1=999 f2=888 f3=777 after call: a1=111 a2=888 a3=333 when an object reference variable is declared final, its reference cannot be changed. however, the object itself can be modified: // binds the reference quarter to the object final Coin quarter = new Coin(25); // error! cannot assign a value to final var quarter = new Coin(5); // OK! quarter.setvalue(5); // prints out the value of the coin as 5 System.out.println(quarter); final in Java is not the same as const in C/C++ cisc3120-spring15-ozgelen-leci.4 15 cisc3120-spring15-ozgelen-leci.4 16

exception handling (1). exception handling (2). exceptions are exceptional situations which would cause a serious error in your program such as bad input data, file not found etc. try clause contains code which may generate an exception. catch clause contains code to execute in case the error happens; i.e., where to go if the exception gets caught: try { // (1) statement that may cause an exception // (2) other statements catch(exception e) { // (3) do something with the exception if the statement at (1) above throws an exception the code will jump to catch statement and handle the exception as stated in (3) if no exception is generated at (1), statments at (2) will be executed an exception is thrown by creating an exception object and placing keyword throw before the object: throw new NumberFormatException(); all exceptions in Java derives from Exception class and generally divided into two categories: RuntimeException which happens due to programming errors (e.g. ArrayIndexOutOfBoundsException, NullPointerException) IOException which refers to situations referring to bad input to an otherwise good program. In general, you should handle IOExceptions and fix the bugs that causes RuntimeException cisc3120-spring15-ozgelen-leci.4 17 cisc3120-spring15-ozgelen-leci.4 18 exception handling (3). exception handling (4). if a method throws an exceptions its signature contains the throws keyword followed by the type of exception thrown. Integer.parseInt method signature in API docs: public static int parseint(string s) throws NumberFormatException try-catch basic form example: try { int i = Integer.parseInt("a"); catch(numberformatexception e) { System.out.println("there was an error: " + e.getmessage()); cisc3120-spring15-ozgelen-leci.4 19 you can have multiple catch blocks for different exception types: Coin c = null; try { int i = Integer.parseInt("a"); c.flip(); catch(numberformatexception nfe) { System.out.println("there was an error: " + nfe.getmessage()); nfe.printstacktrace(); catch(nullpointerexception npe) { System.out.println("You should probably initialize the Coin" + " object rather than catching this exception!"); finally { System.out.println("Done!"); cisc3120-spring15-ozgelen-leci.4 20

comparing objects (1). comparing objects (2). comparing two Java objects is tricky you have to be careful of what you are comparing: is it the value of some member(s) of the class? or is it the reference? (like a pointer in C/C++) using == compares the references (if they refer to the same object) which is not the same as comparing the values of member(s) of the class many classes have a method called compareto() to compare the value of member(s) of the class here s an example from the Coin class: comparing the value of the face member of two coins: Coin coin0 = new Coin(10); Coin coin1 = new Coin(10); if(coin0.getvalue() == coin1.getvalue()) { System.out.println("coins 0 and 1 have the same value"); versus comparing the references: if(coin0 == coin1) { System.out.println("coins 0 and 1 are the same"); cisc3120-spring15-ozgelen-leci.4 21 cisc3120-spring15-ozgelen-leci.4 22 comparing objects (3). comparing objects (4). in order to compare the value of two Strings, we need to use the method public int compareto(string str) from the java.lang.string class this method does a lexical comparison of its String argument with the current object (i.e., its instantiated value) it returns an int as follows: if the current object... then the method returns is the same text as str 0 comes lexically before str an int < 0 (e.g., -1) comes lexically after str an int > 0 (e.g., +1) using == to compare two Strings compares the references, NOT the values of the text they store this is the same for comparing any two objects in Java most classes define a compareto() method, just as most classes define a tostring() method for example: public class CompareString { public static void main(string[] args) { String s1 = new String("hello"); String s2 = new String("hello"); System.out.println("s1=[" + s1 + "]"); System.out.println("s2=[" + s2 + "]"); System.out.println("(s1 == s2) = " + (s1 == s2)); System.out.println("s1.compareTo(s2)=" + s1.compareto(s2)); System.out.println("s2.compareTo(s1)=" + s2.compareto(s1)); sample output: s1=[hello] s2=[hello] (s1 == s2) = false s1.compareto(s2)=0 s2.compareto(s1)=0 cisc3120-spring15-ozgelen-leci.4 23 cisc3120-spring15-ozgelen-leci.4 24

comparing objects (5). vectors (1). so we could add to our Coin class: public int compareto(coin coin) { if(value == coin.getvalue()) { return 0; else if(value < coin.getvalue()) { return -1; else { return 1; Java has a nice class which handles arrays dynamically: java.util.vector the elements of a Vector can be any type of Java Object note that when you fetch an element from a vector, you have to cast it from a generic object to the specific class type the object should be (see example below) some methods: constructor: Vector(); public void addelement(object obj); public void insertelementat(object obj, int index); public void removeelementat(int index); public void removeallelements(); public void setelementat(object obj, int index); public Object elementat(int index); public int size(); cisc3120-spring15-ozgelen-leci.4 25 cisc3120-spring15-ozgelen-leci.4 26 vectors example. vectors things to notice. import java.util.*; import java.io.*; public class Ex4c { public static void main(string[] args) { Vector pocket; int npocket = Integer.parseInt(args[0]); pocket = new Vector(npocket); for(int i = 0; i < npocket; i++) { pocket.addelement(new Coin()); notice that we instantiate twice... notice that we instantiate in the call to pocket.addelement(): pocket.addelement(new Coin()); notice that we cast the return from pocket.elementat(): Coin tmp = (Coin)pocket.elementAt(i); for(int i = 0; i < npocket; i++) { Coin tmp = (Coin)pocket.elementAt(i); System.out.print(tmp + " "); System.out.println(); cisc3120-spring15-ozgelen-leci.4 27 cisc3120-spring15-ozgelen-leci.4 28

utility classes: java.util.stringtokenizer. utility classes: java.text.decimalformat. used to break up a string into tokens, i.e. components each token is separated by a delimiter default delimiter is whitespace but you can set another value for delimiter primary method used: public String nexttoken(); example: line = infile.readline(); tokenizer = new StringTokenizer(line); name = tokenizer.nexttoken(); try { units = Integer.parseInt(tokenizer.nextToken()); price = Float.parseFloat(tokenizer.nextToken()); catch(numberformatexception nfx) { System.out.println("error in input; line ignored: " + line); used to format decimal numbers construct an object that handles a format use that format to output decimal numbers formatting patterns include: 0 used to indicate that a digit should be printed, or 0 if there is no digit in the number (i.e., leading and trailing zeros) # used to indicate that if there is a digit in the number, then it should be printed; indicates rounding if used to the right of the decimal point example: DecimalFormat fmt = new DecimalFormat("#.00"); double price; System.out.println("price = $" + fmt.format(price)); cisc3120-spring15-ozgelen-leci.4 29 cisc3120-spring15-ozgelen-leci.4 30