Visibility, Static, and Exception Handling. June 19, 2017

Size: px
Start display at page:

Download "Visibility, Static, and Exception Handling. June 19, 2017"

Transcription

1 Visibility, Static, and Exception Handling June 19, 2017

2 Reading Quiz

3 What is Printed? System.out.print("A"); try { System.out.print("B"); // SomeExceptionType is thrown } except (SomeExceptionType e1) { System.out.print("C"); } except (OtherExceptionType e2) { System.out.print("D"); A. "ABCDEF" B. "ABF" C. "ABCF" D. "ABEF" E. "ABCEF" } finally { System.out.print("E"); } System.out.print("F");

4 What is the Purpose of Exceptions? A. To indicate a performance issue B. To indicate an uncommon error has occurred, that the programmer should handle C. To provide additional information to the compiler, for optimization D. To provide the programmer an alternate control flow option

5 What is the Result? public class A { private String amethod() { return "Private"; } } A mya = new A(); System.out.print(myA.aMethod()); A. Won't compile B. MethodNotFoundException throw C. "Private" printed D. null printed

6 What does "Static" do? A. To indicate a value won't change during the program's execution B. To indicate a variable will change frequently during the program's execution C. To indicate that a method or variable is connected to the class, and not instances of the class D. To indicate that a method or variable is connected to the instance, and not the class itself

7 What is Printed? public class Parent { public String amethod() { return "Parent"; } } public class Child extends Parent { public String amethod() { return "Child"; } } A. "Parent" B. "Child" C. "ChildParent" D. "ParentChild" Child achild = new Child(); String result = achild.amethod(); System.out.print(result);

8 Done!

9 Housekeeping Debugging SSH / git password issues SSH keys and ~/.ssh/config Abbreviated Office Hours Today Homework 2

10 Homework 2 Animal - Beluga - Chameleon - Dog - GermanShepard - Mammal - Orca 1. iswarmblooded 2. islivingunderwater 3. isnamedaftereuropeancountry 4. canchangecolor 5. isblackandwhite - Reptile - ShibaInu - Snake - Whale

11 Class Visibility

12 Problem Classes represent data and functionality Some functionality is for "users" of code Some functionality is "internal" or "sensitive"

13 Credit Card Account Credit Account Charge Account

14 Credit Card Account Credit Account - Code to verify status of account (ping charge) - Code to send money to account Charge Account - Code to verify status of account (ping charge) - Code to take money to account

15 Credit Card Account Credit Account - Call "Verify Account" - Send money to account Charge Account - Call "Verify Account" - Take money from account Verify Account - Code to verify status of account (ping charge)

16 Credit Card Account Credit Account - Call "Verify Account" - Send money to account Charge Account - Call "Verify Account" - Take money from account Verify Account!!!!!!!!! - Code to verify status of account (ping charge)

17 Java's Solution Public Internal and external access Private Internal class access only Properties and Methods

18 CreditCardAccount.java -->

19 Credit Card Account Credit Account Charge Account Verify Account

20 Subclassing Credit Card Account Credit Account Visa Credit Card Account Charge Account Verify Account Credit Account

21 Subclassing Credit Card Account Credit Account Visa Credit Card Account Charge Account Verify Account Credit Account Subclass "Credit Account" cannot see "Verify Account"

22 Java's Solution Public Internal and external access Private Internal class access Protected Internal class and subclass access

23 CreditCardAccount.java -->

24 Discussion Other examples for public / private / protected methods or properties Security Shared Functionality When subclasses want to share internal functionality / data

25 "Static"

26 Problem Instances describe functionality and data of a type Where to put code and data shared between instances? Constants, aggregators, "Importing", etc

27 Constants Circle property: π method: Area method: Radius

28 Circle Circle property: π method: Area method: Radius property: π method: Area method: Radius Circle Circle property: π property: π property: π method: Area method: Area method: Area method: Radius method: Radiu

29 Circle Circle property: π method: Area method: Radius property: π method: Area method: Radius Circle Circle property: π property: π property: π method: Area method: Area method: Area method: Radius method: Radiu

30 Aggregation Circle Circle Circle Circle Circle property: property: π property: π property: π property: π π method: method: Area method: Area method: Area method: Area Area method: method: Radius method: Radius method: Radius method: Radius Radius We want to find the area of multiple circles We want to store that somewhere in our code Could create a "CircleAdder" class awkward

31 Converters TheirCircle We're using someone else's code We want to convert their types into our types Could create a "CircleConverter" class OurCircle awkward

32 Java's Solution Static: Attach functionality and data to classes (instead of instances) Can also be public / private / protected Same access rules as with instances Properties and Methods

33 Static vs Instance Live on Can Access Number in system Instance Each instance The fields in the same instance Arbitrarily many Static The class Only other static values Just one

34 Circle.java -->

35 Exceptions

36 Problem Errors happen, all the time (Sod's Law) Robust programs need to deal with these errors Some errors are REALLY bad Programmers are lazy Programming languages should nudge in the right direction

37 Error Example writestufftodisk(byte[] lotsofstuff) What to do when things go wrong? Return boolean boolean writestufftodisk(byte[] lotsofstuff) Return "error code" int writestufftodisk(byte[] lotsofstuff) Multiple values ErrorAndResultObject writestufftodisk(byte[] lotsofstuff) Out parameter boolean writestufftodisk(byte[] lotsofstuff, Error errorobject)

38 Error Example writestufftodisk(byte[] lotsofstuff) What to do when things go wrong? Return boolean boolean writestufftodisk(byte[] lotsofstuff) Return "error code" int writestufftodisk(byte[] lotsofstuff) Multiple values ErrorAndResultObject writestufftodisk(byte[] lotsofstuff) Out parameter boolean writestufftodisk(byte[] lotsofstuff, Error errorobject)

39 Error Example writestufftodisk(byte[] lotsofstuff) What to do when things go wrong? Return boolean boolean writestufftodisk(byte[] lotsofstuff) Return "error code" int writestufftodisk(byte[] lotsofstuff) Multiple values ErrorAndResultObject writestufftodisk(byte[] lotsofstuff) Out parameter boolean writestufftodisk(byte[] lotsofstuff, Error errorobject)

40 Error Example writestufftodisk(byte[] lotsofstuff) What to do when things go wrong? Return boolean boolean writestufftodisk(byte[] lotsofstuff) Return "error code" int writestufftodisk(byte[] lotsofstuff) Multiple values ErrorAndResultObject writestufftodisk(byte[] lotsofstuff) Out parameter boolean writestufftodisk(byte[] lotsofstuff, Error errorobject)

41 Error Example writestufftodisk(byte[] lotsofstuff) What to do when things go wrong? Return boolean boolean writestufftodisk(byte[] lotsofstuff) Return "error code" int writestufftodisk(byte[] lotsofstuff) Multiple values ErrorAndResultObject writestufftodisk(byte[] lotsofstuff) Out parameter boolean writestufftodisk(byte[] lotsofstuff, Error errorobject)

42 Problems With these Approaches?

43 Problems With these Approaches Not enough information Large, non-meaningful lookup tables Easy to ignore

44 Java's Solution Force programmers to deal with errors through the compiler try / catch / finally try I'm about to do something risky catch Here's how I'll handle this bad thing that could happen finally Good or bad, do this last thing Part of the method signature

45 Exceptions Example public FileReader(String filename) throws FileNotFoundException

46 Exceptions Example public FileReader(String filename) throws FileNotFoundException FileReader secretsreader = new FileReader("secrets.txt");

47 Exceptions Example public FileReader(String filename) throws FileNotFoundException FileReader secretsreader = new FileReader("secrets.txt"); What could go wrong?

48 Exceptions Example public FileReader(String filename) throws FileNotFoundException try { FileReader secretsreader = new FileReader("secrets.txt"); } catch (FileNotFoundException error) { } System.out.println("Welp, seems we couldn't get the file ");

49 Exceptions Example public FileReader(String filename) throws FileNotFoundException public int read(char[] cbuf) throws IOException try { FileReader secretsreader = new FileReader("secrets.txt"); char[] secrets = new char[1000]; secretsreader.read(secrets); } catch (FileNotFoundException error) { System.out.println("Welp, seems we couldn't get the file "); } catch (IOException othererror) { System.out.println("Got the file, but couldn't read it "); }

50 URL.java -->

51

52 In Groups summer2017/ic/student.java Walk through the code Discuss how this code could be improved using visibility modifiers and static

53 In Groups Code up another example Split into two files, Main.java and Student.java Implement discussed changes

Tutorial 8 Date: 15/04/2014

Tutorial 8 Date: 15/04/2014 Tutorial 8 Date: 15/04/2014 1. What is wrong with the following interface? public interface SomethingIsWrong void amethod(int avalue) System.out.println("Hi Mom"); 2. Fix the interface in Question 2. 3.

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information

Classes, Objects, and OOP in Java. June 16, 2017

Classes, Objects, and OOP in Java. June 16, 2017 Classes, Objects, and OOP in Java June 16, 2017 Which is a Class in the below code? Mario itsame = new Mario( Red Hat? ); A. Mario B. itsame C. new D. Red Hat? Whats the difference? int vs. Integer A.

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

What can go wrong in a Java program while running?

What can go wrong in a Java program while running? Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage This lecture Summary on polymorphism, multiple

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

STATIC, ABSTRACT, AND INTERFACE

STATIC, ABSTRACT, AND INTERFACE STATIC, ABSTRACT, AND INTERFACE Thirapon Wongsaardsakul STATIC When variable is a static type, java allocates memory for it at loading time. Class loader Byte code verifier Static variable has been loaded

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

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

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

CSC207 Week 3. Larry Zhang

CSC207 Week 3. Larry Zhang CSC207 Week 3 Larry Zhang 1 Announcements Readings will be posted before the lecture Lab 1 marks available in your repo 1 point for creating the correct project. 1 point for creating the correct classes.

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

1.Which four options describe the correct default values for array elements of the types indicated?

1.Which four options describe the correct default values for array elements of the types indicated? 1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

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

CISC 323 (Week 9) Design of a Weather Program & Java File I/O CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming

More information

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

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Lecture 4. Types, Memory, Exceptions

Lecture 4. Types, Memory, Exceptions AY17/18 Sem 2 Lecture 4 Types, Memory, Exceptions input.java source files javac.class bytecode java output compile execute with Java Virtual Machine AY17/18 Sem 2 for (Printable o: objs) { o.print(); input.java

More information

AP CS Unit 6: Inheritance Notes

AP CS Unit 6: Inheritance Notes AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything

More information

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

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

Simple Java Input/Output

Simple Java Input/Output Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it

More information

Enums, Generics, Nested Types. June 23, 2017

Enums, Generics, Nested Types. June 23, 2017 Enums, Generics, Nested Types June 23, 2017 Reading Quiz What is true of Generics? A. They allow you to maintain more type information in your code B. They are required to store different types of objects

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CIS265 - Spring Exam 2 First Name Last Name CSU#

CIS265 - Spring Exam 2 First Name Last Name CSU# CIS265 - Spring 2013 - Exam 2 First Name Last Name CSU# MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) An instance of describes system errors.

More information

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM Introduction to the Assignment In this lab, you will finish the program to allow a user to solve Sudoku puzzles.

More information

Object Oriented Programming. Week 7 Part 1 Exceptions

Object Oriented Programming. Week 7 Part 1 Exceptions Object Oriented Programming Week 7 Part 1 Exceptions Lecture Overview of Exception How exceptions solve unexpected occurrences Catching exceptions Week 7 2 Exceptions Overview Week 7 3 Unexpected Occurances

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

CIS 120 Final Exam May 3, Name (printed): Pennkey (login id):

CIS 120 Final Exam May 3, Name (printed): Pennkey (login id): CIS 120 Final Exam May 3, 2013 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

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

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #3. Selections Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

More information

Recitation: Loop Jul 7, 2008

Recitation: Loop Jul 7, 2008 Nested Loop Recitation: Loop Jul 7, 2008 1. What is the output of the following program? Use pen and paper only. The output is: ****** ***** **** *** ** * 2. Test this program in your computer 3. Use "for

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

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

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003 The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled

More information

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

More information

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................

More information

Inheritance and Substitution גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Inheritance and Substitution גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון Inheritance and Substitution גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap In this chapter we will start to investigate the concepts of inheritance and substitution: The intuitive and practical

More information

For more details on SUN Certifications, visit

For more details on SUN Certifications, visit Exception Handling For more details on SUN Certifications, visit http://sunjavasnips.blogspot.com/ Q: 01 Given: 11. public static void parse(string str) { 12. try { 13. float f = Float.parseFloat(str);

More information

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

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overriding עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap A method in a child class overrides a method in the parent class if it has the same name and type signature: Parent void method(int,float)

More information

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle CS112-2012S-23 Abstract Classes and Interfaces 1 23-0: Drawing Example Creating a drawing program Allow user to draw triangles, circles, rectanlges, move them around, etc. Need to store a list of shapes,

More information

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

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

CS 200 File Input and Output Jim Williams, PhD

CS 200 File Input and Output Jim Williams, PhD CS 200 File Input and Output Jim Williams, PhD This Week 1. WaTor Change Log 2. Monday Appts - may be interrupted. 3. Optional Lab: Create a Personal Webpage a. demonstrate to TA for same credit as other

More information

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

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems

More information

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003 Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data

More information

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

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer. Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1 Announcements Lab this week is based on the textbook example

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

CS1150 Principles of Computer Science Boolean, Selection Statements

CS1150 Principles of Computer Science Boolean, Selection Statements CS1150 Principles of Computer Science Boolean, Selection Statements Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 Math Center https://www.uccs.edu/mathcenter/schedules

More information

Exceptions and Error Handling

Exceptions and Error Handling Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent

More information

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O) 116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

9. Java Errors and Exceptions

9. Java Errors and Exceptions Errors and Exceptions in Java 9. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,

More information

C# Programming for Developers Course Labs Contents

C# Programming for Developers Course Labs Contents C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring

More information

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. CS61B Lecture #12 Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. Lateness: Yes, the lateness policy does extend to Project 0. Test 1: still scheduled for 16

More information

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan COSC 121: Computer Programming II Dr. Bowen Hui University of Bri?sh Columbia Okanagan 1 A1 Posted over the weekend Two ques?ons (s?ll long ques?ons) Review of main concepts from COSC 111 Prac?ce coding

More information

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

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

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

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 7 Programmer I. Version: Demo Vendor: Oracle Exam Code: 1Z0-803 Exam Name: Java SE 7 Programmer I Version: Demo QUESTION 1 A. 3 false 1 B. 2 true 3 C. 2 false 3 D. 3 true 1 E. 3 false 3 F. 2 true 1 G. 2 false 1 Correct Answer: D :

More information

10/22/2018 Programming Data Structures

10/22/2018 Programming Data Structures 10/22/2018 Programming Data Structures Quiz 2 on Wednesday, Oct. 24! Assignment14 Quiz Content Recursion 1 Assignment14 public static int readlines(string filename) throws FileNotFoundException { FileInputStream

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

CSC207 Winter Section L5101 Paul Gries

CSC207 Winter Section L5101 Paul Gries CSC207 Winter 2017 Section L5101 Paul Gries Software Design An introduction to software design and development concepts, methods, and tools using a statically-typed objectoriented programming language

More information

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

CS61B Lecture #12. Today: Various odds and ends in support of abstraction. CS61B Lecture #12 Today: Various odds and ends in support of abstraction. Readings: At this point, we have looked at Chapters 1 9 of Head First Java. Today s lecture is about Chapters 9 and 11. For Friday,

More information

Exception Handling Generics. Amit Gupta

Exception Handling Generics. Amit Gupta Exception Handling Generics Amit Gupta Announcements Project 2 deadline 18 th Feb 9 pm. TA Consulting hours Mon Thurs B146 6 9 pm Exam 1 : Feb 15 4:30 5:20 pm Project 1 grading Exception Handling Computer

More information

Assignment 17 Deadline: Oct pm COSC211 CRN15376 Session 14 (Oct. 29)

Assignment 17 Deadline: Oct pm COSC211 CRN15376 Session 14 (Oct. 29) This in-class assignment has 2 points in total. Every bug costs 0.1-0.3 based on its severity. The deadline for this assignment is Tuesday, Oct. 30, NOON, 12 pm. In addition to the 2 points, we have an

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

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

SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.) SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.) A. int []x = 1,2,3,4,5; for(int y = 0; y < 6; y++) System.out.println(x[y]); B. staticint[] x = 7,6,5,4;

More information

d. If a is false and b is false then the output is "ELSE" Answer?

d. If a is false and b is false then the output is ELSE Answer? Intermediate Level 1) Predict the output for the below code: public void foo( boolean a, boolean b) if( a ) System.out.println("A"); if(a && b) System.out.println( "A && B"); if (!b ) System.out.println(

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 25 Nov. 8, 2010 ExcepEons and the Java Abstract Stack Machine Announcements Homework 8 (SpellChecker) is due Nov 15th. Midterm 2 is this Friday, November

More information

CSE 143 Java. Exceptions 1/25/

CSE 143 Java. Exceptions 1/25/ CSE 143 Java Exceptions 1/25/17 12-1 Verifying Validity of Input Parameters A non-private method should always perform parameter validation as its caller is out of scope of its implementation http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html

More information

Correctness and Robustness

Correctness and Robustness Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction

More information

EXCEPTIONS. Fundamentals of Computer Science I

EXCEPTIONS. Fundamentals of Computer Science I EXCEPTIONS Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)

More information

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD This Week 1. Battleship: Milestone 3 a. First impressions matter! b. Comment and style 2. Team Lab: ArrayLists 3. BP2, Milestone 1 next Wednesday

More information

Internal Classes and Exceptions

Internal Classes and Exceptions Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today

More information

CS Introduction to Data Structures Tuesday, February 2, 2016

CS Introduction to Data Structures Tuesday, February 2, 2016 CS 367 - Introduction to Data Structures Tuesday, February 2, 2016 Homework 1 due 10 pm tonight, February 2nd Homework 2 assigned tonight, due 10 pm this Friday, February 5th Program 1 due 10 pm Sunday,

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information

CS365 Midterm -- Spring 2019

CS365 Midterm -- Spring 2019 CS365 Midterm -- Spring 2019 1. This exam is closed-note, closed-book. 2. You must answer all of the questions. 3. The exam has 120 points and you will be scored out of 120 points. For example, if you

More information

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

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: Recreation @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems to

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Generating random numbers Obtain a random double value between 0.0 and 1.0, excluding 1.0 Math.random() Random

More information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure. Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

THE UNIVERSITY OF AUCKLAND

THE UNIVERSITY OF AUCKLAND THE UNIVERSITY OF AUCKLAND CompSci 101 FIRST SEMESTER, 2008 Campus: City COMPUTER SCIENCE TEST Principles of Programming (Time allowed: 75 MINUTES) NOTE: Attempt ALL questions Write your answers in the

More information

6. Java Errors and Exceptions

6. Java Errors and Exceptions Errors and Exceptions in Java 6. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,

More information

Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You ll learn much less if you just look at

Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You ll learn much less if you just look at Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You ll learn much less if you just look at the question, then the answer, and go Okay, that makes

More information

6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources

6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources 129 6. Java Errors and Exceptions Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources Errors and Exceptions in Java 130 Errors and exceptions interrupt the normal

More information

Exam Questions 1z0-853

Exam Questions 1z0-853 Exam Questions 1z0-853 Java Standard Edition 5 Programmer Certified Professional Exam https://www.2passeasy.com/dumps/1z0-853/ 1.Given: 10. class One { 11. void foo() { } 12. } 13. class Two extends One

More information

Instructions. Grading Box 2. /10 4. /10 1. /10 3. /10 5. /10. Total /50

Instructions. Grading Box 2. /10 4. /10 1. /10 3. /10 5. /10. Total /50 Instructions 1. Write your answers clearly and succinctly. (a) You will receive no point for an unclear answer. (b) There is no additional deduction for a wrong answer. (c) Do not use red ink. 2. No aids

More information

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down CS112-2012S-22 Exceptions 1 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected situation Logic error in code Like to handle these errors gracefully, not just halt the program

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Mutating Object State and Implementing Equality

Mutating Object State and Implementing Equality Mutating Object State and Implementing Equality 6.1 Mutating Object State Goals Today we touch the void... (sounds creepy right... see the movie, or read the book, to understand how scary the void can

More information

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

More information

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015 Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015 There are 9 problems on the exam, with 54 points total available. There are 8 pages to the exam (4 pages double-sided),

More information

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1 Video 2.1 Arvind Bhusnurmath SD1x-2 1 Topics Why is testing important? Different types of testing Unit testing SD1x-2 2 Software testing Integral part of development. If you ship a software with bugs,

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success }

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success } Exceptions Error Handling You do a lot on this in your practicals, so we'll just touch on it here The traditional way of handling errors is to return a value that indicates success/failure/error public

More information

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

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information