Fall 2017 CISC124 10/1/2017

Similar documents
5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Fall 2017 CISC124 9/27/2017

Week 6: Review. Java is Case Sensitive

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Fall 2017 CISC124 9/16/2017

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Fall 2017 CISC/CMPE320 9/27/2017

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

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

Introduction to Programming Using Java (98-388)

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

STRINGS AND STRINGBUILDERS. Spring 2019

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Text User Interfaces. Keyboard IO plus

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

CSC Java Programming, Fall Java Data Types and Control Constructs

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

Programming II (CS300)

A variable is a name for a location in memory A variable must be declared

HST 952. Computing for Biomedical Scientists Lecture 8

Notes from the Boards Set BN19 Page

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

CS159. Nathan Sprague

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

CS 11 java track: lecture 3

Comp 249 Programming Methodology Chapter 9 Exception Handling

ITI Introduction to Computing II

ITI Introduction to Computing II

Internal Classes and Exceptions

Programming II (CS300)

Midterms Save the Dates!

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Computer Science is...

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Lecture 19 Programming Exceptions CSE11 Fall 2013

School of Informatics, University of Edinburgh

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

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

Object Oriented Programming. Week 7 Part 1 Exceptions

Introduction Unit 4: Input, output and exceptions

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

First Java Program - Output to the Screen

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Full file at

Exceptions and Design

Midterm Review 01. SP17 ICS 111 Ed Meyer

Objects and Classes -- Introduction

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

BBM 102 Introduction to Programming II Spring Exceptions

We now start exploring some key elements of the Java programming language and ways of performing I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

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

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

Object-Oriented Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

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

Using Java Classes Fall 2018 Margaret Reid-Miller

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Pace University. Fundamental Concepts of CS121 1

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

BBM 102 Introduction to Programming II Spring 2017

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Index COPYRIGHTED MATERIAL

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

tostring() Method tostring() Method -Example tostring() Method -Example StringBufferClass StringBuffer class - Constructors

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

CS 251 Intermediate Programming Methods and Classes

1.00 Lecture 30. Sending information to a Java program

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

CS11 Introduction to C++ Fall Lecture 6

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS159. Nathan Sprague

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Exception-Handling Overview

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Inheritance and Interfaces

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Errors and Exceptions

Transcription:

CISC124 Today First onq quiz this week write in lab. More details in last Wednesday s lecture. Repeated: The quiz availability times will change to match each lab as the week progresses. Useful Java classes: String class, Cont. StringTokenizer class (in java.util) Method Overloading Exceptions (if we have time) Fall 2017 CISC124 - Prof. McLeod 1 Fall 2017 CISC124 - Prof. McLeod 2 Since String s are Objects they can have methods. String methods (67 of them!) include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) indexof(searchstring) replace(oldchar, newchar) startswith(prefixstring) endswith(suffixstring) valueof(integer) String s do not have any attributes. See the API Docs for details on all the String class methods. Fall 2017 CISC124 - Prof. McLeod 3 Fall 2017 CISC124 - Prof. McLeod 4 A few examples: int i; boolean abool; String teststuff = A testing string. ; i = teststuff.length(); // i is 17 char achar; achar = teststuff.charat(2); // achar is t i = teststuff.indexof( test ); // i is 2 abool = teststuff.equals( a testing string. ); // abool is false abool = teststuff.equalsignorecase( A TESTING STRING. ); // abool is true Fall 2017 CISC124 - Prof. McLeod 5 Fall 2017 CISC124 - Prof. McLeod 6 Prof. Alan McLeod 1

Aside - More about String s Is Hello class (a String literal) an Object? Yup, Hello class!.length() would return 12. Also, String s are immutable meaning that they cannot be altered, only re-assigned. There are no methods that can alter characters inside a string while leaving the rest alone. Arrays are mutable, in contrast any element can be changed Fall 2017 CISC124 - Prof. McLeod 7 Aside - Exercises You are now ready for exercises 4, 5 and 6: Exercise 4 on File I/O the content will not be discussed in class. Exercise 5 will give you practice with the String and Character classes. Exercise 6 will give you more practice with modular program design and get you thinking about Object Oriented design. Fall 2017 CISC124 - Prof. McLeod 8 Other java.lang Classes Object is the base class for all objects in Java. We ll need to learn about object hierarchies (Inheritance) for this to make more sense. Thread is a base class used to create threads in multi-threaded program. More about this topic near the end of the course. StringTokenizer Class This useful class is in the java.util package, so you need to have an import java.util.*; or import.java.util.stringtokenizer; statement at the top of your program. This class provides an easy way of parsing strings up into pieces, called tokens. Tokens are separated by delimiters, that you can specify, or you can accept a list of default delimiters. Fall 2017 CISC124 - Prof. McLeod 9 Fall 2017 CISC124 - Prof. McLeod 10 The constructor method for this class is overloaded. So, when you create an Object of type StringTokenizer, you have three options: new StringTokenizer(String s) new StringTokenizer(String s, String delim) new StringTokenizer(String s, String delim, boolean returntokens) s is the String you want to tokenize. delim is a list of delimiters, by default it is: \t\n\r or space, tab, line feed, carriage return. You can specify your own list of delimiters if you provide a different String for the second parameter. Fall 2017 CISC124 - Prof. McLeod 11 Fall 2017 CISC124 - Prof. McLeod 12 Prof. Alan McLeod 2

If you supply a true for the final parameter, then delimiters will also be provided as tokens. The default is false - delimiters are not provided as tokens. Here is some example code: String astring = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); System.out.println("The String has " + st.counttokens() + " tokens."); System.out.println("\nThe tokens are:"); while (st.hasmoretokens()) { System.out.println(st.nextToken()); } // end while Fall 2017 CISC124 - Prof. McLeod 13 Fall 2017 CISC124 - Prof. McLeod 14 Screen output: The String has 6 tokens. The tokens are: This is a String - Wow! Note that the StringTokenizer object is emptied out as tokens are removed from it. You will need to re-create the object in order to tokenize it again. Fall 2017 CISC124 - Prof. McLeod 15 Fall 2017 CISC124 - Prof. McLeod 16 Scanner Class Tokenizer The Scanner class has a tokenizer built into it. Scanner uses a regular expression or regex instead of the (easier to understand, but less powerful!) delimiter list. The default regex is: "\p{javawhitespace}+" which means any number of whitespace characters. A whitespace character is a space, a tab, a linefeed, formfeed or a carriage return. " \t\n\f\r" in other words. Tokenizing Demo See SystemPropertiesDemo.java Includes some old-fashioned string parsing code that uses String class methods only. Fall 2017 CISC124 - Prof. McLeod 17 Fall 2017 CISC124 - Prof. McLeod 18 Prof. Alan McLeod 3

Method Overloading A method can have the same name in many different classes (println(), for example). Overloading is when a method name is used more than once in method declarations within the same class. (also like println() ) The rule is that no two methods with the same name within a class can have the same number and/or types of parameters in the method declarations. (The NOT rule.) Why bother? Convenience! Java does not have default arguments. Allows the user to call a method without requiring him to supply values for all the parameters. One method name can be used with many different types and combinations of parameters. Also, allows the programmer to keep an old method definition in the class for backwards compatibility. Fall 2017 CISC124 - Prof. McLeod 19 Fall 2017 CISC124 - Prof. McLeod 20 How does it work? Java looks through all methods until the parameter types match with the list of arguments supplied by the user. If none match, Java tries to cast types in order to get a match. (Only widening casting like int to double, however.) Final notes on overloading: You can have as many overloaded method definitions as you want, as long as they are differentiated by the type and/or number of the parameters listed in the definition. Do not change the return type that is tacky! See the getint() and getdouble() overloaded methods in the Exercise 1 IOHelper class for example. Fall 2017 CISC124 - Prof. McLeod 21 Fall 2017 CISC124 - Prof. McLeod 22 Exceptions How can a method indicate that it is unable to return what it is supposed to return? How can a method deliver details about the error condition? How else can you prevent the instantiation of an Object? The limitation of only returning a single thing means that you either designate error values for the thing or you have some other way to return the indication of an error. Fall 2017 CISC124 - Prof. McLeod 23 Exceptions - Cont. The designers of Java followed conventions used by many other OOP languages - they allowed for another way to get something out of a method. However, an exception is thrown, not returned. Exceptions are Objects (big surprise!). When an error condition is encountered, a method can throw an instance of a pre-defined exception Object. A method can throw several exceptions, one for each possible kind of error condition. Fall 2017 CISC124 - Prof. McLeod 24 Prof. Alan McLeod 4

Exceptions - Cont., Propagation If a method throws an exception, then that method is immediately halted and there is no need for any return value, even if the method is non-void. The invoking method then receives the exception if it does not catch it, then it goes to the next invoking method all the way to main, if necessary. Called cascading. Finally, if main does not catch the exception, your program crashes and a message is sent to the console window. Fall 2017 CISC124 - Prof. McLeod 25 Exceptions - Cont., Message Handler How does an Exception Object contain information about the error condition? The type of the Object: IOException NumberFormatException FileNotFoundException ArrayIndexOutOfBoundsException So, the method should throw a relevant exception object. Turns out that exceptions can also carry a String message. Fall 2017 CISC124 - Prof. McLeod 26 An exception is just a: Exceptions - Cont., Catching This is done with a try/catch block (see the next slide for the syntax). The exception itself cannot do anything about the problem. But it can act to stop your program! Fall 2017 CISC124 - Prof. McLeod 27 The compiler will force you to use try/catch blocks when you invoke methods that throw exceptions. (Eclipse can help build a try/catch: Select the code to be surrounded. Right click and choose Surround with, then Try/catch block. The wizard will automatically choose all the possible exceptions.) Fall 2017 CISC124 - Prof. McLeod 28 Syntax of a try-catch block : try { that might // generate an exception } catch (exception_type identifer) { }[ catch (exception_type identifer) { }][ finally { }] Fall 2017 CISC124 - Prof. McLeod 29 You must have at least one catch block after the try block (otherwise the try block would be useless!) You can have many catch blocks, one for each exception you are trying to catch. The code in the finally block is always executed, whether an exception is thrown, caught, or not. Fall 2017 CISC124 - Prof. McLeod 30 Prof. Alan McLeod 5