Final Review.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Java Language Quick-Reference Guide B. Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the.
CIS 183, Fall 2000, Dr. Iren Valova, 1 package Chapter7; public class Circle { private double radius; public Circle(double radius) { radius=radius; } public.
Written by: Dr. JJ Shepherd
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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:
Week 1 - Friday.  What did we talk about last time?  Basic programming model  Other Java stuff  References  Static  Inner classes  Exceptions.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
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.
Object Oriented Programming Lecture 2: BallWorld.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Testing and Exceptions
Building Java Programs Chapter 7
Web Design & Development Lecture 7
Tutorial Exceptions Handling.
Exceptions.
Exceptions.
Presentation transcript:

Final Review

Topics Inheritance Interfaces Polymorphism File Input/output Exception handling Recursion Java collections Sorting/searching Generics

Question Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code: class Square extends GeometricObject { double length; Square(double length) GeometricObject(length); }  Which is right? The program compiles fine, but you cannot create an instance of Square because the constructor does not specify the length of the Square. The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally. The program compiles fine, but it has a runtime error because of invoking the Square class's constructor illegally.

Answer Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code: class Square extends GeometricObject { double length; Square(double length) GeometricObject(length); }   The program compiles fine, but you cannot create an instance of Square because the constructor does not specify the length of the Square. The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally. The program compiles fine, but it has a runtime error because of invoking the Square class's constructor illegally.

Question What is wrong in the following code? class Test {   class Test { public static void main(String[] args) { A a = new A(); a.print(); } class A { String s; A(String s) { this.s = s; public void print() { System.out.print(s);

Answer Class A does not have a no-arg constructor. So you cannot use new A().

Question What is the output of running class C? class A { public A() {   class A { public A() { System.out.println( "The default constructor of A is invoked"); } class B extends A { public B(String s) { System.out.println(s); public class C { public static void main(String[] args) { B b = new B("The constructor of B is invoked"); none "The constructor of B is invoked" "The default constructor of A is invoked" "The constructor of B is invoked" "The default constructor of A is invoked"

Answer "The default constructor of A is invoked" "The constructor of B is invoked" super(); is always there if you don't specify explicitly. Java only adds automatic call if you don't specify it explicitly. E.g. B() { super(); System.out.println(“B’s constructor called!"); } is same as System.out.println("B");

Question Which of the following possible modifications will fix the errors in this code? public class Test { private double code;   public double getCode() { return code; } protected abstract void setCode(double code); Remove abstract in the setCode method declaration. Change protected to public. Add abstract in the class declaration. b and c.

Answer Which of the following possible modifications will fix the errors in this code? public class Test { private double code;   public double getCode() { return code; } protected abstract void setCode(double code); Remove abstract in the setCode method declaration. Change protected to public. Add abstract in the class declaration. b and c.

Question An instance of _________ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Answer An instance of ___ Error __ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Question What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); }

Answer No Exception

Question What is wrong in the following program? class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); }

Answer You cannot have a try block without a catch block or a finally block.

Question What will happen if recursive method does not have a base case?

Answer An infinite loop occurs which results in stack overflow.

Question Write a program that reads words separated by spaces from a text file and displays words in ascending order. (If two words are the same, display only one). Pass the text filename from the command line.

Answer import java.util.*; public class Test {  import java.io.*; import java.util.*;   public class Test { public static void main(String[] args) throws Exception {  File file = new File(args[0]); Scanner input = new Scanner(file); TreeSet<String> set = new TreeSet<String>(); while (input.hasNext()) { set.add(input.next()); } for (String word : set) System.out.println(word);

Question What happens when following code is executed?   public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); } public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1);

Answer The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException.   Explanation: xMethod(x, 5) is invoked, then xMethod(x, 4), xMethod(x, 3), xMethod(x, 2), xMethod(x, 1), xMethod(x, 0). When invoking xMethod(x, 0), a runtime exception is raised because System.out.print(' '+x[0-1]) causes array out of bound.

Question Write a recursive method power(base, exponent) that, when called, returns base exponent .For example, power( 3,4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. [Hint: The recursion step should use the relationship base exponent = base · base exponent – 1

Answer public static int integerPower( int base, int exponent ) { if ( exponent == 1 ) return base; else return base * integerPower( base, exponent - 1 ); }

Question For the following expressions, what is the order of the growth of each? n2 + 2n + 1 2n + n2

Answer n2 + 2n + 1 O(n2) 2n + n2 O(2n)

Question What is the growth rate of the following method? public static int count(int[] a, int c) { int count = 0; for (int i = 0; i < a.length; i++) if (a[i] == c) count++; } return count;

Answer O(n)

Question Write a method reverseList that give the argument a list, compute and returns a list with elements in reverse order

Answer public static LinkedList< Character > reverse( List< Character > one ) { LinkedList< Character > reversed = new LinkedList< Character >(); for ( char element : one ) reversed.addFirst( element ); return reversed; }

Question Assuming following code included in a try block write all possible (most specific) catch blocks (with proper error messages printed by you in your own words) and a finally clause that close the files. int[] frequency = new int[ 6 ]; Formatter writer = null; Scanner pollNumbers = null; pollNumbers = new Scanner( new File( "numbers.txt" ) ); writer = new Formatter( "output.txt" ); writer.format( "%-12s%-12s\n", "Rating", "Frequency" ); // for each answer, use that value as subscript to // determine element to increment while ( pollNumbers.hasNext() ) ++frequency[ pollNumbers.nextInt() ]; // append frequencies to String output for ( int rating = 1; rating < frequency.length; rating++ ) writer.format( "%-12d%-12d\n", rating, frequency[ rating ] );

Answer int[] frequency = new int[ 6 ]; Formatter writer = null; Scanner pollNumbers = null; try { pollNumbers = new Scanner(new File( "numbers.txt" ) ); writer = new Formatter( "output.txt" ); writer.format( "%-12s%-12s\n", "Rating", "Frequency" ); // for each answer, use that value as subscript to // determine element to increment while ( pollNumbers.hasNext() ) ++frequency[ pollNumbers.nextInt() ]; // append frequencies to String output for ( int rating = 1; rating < frequency.length; rating++ ) writer.format( "%-12d%-12d\n", rating, frequency[ rating ] ); } // end try

catch ( FileNotFoundException fileNotFoundException ) { System. err catch ( FileNotFoundException fileNotFoundException ) { System.err.println( "Error: Files cannot be opened." ); } // end catch catch ( FormatterClosedException formatterClosedException ) System.err.println( "Error: Output file is closed." ); catch ( SecurityException securityException ) System.err.println( "Error opening file for writing." ); catch ( IllegalFormatException illegalFormatException ) System.err.println( "Error writing data to file." ); catch ( NoSuchElementException noSuchElementException ) System.err.println( "Error reading from file." ); catch ( IllegalStateException illegalStateException ) System.err.println( "Error: Input file is closed." );

finally { if ( writer. = null ) writer. close(); if ( pollNumbers finally { if ( writer != null ) writer.close(); if ( pollNumbers != null ) pollNumbers.close(); } // end finally