Download presentation
Presentation is loading. Please wait.
1
Final Review
2
Topics Inheritance Interfaces Polymorphism File Input/output
Exception handling Recursion Java collections Sorting/searching Generics
3
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.
4
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.
5
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);
6
Answer Class A does not have a no-arg constructor.
So you cannot use new A().
7
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"
8
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");
9
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.
10
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.
11
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.
12
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.
13
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); }
14
Answer No Exception
15
Question What is wrong in the following program? class Test {
public static void main (String[] args) { try { System.out.println("Welcome to Java"); }
16
Answer You cannot have a try block without a catch block or a finally block.
17
Question What will happen if recursive method does not have a base case?
18
Answer An infinite loop occurs which results in stack overflow.
19
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.
20
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);
21
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);
22
Answer The program displays 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.
23
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
24
Answer public static int integerPower( int base, int exponent ) { if ( exponent == 1 ) return base; else return base * integerPower( base, exponent - 1 ); }
25
Question For the following expressions, what is the order of the growth of each? n2 + 2n + 1 2n + n2
26
Answer n2 + 2n + 1 O(n2) 2n + n2 O(2n)
27
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;
28
Answer O(n)
29
Question Write a method reverseList that give the argument a list, compute and returns a list with elements in reverse order
30
Answer public static LinkedList< Character > reverse( List< Character > one ) { LinkedList< Character > reversed = new LinkedList< Character >(); for ( char element : one ) reversed.addFirst( element ); return reversed; }
31
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 ] );
32
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
33
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." );
34
finally { if ( writer. = null ) writer. close(); if ( pollNumbers
finally { if ( writer != null ) writer.close(); if ( pollNumbers != null ) pollNumbers.close(); } // end finally
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.