Final Review. Topics Inheritance Interfaces Polymorphism File Input/output Exception handling...

34
Final Review

Transcript of Final Review. Topics Inheritance Interfaces Polymorphism File Input/output Exception handling...

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?A. The program compiles fine, but you cannot create an instance of Square

because the constructor does not specify the length of the Square.B. The program has a compile error because you attempted to invoke the

GeometricObject class's constructor illegally.C. 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); }}

A. The program compiles fine, but you cannot create an instance of Square

because the constructor does not specify the length of the Square.B. The program has a compile error because you attempted to invoke the

GeometricObject class's constructor illegally.C. 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 { 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() { 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"); }}

A. noneB. "The constructor of B is invoked"C. "The default constructor of A is invoked" "The constructor of B is invoked"D. "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

B() {

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);}

A. Remove abstract in the setCode method declaration.B. Change protected to public.C. Add abstract in the class declaration.D. 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);}

A. Remove abstract in the setCode method declaration.B. Change protected to public.C. Add abstract in the class declaration.D. 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.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

Answerpublic 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.println( "Error: Files cannot be opened." ); } // end catch catch ( FormatterClosedException formatterClosedException ) { System.err.println( "Error: Output file is closed." ); } // end catch catch ( SecurityException securityException ) { System.err.println( "Error opening file for writing." ); } // end catch catch ( IllegalFormatException illegalFormatException ) { System.err.println( "Error writing data to file." ); } // end catch catch ( NoSuchElementException noSuchElementException ) { System.err.println( "Error reading from file." ); } // end catch catch ( IllegalStateException illegalStateException ) { System.err.println( "Error: Input file is closed." ); } // end catch

finally { if ( writer != null ) writer.close();

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