Java Programming Review (Part II) Enterprise Systems Programming.

Slides:



Advertisements
Similar presentations
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Advertisements

Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
11-Jun-15 Exceptions. 2 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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
16-Jun-15 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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Data Structures and Java CS /14/2015 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L6:
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 11 Exceptions and Input/Output Operations.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Chapter 14 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to Exceptions in Java
Creating and Modifying Text part 2
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Exception Handling Contents
Exceptions 10-May-19.
Presentation transcript:

Java Programming Review (Part II) Enterprise Systems Programming

Outline  Java programs and packages  Classes, fields, methods, objects  Naming conventions  Types, variables, parameters  Arrays  Inheritance, interfaces  Exceptions  Files and streams  Static fields and methods  Java core packages, collection classes  Generics, auto-boxing  Inner classes

Exceptions  Exception: something unexpected that can occur in the execution of a program wrong number format NullPointerException ArrayIndexOutOfBoundsException divide by zero attempt to open a file that does not exist etc.  Java provides a way to handle exceptions that are thrown: the try-catch statement

The try-catch statement try { statement1; statement2; // if exception occurs here, // statement3 will be skipped statement3; } catch ( ExceptionClass e ) { statement4; // executed after exception occurs }

Example String s; … int convertedValue; try { convertedValue = Integer.parseInt( s ); } catch( NumberFormatException e ) { convertedValue = 0; } // ensures that convertedValue has a value // even if s does not contain a valid number

Some Java Exception classes Exception RunTimeExceptionSQLExceptionIOException ArithmeticException IndexOutOfBounds Exception FileNotFound Exception These are built-in Exception classes

Categories of exceptions  Checked At compile time, the compiler requires you to address these errors Likely to happen no matter how careful you are in coding Class will not compile if you have no error handling E.g. IOException and SQLException are checked  Unchecked Class will compile even without error handling Result from mistakes in programming E.g. all RuntimeException classes are unchecked

Throwing your own exceptions  Some methods of the classes you write may result in errors during execution  One option: handle the error within that method by printing an error message Use an if-statement Can be annoying since the user of the method may get the message interspersed with other output  Better alternative: throw exceptions so that the user of the method can decide how to deal with the error

Throwing your own exceptions in Java  Exceptions are thrown from the method that could cause the exception  What needs to be done Define a class that extends Exception In the method declaration, include a throws clause In the method body, include a throw statement where the exception occurs  Users of the method now need to use a try-catch statement

Example public class Dictionary { //… public void addWord( String word, String definition ) throws DuplicateWordException { if ( getDefinition( word ) != null ) throw new DuplicateWordException(); // code to add dictionary entry here… } // … } public class DuplicateWordException extends Exception { // this class could be empty }

Example Dictionary d = new Dictionary(); try { d.addWord( “bat”, “mammal with wings” ); d.addWord( “cat”, “animal with whiskers” ); d.addWord( “bat”, “equipment used in baseball” ); d.addWord( “elephant”, “a large mammal” ); } catch( DuplicateWordException e ) { System.out.println( “Duplicate Word Error” ); } An exception will be thrown on this call

More on exceptions  Can have a more elaborate exception class by defining exception/error details inside the class; for example: error message additional data about the error (in the example, the word that causes the duplicate to occur can be stored in the DuplicateWordException class)  Different kinds of exceptions can be handled using a try-catch chain

Try-catch chain try { … file operations … } catch( FileNotFoundException se ) { … if file is not found … } catch( EOFException ee ) { … if no more data to read … } catch( IOException e ) { … for all other cases not yet covered … } …  You can use a try-catch chain to catch specific exceptions  Note that in the example the last catch clause handles any kind of IOException

RuntimeException  Make the exception class extend RuntimeException instead of Exception whenever you do not want to require that the exception be caught  The user of the method may or may not use a try-catch statement (try-catch is required for Exceptions)  If not within a try-catch, the program aborts

Ignoring exceptions  If you choose to ignore (or not catch) checked exceptions, you must declare that they will be thrown  In this example, when a file-related exception does occur, a run-time error will result public static void main( String args[] ) throws IOException { … file operations not enclosed in a try-catch statement }

Files and Streams  File: Unit of “secondary” storage as opposed to “primary” storage in memory  Stores a sequence of bytes/characters Stream operations: read from stream, write to stream  Associated with a filename  Often organized under a directory hierarchy  Text files and streams: contains readable text

Text files  To write to a text file 1. Create it. 2. Write to it (repeatedly). 3. Flush it (optional) 4. Close it.  To read from a text file 1. Open it. 2. Read from it (repeatedly). 3. Close it  Assumes the file exists.

Writing to text files  Create the text file PrintWriter f = new PrintWriter( “filename.txt” ); This opens the file. File is initially empty.  Write to the text file f.println(…); // use like System.out Can be repeated.  Close the file before exiting the program f.close(); // ensures contents are updated  If you want to update the file without closing it yet, you can call f.flush();

Reading from a text file  Open the text file FileReader reader = new FileReader( “file.txt”) Scanner in = new Scanner( reader )  Read from the text file String line = in.nextLine();  Can be repeated.  Close the text file in.close();

The static keyword  In Java, the keyword static is used to indicate that a field or method is at the level of the class  Regular fields and variables reside or operate at the level of objects

Class-level (static) fields and methods  Built-in constants or objects Math.PI, Color.green, System.out  Built-in functions Math.sqrt(), Math.abs(), Integer.parseInt()  Static methods public static void main( String[] args )  Static fields your own constants  public static final int MY_CONSTANT

Static fields  means that the field is shared by all instances of the same class  aka class variable as opposed to an instance variable  e.g., in BankAccount, balance is an instance variable – each instance has its own independent copy However, if all BankAccounts share a minimum balance value, we can make a static field for that

Example: minimum balance SV129SV506 SV008 balance minBalance There is one copy of minBalance for the whole class and shared by all instances. The BankAccount class instances of the BankAccount class

Static methods  Normally, a method applies to a particular instance b.deposit( 100); deposits 100 to a particular object (pointed to by variable b)  A static method is a method that does not operate on a particular instance That’s why we call them using ClassName.methodName()  It is not meant be invoked on an instance. It belongs to the class. Useful for functions  e.g., Math.sqrt( double d ) Note: these methods cannot refer to instance variables  can only use static fields and methods

Some Java core packages  java.lang – basic classes (no need to import)  java.util – data structure and collection classes  java.io – files and streams  java.math – math functions  java.net – networking  java.sql – JDBC  java.awt – abstract windowing toolkit (GUI)  javax.swing – platform-independent GUI  Use javap java.packagename.ClassName to print class details

Generics  Generics allow container/collection classes to be type specific Less used alternative: contents are of type Object, the topmost class in Java  Example: array lists ArrayList accounts; words.add( new BankAccount( 1000 ) ); System.out.println( s.get( 0 ).getBalance() ); Parameter to add() must be a BankAccount object

Wrapper classes and auto-boxing  Each of the primitive types have corresponding wrapper classes containing single fields of that primitive type int => Integer, double => Double, … If you need objects/object references instead of regular values, use these wrapper classes  Example: ArrayList numbers; is not allowed but ArrayList numbers; is fine Auto-boxing makes use of wrapper classes more convenient: numbers.add( 1 ); instead of numbers.add( new Integer( 1 ) );

Inner classes  In general, only one Java class is defined in a single.java file  The hard rule: A.java file must contain exactly one public class  Non-public classes can be defined in the same file, for use inside the file only  Inner classes: classes defined inside a class or inside methods of the class Restricts use of these classes to a particular scope Anonymous classes: some inner classes don’t need even have to be named, although instances may be created