Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Similar documents
Final Exam Practice Questions

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS 113 PRACTICE FINAL

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Exam Duration: 2hrs and 30min Software Design

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Final Examination Semester 3 / Year 2008

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Full file at Chapter 2 - Inheritance and Exception Handling

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Java Simple Data Types

Recitation #2 Abstract Data Types, Collection Classes, and Linked List

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Java Simple Data Types

First IS-A Relationship: Inheritance

University of Palestine. Mid Exam Total Grade: 100

CS260 Intro to Java & Android 03.Java Language Basics

More Relationships Between Classes

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Rules and syntax for inheritance. The boring stuff

About this sample exam:

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Instance Members and Static Members

CS 231 Data Structures and Algorithms, Fall 2016

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Key Java Simple Data Types

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CSE 143 Sp03 Final Exam Sample Solution Page 1 of 13

COP 3330 Final Exam Review

Java for Non Majors Spring 2018

Questions Answer Key Questions Answer Key Questions Answer Key

Practice for Chapter 11

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exception-Handling Overview

SSE3052: Embedded Systems Practice

CLASS DESIGN. Objectives MODULE 4

Object-Oriented Programming More Inheritance

F I N A L E X A M I N A T I O N

TeenCoder : Java Programming (ISBN )

UNIVERSITI SAINS MALAYSIA. CIT502 Object-Oriented Programming and Software Engineering

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Making New instances of Classes

Example: Count of Points

COMP 250: Java Object Oriented Programming

CS 251 Intermediate Programming Inheritance

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

INHERITANCE AND EXTENDING CLASSES

CO Java SE 8: Fundamentals

CompuScholar, Inc. 9th - 12th grades

INHERITANCE. Spring 2019

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

Introduction to Programming Using Java (98-388)

Building Java Programs

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Distributed Systems Recitation 1. Tamim Jabban

Inheritance and Polymorphism

Java Fundamentals (II)

Week 11: Class Design

Note that if both p1 and p2 are null, equals returns true.

COMP 110/L Lecture 19. Kyle Dewey

Class, Variable, Constructor, Object, Method Questions

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

AP CS Unit 8: Inheritance Exercises

Programming II (CS300)

Final Exam Practice Questions

CH. 2 OBJECT-ORIENTED PROGRAMMING

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

CMSC 331 Second Midterm Exam

What is Inheritance?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Final Exam Practice. Partial credit will be awarded.

Inheritance (continued) Inheritance

CS 61B Discussion 5: Inheritance II Fall 2014

JAVA OPERATORS GENERAL

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Polymorphism. return a.doublevalue() + b.doublevalue();

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

In this lab we will practice creating, throwing and handling exceptions.

Computer Science II (20073) Week 1: Review and Inheritance

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance (Part 5) Odds and ends

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Programming II (CS300)

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

COE318 Lecture Notes Week 10 (Nov 7, 2011)

CS 251 Intermediate Programming Methods and Classes

Super-Classes and sub-classes

Transcription:

: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order are the constructors for these classes called when a Gamma object is instantiated?. What class is a superclass of every other class? What does one need to do to use methods inherited from that class. 3. A superclass reference can refer to a subclass object. True or False? A subclass reference can refer to a superclass object. True or False? Show an example of the true scenario? (Do not define classes, just state which class inherits from which and then write a statement that illustrates one or both of the cases above.) 4. Explain what extends keyword is used for. 5. Show how to open a file for reading characters. 6. How many classes can extend a superclass? How many superclasses can a class extend? 7. Show the output of following program: public class Test { public static void main(string[] args) { A a = new A(3); class A extends B { public A(int t) { super(); System.out.println("A s constructor is invoked"); class B { public B() { System.out.println("B s constructor is invoked"); 8. Answer the following multiple choice questions. There might be more than one correct answer - mark all that apply. (a) A subclass inherits from its superclass. i. private methods 1

ii. protected methods iii. public methods iv. static methods (b) When you implement a method that is defined in a superclass, you the original method. i. overload ii. override iii. copy iv. call (c) What is the output of running the class C. public class C { public static void main(string[] args) { Object o1 = new A(); Object o = new B(); System.out.print(o1); System.out.print(o); class A extends B { public String tostring() { return "A"; class B { public String tostring() { return "B"; i. AB ii. BA iii. BAB iv. ABA v. None of above (d) If a class named Student has a constructor Student(String name) defined explicitly, the following constructor is implicitly provided. i. public Student() ii. protected Student() iii. private Student() iv. Student() v. None 9. Design a class named Person and its two subclasses named Student and Employee. A person has a name and email address. A student has a GPA. An employee has an office number and a salary. Override the tostring method in each class to display the class name and the person s name. 10. Consider the following code. 1 public class Division { 3 public static void main ( String [ ] args ) { 4 Scanner in = new Scanner ( System. in ) ;

5 6 int num1 = 0, num = 0; 7 8 try { 9 System. out. println ( " Please enter two integers to divide : " ) ; 10 System. out. print ( " numerator : " ) ; 11 num1 = in. nextint ( ) ; 1 System. out. print ( "\ndenominator : " ) ; 13 num = in. nextint ( ) ; 14 15 System. out. p r i n t f ( "The quotient of %d and %d i s %d\n", 16 num1, num, num1/ num ) ; 17 18 19 catch ( ArithmeticException e ) { 0 System. out. println ( " Sorry, cannot divide by zero!\n" ) ; 1 catch ( InputMismatchException e ) { 3 System. out. println ( " This i s not an integer!\n" ) ; 4 5 catch ( Exception e ) { 6 System. out. println ( "You did something wrong!\n" ) ; 7 8 9 System. out. println ( "Thank you f o r trying Division. " ) ; 30 in. c l o s e ( ) ; 31 3 33 What is the output when user enters (a) 10 and 5 (b) 1 and 5 (c) 1 and 0 (d) 11 and 5.5 11. Write a CalendarDate class that has two private data fields day, and month. Your class should have a default constructor that sets the date to a random day in May (May has 31 days) compareto method (remember that it returns 0 when two CalendarDate objects are equal, a number < 0 when this object is smaller than the parameter object, and a number > 0 when this object is greater than the parameter object) 1. Write a checkdate() method that given an array of CalendarDate objects (as defined in question 11) and another CalendarDate object returns true if the object is in the array, and false otherwise. 13. Write a program that opens the file European_capitals.txt whose content is reprinted below: Paris 43833 Amsterdam 110897 Warsaw 1715517 Rome 645907 Prague 16106 London 8308369 Berlin 3415091 3

The file contains names of several capitals and their population size. You can assume that there is a single space between the name of the city and the number. You can assume that each city is listed on a new line. Your program should read in the data from this file into two arrays (one of type String, the other of type int). You program should display the following information: name of the city with smallest population name of the city with largest population total population size for all the cities. Make sure that the two arrays remain in sync as you are doing this. 14. For the purpose of this question, assume that you are developing static methods for your own statistics library MyStats (it is similar to the Java s Math library that you have been using throughout the semester). (a) Write a public static method threeequal() for MyStats that takes three int values as arguments and returns true if all three numbers are equal, false otherwise. (b) Write a public static method median() for MyStats that takes as an argument an array of sorted integer values and returns the middle value. Your method should first verify if the array is sorted, and if it is not it should throw an IllegalArgumentException. (c) Give a single Java expression that a client of MyStats could use to test whether the medians of three arrays of integer values int[] a, int[] b, and int[] c are all equal. 15. Consider the following program. 1 public class Mystery { public static void main ( String [ ] args ) { 3 4 int N = args. length ; 5 String [ ] a = new String [N ] ; 6 for ( int i = 0; i < N; i ++) { 7 a [ i ] = args [ i ] ; 8 a [ i + N] = args [N i 1 ] ; 9 10 for ( int i = 0; i < a. length ; i ++) 11 System. out. println ( a [ i ] + " " ) ; 1 System. out. println ( ) ; 13 14 (a) What does this program print out when the following command is executed (from the command line)? java Mystery aaa bbb ccc (b) What does this program print out when the following command is executed (from the command line)? java Mystery xxxx yyyy 16. Consider the following program, which is supposed to read in integer N from standard input, read N strings from standard input, and print them to standard output in reverse order. 1 public class ReverseInputBuggy { 3 public static void main ( String [ ] args ) 4

4 { 5 java. u t i l. Scanner in = new java. u t i l. Scanner ( Std. in ) ; 6 int N = in. nextint ( ) ; 7 String s ; 8 for ( int i = 1; i < N; i ++) 9 s [ i ] = in. next ( ) ; 10 for ( int i = N; i >= 0; i ) 11 System. out. println ( s [ i ] ) ; 1 13 This program has three bugs. (a) Which bug prevents the program from compiling successfully? Identify the line number where the bug appears and give a correct version of this line of code. Line number Correct version: (b) After fixing the first bug, which bug causes the program to crash? Identify the line number where the bug appears and give a correct version of this line of code. Line number Correct version: (c) After fixing the first two bugs, which bug causes the program to produce incorrect output? Identify the line number where the bug appears and give a correct version of this line of code. Line number Correct version: 17. Implement the Java class Digits, which allows you to access a number by its individual digits. Here is the complete interface: 1 public class Digits { 3 / / c r e a t e D i g i t s v e r s i o n o f num 4 / / a s s u m e num >= 0 5 public Digits ( int num) {... 6 7 / / g e t s d i g i t i o f t h e number, 8 / / s u c h t h a t d i g i t 1 i s t h e l e f t m o s t d i g i t, 9 / / a n d d i g i t n u m D i g i t s ( ) i s t h e r i g h t m o s t d i g i t 10 / / a s s u e 1 <= i <= n u m D i g i t s ( ) 11 public int getdigit ( int i ) {... 1 13 / / r e t u r n s t h e n u m b e r o f d i g i t s i n t h e n u m b e r 14 public int numdigits ( ) {... 15 16 / / r e t u r n s t h e i n t e g e r i t s e l f 17 public int getint ( ) {... 18 19 Here s an example of using the class: Digits zero(0); System.out.println(zero.numDigits() + + zero.getdigit(1)); // prints: 1 0 5

Digits digits(507); System.out.println(digits.numDigits()); // prints: 4 System.out.println(digits.getDigit(1) + + digits.getdigit(3)); // prints: 5 0 System.out.println(digits.getInt()); // prints: 507 Hint: the modulus (%) and integer division operators will be useful in your implementation. 18. Write the Java function lengthofsortedsequence which returns the length of the longest sorted sequence in an array. For this problem a sorted sequence is a sequence of non-decreasing values. Here are some examples: array return value from lengthofsortedsequence( array ) [-7 3 99-10 0 0 43 10 0 30 5] 4 [-1,, 3, 3] 4 [5,, 1] 1 [1] 1 [] 0 19. Write a Java class Point that represents (x,y) point in a plain. The class should implement Comparable interface. The points should be compared based on their distance from the origin (point (0,0)). The distance from the origin can be computed using distance = x + y. Your class should implement all methods needed for the following code to compile and run successfully: Random r = new Random; Point [] mypoints = new Point[10]; for (int i = 0; i < mypoints.length; i++) mypoints[i] = new Point(r.nextDouble(), r.nextdouble() ); Arrays.sort(myPoints); You do not need to provide any additional methods. 0. Implement the static method mode, which returns the value that occurs most often in an array of integers. You may assume the array has at least one element, and all of the values in the array are in the range 0-100. If there is more than one value that occurs most often, return the smallest such value (See Example below). Here are some examples: Example 1: array contains 99 86 99 99 95 86, mode(array) returns 99 Example : array contains 3 15 15 74 3, mode(array) returns 15 Example 3: array contains 76, mode(array) returns 76 For full credit, your answer must only traverse the data in array once. Hint: you are allowed to use additional memory. 1. For each of the following Java definitions, fill in the question marks (???) such that the given main class always prints the number 4. If it s not possible to do this, then explain why. Keep your answers as simple as possible. (a)1 class C { public int foo ( ) { 3 return 10; 4 5 6

6 class S extends C { 7??? 8 9 class Main { 10 public static void main ( String [ ] args ) { 11 S x = new S ( 4 ) ; 1 System. out. println ( x. foo ( ) ) ; 13 14 (b)1 class C { private int x ; 3 public C( int x ) { 4 this. x = x ; 5 6 public int foo ( ) { 7 return x ; 8 9 10 class S extends C { 11 public S ( ) { 1??? 13 14 15 class Main { 16 public static void main ( String [ ] args ) { 17 S x = new S ( ) ; 18 System. out. println ( x. foo ( ) ) ; 19 0 (c)1 class C {??? 3 4 class Main { 5 public static void main ( String args [ ] ) { 6 C x = new C ( ) ; 7 C y = new C ( ) ; 8 System. out. println ( x. get ( ) + y. get ( ) + 1 ) ; 9 10. Write the method sumseries() that given an integer argument n will return as a double the following sum: 1 n + n 1 + 3 n +... + n 1 + n 1. Do not write a full program with input and output, just the method. Hints/Notes: You need only a single loop. The return value is a double, make sure that as the sum is computed using double division and not integer division. 7

You don t need to check for valid values of n, assume it s an integer > 0. 3. Define a class PongBall that is used for a Pong game (just like the one you implemented for one of the assignments). The class should have data fields representing its x and y coordinates of the center, and two data fields that indicate increments in both x and y directions when the ball moves. It should have a constructor that initializes the balls position to a random location within a window that is 300x300 pixels - you need to decide if this constructor requires any parameters or not. The increments in both x and y directions should be set to. Provide a move() method that adjusts the balls position (you do not need to worry about the boundary conditions) and draws the ball in its new position in the window. 4. What would be printed by the following programs? (a)1 public class CatsAndDogs { 3 public static void main ( String [ ] args ) { 4 foo ( " Cats and Dogs ", 4 ) ; 5 6 7 public static void foo ( String s, int n ) { 8 i f ( n <= 1) 9 System. out. println ( " Cats " ) ; 10 else { 11 System. out. println ( s ) ; 1 foo ( s, n 1 ) ; 13 14 15 (b)1 public class Numbers { 3 public static void main ( String [ ] args ) { 4 int [ ] l i s t = { 1,, 3, 4, 5 ; 5 6 System. out. println ( foo ( l i s t, 0, l i s t. length 1) ) ; 7 8 public static int foo ( int [ ] nums, int begin, int end ) { 9 i f ( begin == end ) 10 return nums[ begin ] ; 11 else 1 return nums[ begin ] + foo (nums, begin +1, end ) ; 13 14 5. Write an iterative and recursive implementation of a method that given two values: a real number x and an integer y, computes the value of x y. 6. Given the following recursive method, answer the short questions below: 1 int puzzle ( int base, int l i m i t ) { 3 i f ( base > l i m i t ) 4 return 1; 5 else i f ( base == l i m i t ) 6 return 1; 7 else 8

8 return base puzzle ( base + 1, l i m i t ) ; 9 What would be printed by the following calls to the recursive method(write your answer next to each statement): System.out.println( puzzle (5,) ); System.out.println( puzzle (,5) ); System.out.println( puzzle (0,0) ); Which lines of code contain the base case(s)? Which lines of code contain the general/recursive case(s)? What is the total number of calls made to puzzle method when calculating puzzle (5,) (include the initial call)? What is the total number of calls made to puzzle method when calculating puzzle (,5) (include the initial call)? 7. What is the problem with the following recursive method to compute a n, for positive integer n? public static double exponent(double a, int n) { return a*exponent(a,n-1); Describe briefly how this should be fixed. Your solution should still use recursion. 9