Computing Science 114 Solutions to Final Examination Tuesday December 14, 2004

Similar documents
Contents. 9-1 Copyright (c) N. Afshartous

Java Interview Questions and Answers

J a v a Quiz (Unit 3, Test 0 Practice)

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Crash Course in Java

public static void main(string[] args) { System.out.println("hello, world"); } }

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

The following program is aiming to extract from a simple text file an analysis of the content such as:

Data Structures and Algorithms Written Examination

Unit 6. Loop statements

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Introduction to Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Introduction to Programming

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Part I. Multiple Choice Questions (2 points each):

Introduction to Java. CS 3: Computer Programming in Java

Section IV.1: Recursive Algorithms and Recursion Trees

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Java Programming Fundamentals

Object Oriented Software Design

AP Computer Science Java Mr. Clausen Program 9A, 9B

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

AP Computer Science Java Subset

Java CPD (I) Frans Coenen Department of Computer Science

Object Oriented Software Design

Fundamentals of Java Programming

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

13 Classes & Objects with Constructors/Destructors

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Java Application Developer Certificate Program Competencies

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Chapter 2 Introduction to Java programming

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Object-Oriented Programming

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Regular Expressions and Automata using Haskell

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

In this Chapter you ll learn:

An Overview of Java. overview-1

NUMBER SYSTEMS APPENDIX D. You will learn about the following in this appendix:

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Semantic Analysis: Types and Type Checking

Install Java Development Kit (JDK) 1.8

Algorithms and Data Structures Written Exam Proposed SOLUTION

AP Computer Science Static Methods, Strings, User Input

Sample CSE8A midterm Multiple Choice (circle one)

Pemrograman Dasar. Basic Elements Of Java

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Moving from CS 61A Scheme to CS 61B Java

java Features Version April 19, 2013 by Thorsten Kracht

Sources: On the Web: Slides will be available on:

8 Primes and Modular Arithmetic

Habanero Extreme Scale Software Research Project

Chapter 7: Sequential Data Structures

Computer Programming I

Example of a Java program

VHDL Test Bench Tutorial

Programming with Data Structures

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Why? A central concept in Computer Science. Algorithms are ubiquitous.

The C Programming Language course syllabus associate level

Basic Object-Oriented Programming in Java

Java Crash Course Part I

CS 106 Introduction to Computer Science I

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

Automata and Computability. Solutions to Exercises

(Eng. Hayam Reda Seireg) Sheet Java

CS 111 Classes I 1. Software Organization View to this point:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Number Representation

C H A P T E R Regular Expressions regular expression

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Properties of Real Numbers

C++ INTERVIEW QUESTIONS

7.1 Our Current Model

Lecture 5: Java Fundamentals III

Pseudo code Tutorial and Exercises Teacher s Version

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

=

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Programming and Software Development CTAG Alignments

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Introduction to Data Structures

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Lab Experience 17. Programming Language Translation

Chapter 2: Elements of Java

The ADT Binary Search Tree

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Transcription:

Computing Science 114 Solutions to Final Examination Tuesday December 14, 2004 INSTRUCTOR: I. E. LEONARD TIME: 3 HOURS Question 1. [10 = 5 + 5 pts] An operator is said to be overloaded when it is used for two or more different operations. (a) Describe at least two different ways in which the symbol + can be used in a Java program. Answer: As the arithmetic operator which operates on two integers and produces the sum of the two integers; and as the concatenation operator which operates on two strings and produces the concatenated string. (b) Write a Java code fragment which uses the overloaded operator + in the two different ways as described in part (a). Answer: System.out.println("The answer is as easy as " + (1 + 2) + " = 3"); Question 2. [10 = 5 + 5 pts] An instance method in a given class may also be overloaded. (a) What does it mean to say that an instance method is overloaded? Answer: A method is overloaded when, within the same class, you have two (or more) definitions with the same name. (b) Can a Java class contain both of the following method definitions? Give a reason. public static int convertvalue(double number){ if (number > 0.0) return (int) number; return 0; public static double convertvalue(int number){ if (number > 0) return (double) number; return 0.0;

Answer: When you overload a method, any two definitions of the same method must either have different numbers of parameters, or some parameter position must be of differing types in the two definitionsr. A Java class may therefore contain both of the methods above. Question 3. [10 = 5 + 5 pts] Consider the following Java program: import java.lang.*; import java.util.*; public class Prob3{ public static void main(string args[]){ prob3method(1,2); public static void prob3method(int M, double N){ System.out.println("M + N = " + (M + N)); public static void prob3method(double M, int N){ System.out.println("M + N = " + (M + N)); (a) The program above will not compile. Why not? Answer: The overloaded methods are fine. However, Java always tries to use overloading before it tries to use automatic type conversion. If Java can find a definition of a method that matches the types of the arguments, it will use that definition. Java will not do an automatic type conversion of a method s argument until after it has tried and failed to find a definition of the method with parameter types that exactly match the arguments in the method definition. In this case, the methods differ in the type of their parameter, and so this is a valid overloading of the method name prob3method. However, Java cannot decide whether to convert the int value 2 to a double value 2.0 and use the first definition of prob3method, or whether to convert the int value 1 to a double value 1.0 and use the second definition.

(b) Find and correct the error in the program. What is the output? Answer: The error occurs in the method main, where the invocation of the method is made, since Java cannot decide which overloaded definition of prob3method to use. In this situation, Java issues an error message indicating that the method invocation prob3method(1,2) is ambiguous. There are several ways to correct the error, the easiest solution is to change the method invocation to prob3method(1.0,2) or prob3method(1,2.0). In both cases the output would be M + N = 3.0. Another solution is to change the type of one of the parameters in one of the methods from double to int. Yet another solution is write a separate method where both parameters are of type int. In all of these cases, the output would be M + N = 3. Question 4. [10 = 5 + 5 pts] In Java, a String is immutable, meaning that once it is instantiated, a Java String cannot be altered in any way. (a) Given the fact that a String is immutable, explain how the following code works. import java.lang.*; import java.util.*; public class Prob4a{ public static void main(string args[]){ String name = "Ed"; name = name + " Leonard"; System.out.println(name); Answer: In the program, the variable name is bound to the String object whose value is "Ed", and in the assignment statement name = name + " Leonard"; Java will evaluate the right-hand side, creating a new String object, whose value is the concatenation of name + "Leonard ". It will rebind the variable name to this new String object, and the previous String object that name was bound to becomes an orphan, that is, an object that no longer has any references to it and will be garbage collected.

(b) What is the output of the following Java program? import java.lang.*; import java.util.*; public class Prob4b{ public static void main(string[] args){ String name = "Ed Leonard"; String answer = new String(mysteryMethod(name)); System.out.println(answer); public static String mysterymethod(string s){ String result = new String(); for (int k = s.length()-1; k >= 0; k--) result = result + s.substring(k,k+1); return result; Answer: The method mysterymethod returns a String object in which the letters are reversed. It works by creating a new String object and concatenating it with substrings of length 1, which contain, in turn, the characters of the original String object, starting with the last character in the original String and ending with the first character. If the input String has the value Ed Leonard, then the output String has the value dranoel de. Question 5. [10 = 5 + 5 pts] A default constructor is a constructor with no parameters. The wrapper classes Integer, Double, Character, Boolean, Byte, Short, Long, and Float have no default constructors. (a) How would you create and initialize a new object in one of these classes? Answer: For the wrapper class Integer, we can create and initialize a new object N in this class as follows: Integer N = new Integer(15);

Similarly for the other wrapper classes, for example, Double height = new Double(1.5); Character mymark = new Character( A ); Boolean valid = new Boolean(true); Byte bit = new Byte(1); et cetera. (b) When is a default constructor provided automatically by Java and when is it not provided? Answer: If you give no constructor definition for a class, Java will automatically provide a default constructor. If you provide one or more constructors of any sort, then Java does not provide any constructors beyond those that you define. Therefore, if you define one or more constructors and none of them is a default constructor, then the class has no default constructor.

Question 6. [10 pts] What is the output of the following Java code? import java.lang.*; import java.util.*; public class TestEquals{ public static void main(string[] args){ int[] a = new int[3]; int[] b = new int[3]; for (int i = 0; i < a.length; i++) a[i] = i*i; for (int i = 0; i < b.length; i++) b[i] = i*i; if (b == a) System.out.println("Equal by ==."); else System.out.println("Not equal by ==."); if (equals(b,a)) System.out.println("Equal by the equals method."); else System.out.println("Not equal by the equals method."); public static boolean equals(int[] a, int[] b){ boolean match; if (a.length!= b.length) match = false; else{ match = true; int i = 0; while (match && (i < a.length)){ if (a[i]!= b[i]) match = false; i++; return match; Answer: The output is Not equal by ==. Equal by the equals method.

Question 7. [15 pts] Given an array of length n containing only the digits 0 and 1, the following method claims to determine whether or not the array contains 3 or more consecutive zeros, that is, it returns true if the array does not contain 3 or more consecutive 0 s and false otherwise. public static boolean consecutiveones(int[] B, int n) { if (n == 0 n == 1) return true; else if (B[n-1] == 0 && B[n-2] == 0 && B[n-3] == 0) return false; else return consecutiveones(b,n-1); (a) What is the output if n = 3 and the array B contains 0 0 1? The output is the error message: ArrayIndexOutOfBoundsException. (b) What happens if n = 3 and the array B contains 0 0 0? The output is: false. (c) If there is an error in the method, change it so that it produces the correct output. The corrected method is shown below. public static boolean consecutiveones(int[] B, int n) { if (n == 0 n == 1 n == 2) return true; else if (B[n-1] == 0 && B[n-2] == 0 && B[n-3] == 0) return false; else return consecutiveones(b,n-1); The reason for the error in part (a) is the lazy evaluation of the conjunction performed by Java. For the input 0 0 1, with n = 3, the last recursive call, consecutiveones(b,2) forces the evaluation of B[2-3] == 0, since B[1] == 0 and B[0] == 0 are true. For the input 0 0 0, with n = 3, the first recursive call returns false, since now, with this input, B[2] == 0, B[1] == 0, and B[0] == 0 all evaluate to true.

Question 8. [15 pts] Complete the recursive method below. The method has one parameter n, which is a nonnegative integer, and returns the number of zero digits in n. Fill in the blanks in the spaces below the code. Assume that n does not have any leading 0 s. pubic static int numberofzeros(int n) { if (n == 0) return ; // base case (a) else if (n < 10) return ; // base case (b) else if (n%10 == 0) return ; // recursive call (c) else return ; // recursive call (d) Answer: The answers are: (a) 1 (b) 0 (c) numberofzeros(n/10) + 1 (d) numberofzeros(n/10) The completed code is given below. pubic static int numberofzeros(int n) { if (n == 0) return 1; else if (n < 10) return 0; else if (n%10 == 0) return numberofzeros(n/10) + 1; else return numberofzeros(n/10);

(e) Draw the recursion tree when the method is called with n = 1001. Answer: numberofzeros(1001) numberofzeros(100) 0+1+1 = 2 0+1 = 1 numberofzeros(10) 0 numberofzeros(1) Question 9. [10 pts] Write the pseudocode for an algorithm to solve the following problem. Given a positive integer with N digits, find the next smallest integer that can be formed using exactly the same digits that appear in the original integer, or output a message stating that no such smaller integer exists. Answer: The algorithm we seek is fairly straightforward. Search through the digits from right to left until we find the first inversion, that is, the first pair that decreases the value if they are interchanged. Interchange the leftmost digit in this pair with the next smallest digit to its right. Sort the digits to the right of this leftmost digit in the pair into decreasing order from left to right. For example, 8 4 1 2 inversion 3 4 5 6 8 4 1 2 3 switch 4 5 6 8 3 1 2 4 4 5 6 sort 8 3 6 5 4 4 2 1 done!