Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

CSCI 160 Midterm Review Rasanjalee DM.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Utilities (Part 3) Implementing static features 1.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Lists Chapter 4. 2 Chapter Contents Specifications for the ADT List Redefining the Specifications Using the ADT List Using a List Is Like Using a Vending.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Chapter 3 Introduction to Collections – Stacks Modified
Effective Java: Generics Last Updated: Spring 2009.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Utilities (Part 2) Implementing static features 1.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
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.
Effective Java, Chapter 7: Methods Items Last modified Fall 2012 Paul Ammann.
Session 7 Methods Strings Constructors this Inheritance.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Lists Chapter 4. 2 Chapter Contents Specifications for the ADT List Redefining the Specifications Using the ADT List Using a List Is Like Using a Vending.
1  lecture slides online
The Math Class Methods Utilizing the Important Math Operations of Java!
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Methods.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CSC 243 – Java Programming, Fall, 2008 Tuesday, September 30, end of week 5, Interfaces, Derived Classes, and Abstract Classes.
Chapter VII: Arrays.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
slides created by Ethan Apter
Outline Creating Objects The String Class The Random and Math Classes
Implementing static features
slides created by Ethan Apter and Marty Stepp
ArrayLists Readings: 10.1 (pg. 559 – 571).
Presentation transcript:

Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY); } [Java Puzzlers by Joshua Block and Neal Gaffer]

2  prints 5  the problem occurs because the expression 24 * 60 * 60 * 1000 * 1000 evaluates to a number bigger than int can hold  86,400,000,000 > 2,147,483,647 (Integer.MAX_VALUE)  called overflow  notice that the numbers in the expression are of type int  Java will evaluate the expression using int even though the constant MICROS_PER_DAY is of type long  solution: make sure that the first value matches the destination type 24L * 60 * 60 * 1000 * 1000

Goals for Today 3  learn about method overloading  how-to  overload resolution  ambiguous overloads  confusing overloads  compare preconditions versus validation  look at the UML class diagram for our utility

Overloading kilometresToMiles() 4  suppose we want to provide a method to convert many values stored in an array from kilometres to miles  we can provide another method called kilometresToMiles() as long as the signature is different  providing multiple methods with the same name but different signatures is called method overloading  the intent of overloading is to provide flexibility in the types of arguments that a client can use

Version 4 (overload a method) 5 public class DistanceUtility { // attributes and constructors; see Version 2 or 2a... // methods public static double kilometresToMiles(double km) { // see version 3} public static double[] kilometresToMiles(double[] km) { double[] miles = new double[km.length]; for(int i = 0; i < km.length; i++) { miles[i] = kilometresToMiles(km[i]); // good! } return miles; } }

What to do About Invalid Arguments 6  as the author of a class, you have control over how your method is implemented  what you cannot control is the value of the arguments that clients pass in  a well written method will 1. specify any requirements the client must meet with the arguments it supplies  preconditions 2. validate the state of any arguments without preconditions and deal gracefully with invalid arguments  validation [notes 1.4 and 1.5]

Preconditions 7  if a method specifies a precondition on one of its parameters, then it is the client's responsibility to make sure that the argument it supplies satisfies the precondition  if a precondition is not satisfied then the method can do anything (such as throw an exception, return an incorrect value, behave unpredictably,...)  garbage in, garbage out  for our method possible preconditions are:  km must not be null  km.length > 0  note that the second precondition is more restrictive than the first

8 /** * Converts distances in kilometres to miles for arrays. * If an element of the array argument is negative the * corresponding element of the returned array is also * negative. * km The distances to convert. km.length > 0 Distances in miles in an array with * length == km.length. */ public static double[] kilometresToMiles(double[] km)

Validation 9  alternatively, the class implementer can relax preconditions on the arguments and validate the arguments for correctness  the implementer assumes the responsibility for dealing with invalid arguments  must check, or validate, the arguments to confirm that they are valid  invalid arguments must be accommodated in a way that allows the method to satisfy its postconditions  in our example, a possible return value for a null array is a zero-length array [notes 1.4 and 1.5]

10 /** * Converts distances in kilometres to miles for arrays. * If an element of the array argument is negative the * corresponding element of the returned array is also * negative. * km The distances to convert. Distances in miles in an array with * length == km.length. If the * array argument is null then a * zero-length array is returned. */ [notes 1.4 and 1.5]

11 public static double[] kilometresToMiles(double[] km) { double[] miles = null; if (km == null) { miles = new double[0]; } else { miles = new double[km.length]; for(int i = 0; i < km.length; i++) { miles[i] = kilometresToMiles(km[i]); } } return miles; }

Method Overloading 12  simple rule  a class can define multiple methods with the same name as long as the signatures are unique // DistanceUtility examples kilometresToMiles(double) kilometresToMiles(double[]) // String examples String() String(char[] value) String(char[] value, int offset, int count) [notes 1.3.4], [AJ 4.3]

Overloading 1 13  everything other than the signature is ignored in determining a legal overload // illegal; parameter names not part of signature // add this to DistanceUtility: legal or illegal? public static double kilometresToMiles(double kilos)

Overloading 2 14 // illegal; access modifier not part of signature // legal or illegal? private static double kilometresToMiles(double km)

Overloading 3 15 // illegal; static modifier not part of signature // legal or illegal? public double kilometresToMiles(double km)

Overloading 4 16 // illegal; return type not part of signature // legal or illegal? public static float kilometresToMiles(double km)

Overloading 5 17 // legal; parameter type is part of signature // legal or illegal? public static float kilometresToMiles(float km) { // this works return (float)(km / KILOMETRES_PER_MILE); }

Overloading 5a 18 // implemented in terms of kilometresToMiles(double) // public static float kilometresToMiles(float km) { // but this might be better return (float)kilometresToMiles((double)km); }

Selection of Overloaded Methods 19  loosely speaking, the compiler will select the method that most closely matches the number and types of the arguments  “The rules that determine which overloading is selected are extremely complex. They take up thirty-three pages in the language specification [JLS, ], and few programmers understand all of their subtleties.”  Effective Java, Second Edition, p 195.

Selection Examples 20 // from java.lang.Math Math.abs(-5); Math.abs(-5f); Math.abs(-5.0); Math.max(1, 2); Math.max(1.0, 2.0); Math.max(1, 2.0); // Math.abs(int a) // Math.abs(float a) // Math.abs(double a) // Math.max(int a, int b) // Math.max(double a, double b) no exact match for Math.max(int, double) but the compiler can convert int to double to match Math.max(double, double)

Ambiguous Overloads 21 public class Ambiguous { public static void f(int a, double b) { System.out.println("f int double"); } public static void f(double a, int b) { System.out.println("f double int"); } public static void main(String[] args) { f( 1, 2 );// will not compile } } [AJ 4.3, ]

Confusing Overload 22 import java.util.*; public class SetList { public static void main(String[] args) { Set set = new TreeSet (); List list = new ArrayList (); // fill set and list with -3, -2, -1, 0, 1, 2, 3 for(int i = -3; i <= 3; i++) { set.add(i); list.add(i); } System.out.println("before " + set + " " + list); [Effective Java, Second Edition, p 194]

Confusing Overload 23 // remove 0, 1, and 2? for(int i = 0; i < 3; i++) { set.remove(i); list.remove(i); } System.out.println("after " + set + " " + list); } } [Effective Java, Second Edition, p 194]

Confusing Overload Explained 1 24  before [-3, -2, -1, 0, 1, 2, 3] [-3, -2, -1, 0, 1, 2, 3]  after [-3, -2, -1] [-2, 0, 2]  set and list are collections of Integer s  calls to add autobox their int argument set.add(i); // autobox int i to get Integer list.add(i); // autobox int i to get Integer  calls to TreeSet remove also autobox their int argument set.remove(i); // autobox int i to get Integer [auto-boxing and unboxing, AJ p 265–267]

Confusing Overload Explained 2 25  however, ArrayList has an overloaded remove method remove(int index) Removes the element at the specified position in this list.  therefore, list.remove(i) matches the int version of remove() instead of the Integer version of remove() list.remove(0); // [-3, -2, -1, 0, 1, 2] list.remove(1); // [-2, -1, 0, 1, 2] list.remove(2); // [-2, 0, 1, 2]

UML Class Diagram for Utilities 26  class name preceded by >  + means public (– means private)  attributes: type  methods:parameters and return type > DistanceUtility + KILOMETRES_PER_MILE : double + kilometresToMiles(double) : double + kilometresToMiles(double[]) : double[] + milesToKilometres(double) : double

Exercise 27  Add a method to DistanceUtility that takes a Collection of distances in kilometres as an argument and returns an array of distances converted to miles  hint: consider overloading kilometresToMiles()  hint: [AJ 16.1, especially p 884]  see [notes 1.6.3] for a similar exercise