Answer Key
University
Stony Brook UniversityCourse
CSE 114 | Introduction to Object-Oriented ProgrammingPages
12
Academic year
2023
Riley
Views
23
CSE114 Spring 2022:Midterm2 Maximum points possible: 100 Time allowed: 1 hour 20 minutes for test + 10 minutes (any technical issues that may arise during the test) = 1 hour 30 minutes. Instructions There are 24 questions in this test: 10 Questions are very short answer type carrying 2 points each. 10 Questions are short answer type carrying 4 points each. 4 Questions are medium size programming type carrying 10 points each. Questions are randomized, you are not allowed to go back to the previous question. You may login again in case of technical issues. 1. Show the output of the following code : [4] public class Problem { public static void main(String[] args ) { int [] a = {4, 15, 11}; modify ( a ); System. out .println( a [0] + ", " + a [1] + ", " + a [2]); } public static void modify( int [] x ) { x [0] = 3 * x [1]; x [1] = x [1] % x [0]; x [2] = x [2] + x [0] + x [1]; } } Solution: 45, 15, 71 2. List three access modifiers (including the default access modifier) in Java. Solution: public, private and package private(default) [4] 3. Assume that you are creating a class named ComplexNumber to represent a complex number. This class has two data members called realPart and imaginaryPart for the real and the imaginary parts of the complex number, respectively. These data fields are of type double and are private. Write a toString() method for this class. [4] Solution: public String toString() { String st = "" ; st = st + "real part: " + real + "imaginary part:" + imaginary; return st;
} 4. A class data member should only be of primitive data types. [2] a. TRUE b. FALSE 5. An instance method can: [4] a. Invoke an instance method b. Can access an instance data field c. Can invoke a static method d. Can access a static data field Solution: Can invoke an instance method Can access an instance data field Can invoke a static method Can access static data field 6. (Pick all the options that apply to the following statement:) [4] a. A static method can: b. Invoke an instance method c. Can access an instance data field d. Can invoke a static method e. Can access a static data field Solution: Can not invoke an instance method Can not access an instance data field Can invoke a static method Can access a static data field. 7. What will be the output of the following program? [4] import java.util.Date; public class Person { private String name ; private int age ; private boolean isStudent ; private Date birthDate ; public String toString() {
String st = "" ; st += "Name: " + name + "\n" ; st += "Age: " + age + "\n" ; st += "Is a student? " + isStudent + "\n" ; st += "Was born on: " + birthDate + "\n" ; return st ; } } public class TestPerson { public static void main(String[] args ) { Person p1 = new Person(); System. out .println( p1 ); } } Solution: Name: null Age: 0 Is a student? false Was born on: null 8. Comment on the correctness of the program below (correct/ compiler error). If there is any error then please fix that. You need not rewrite the whole program, just specify the error and provide the correct statement. Also, write the statements to print the elements of the array a. [Do not write or copy the complete program: only write the statements that you will add in the program below:] [4] public class Problem { public static void main(String[] args ) { int [][] x = new int [4][]; int [] f = {21, 56, 13}; int [] g = {14, 23, 61, 78}; int [] h = {100}; x [0] = f ; x [1] = f ; x [2] = g ; x [3] = h ; // write down the statements below to print the array in // text box below.
} } Solution: The program is correct. for ( int i = 0; i < x . length ; i ++) { for ( int j = 0; j < x [ i ]. length ; j ++) System. out .print( x [ i ][ j ] + " " ); System. out .println(); } 9. Suppose that we are required to design a UML class diagram to represent a class named Rectangle. In this class we have two data members called width and height of type double. The data members need to be declared as private. We need the getter methods for these two data members of this Rectangle class. How will you represent these two data members and the corresponding getter methods in the UML class diagram? [ You are not required to draw the UML, just write the corresponding declarations in UML class diagram ] [4] Solution: -width: double -height: double +getWidth():double +getHeight():double 10. An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 5 emirps. [10] Solution: public class Emirp { public static void main(String[] args ) { int count = 0; int i = 2; while ( count < 5) { if ( i != reverse ( i )) if ( isPrime ( i ) && isPrime ( reverse ( i ))) { System. out .println( i + " is an Emirp" ); count ++; } i ++; } } public static boolean isPrime( int x ) { boolean flag = true ; int divider = 2;
while ( divider <= x /2) { if ( x % divider == 0) { flag = false ; break ; } divider ++; } return flag ; } public static int reverse( int x ) { int rev = 0; int temp ; while ( x > 0) { temp = x % 10; rev = rev * 10 + temp ; x = x /10; } return rev ; } } 11. Design a class named Stock that contains: • A string data field named symbol for the stock’s symbol. • A string data field named name for the stock’s name. • A double data field named previousClosingPrice that stores the stock previous price for the previous day. • A double data field named currentPrice that stores the stock price for the current time. • A constructor that creates a stock with the specified symbol and name. • A method named getChangePercent() that returns the percentage changed from previousClosingPrice to currentPrice. Write a test program that creates a Stock object with the symbol ORCL, the name Oracle Corporation, and the previous closing price of 34.5. Set a new current price to 34.35 and display the price-change percentage. [10] Solution: public class Stock { private String symbol ; private String name ; private double previousClosingPrice ; private double currentPrice ; public Stock() { }
public Stock(String text1 , String text2 , double price1 , double price2 ) { symbol = text1 ; name = text2 ; previousClosingPrice = price1 ; currentPrice = price2 ; } public double getChangePercent() { return (( previousClosingPrice - currentPrice ) / previousClosingPrice ) * 100; } public String getSymbol() { return symbol ; } public String name() { return name ; } public double previousClosingPrice() { return previousClosingPrice ; } public double currentPrice() { return currentPrice ; } } public class TestStock { public static void main(String[] args ) { Stock a = new Stock( "ORCL" , "Oracle" , 34.5, 34.35); System. out .println( "The price change for the stock Oracle(ORCL) is " + a .getChangePercent()); } } 12. Write the following method that tests whether the array has four consecutive numbers with the same value: public static boolean isConsecutiveFour (int [] values ) Write a test program that prompts the user to enter a series of integers and displays it if the series contains four consecutive numbers with the same value. Your program should first prompt the user to enter the input size-i.e., the number of values in the series. Here is a sample run: [10] Enter the number of values: 8 Enter the values: 3 4 5 5 5 5 4 5 The list has consecutive fours. Enter the number of values: 9
Enter the values: 3 4 5 5 6 5 5 4 5 The list has no consecutive fours. Solution: import java.util.Scanner; public class Problem { public static void main(String[] args ) { Scanner stdin = new Scanner(System. in ); System. out .print( "Enter the number of values:" ); int num = stdin .nextInt(); int [] x = new int [ num ]; System. out .print( "Enter the values:" ); for ( int i = 0; i < x . length ; i ++) x [ i ] = stdin .nextInt(); System. out .println( "The elements are:" ); for ( int i = 0; i < x . length ; i ++) System. out .print( x [ i ] + " " ); boolean flag ; System. out .println(); flag = isConsecutiveFour ( x ); if ( flag ) System. out .println( "The list has consecutive fours." ); else System. out .println( "The list has no consecutive fours." ); stdin .close(); + 2] } public static boolean isConsecutiveFour( int [] values ) { boolean result = false ; if ( values . length >= 4) for ( int i = 0; i < values . length - 4; i ++) { if ( values [ i ] == values [ i + 1] && values [ i ]== values [ i && values [ i ]== values [ i + 3]) { result = true ; break ; } } return result ; } } 13. Write a program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the matrix, and finds the first row and column with most 1s. [10] Here is a sample run of the program:
0011 0011 1101 1010 The largest row index: 2 The largest column index: 2 Solution: public class BinaryMatrix { public static void main(String[] args ) { int [][] mat = new int [4][4]; double rand ; for ( int i = 0; i < mat . length ; i ++) { for ( int j = 0; j < mat [ i ]. length ; j ++){ rand = Math. random (); if ( rand >= 0.5) mat [ i ][ j ] = 1; } } printMatrix ( mat ); System. out .println( "The largest row index:" + maxRowIndex ( mat )); System. out .println( "The largest column index:" + maxColIndex ( mat )); } public static void printMatrix( int [][] mat ) { for ( int i = 0; i < mat . length ; i ++) { for ( int j = 0; j < mat [ i ]. length ; j ++) System. out .print( mat [ i ][ j ] + " " ); System. out .println(); } } public static int maxRowIndex( int [][] mat ) { int maxIndex = 0; int max = 0; int sum ; for ( int i = 0; i < mat . length ; i ++) { sum = 0; for ( int j = 0; j < mat [ i ]. length ; j ++) sum += mat [ i ][ j ]; if ( sum > max ) { max = sum ; maxIndex = i ; } }
return maxIndex ; } public static int maxColIndex( int [][] mat ) { int maxIndex = 0; int max = 0; int sum ; for ( int i = 0; i < mat [0]. length ; i ++) { sum = 0; for ( int j = 0; j < mat . length ; j ++) sum += mat [ j ][ i ]; if ( sum > max ) { max = sum ; maxIndex = i ; } } return maxIndex ; } } 14. A no-arg constructor is a default constructor in a class with no arguments. [2] a. TRUE b. FALSE 15. What do you mean by an accessor method and a mutator method in Java? [2] Solution: In Java accessor method is a public method provided in a class to access its private data field. Mutator is a method which is public and is used to update a private data field. 16. What do you mean by data field encapsulation in Java? [2] Solution: In Java data field encapsulation means that the data fields should be declared as private and the getters and/or the setters should be provided as public methods for accessing these private data fields in a class. 17. A class can be declared as private. [2] a. TRUE b. FALSE 18. (Select all the options that apply to the following statement) [2] In Java a method can be written to return (with return type): a. int b. boolean c. char d. String[] e. all the above
19. In a class definition we are allowed to declare the data members and the methods in any arbitrary order. [It is not compulsory to first define (declare) the data members before the methods definition]. So a class definition given below is valid. public class Store { public Store(String n ) { setName( n ); } public String getName() { return name ; } private String name ; public void setName(String n ) { name = n ; } public String toString() { return ( "name: " + name ); } public final double SALES_TAX_RATE = 0.06; } a. TRUE [2] b. FALSE 20. A Java array is an object that can contain primitive-type values or object-type values. When an array of objects is created, its elements are assigned the default value of null. [2] a. TRUE b. FALSE 21. The method nextLine() in Scanner class is an example of a static method. [2] a. TRUE b. FALSE 22. A call to a method with a void return type is always a statement itself, but a call to a value-returning method cannot be a statement by itself. [2] a. TRUE b. FALSE 23. What will be the output of the following program? [4] public class Problem { public static void main(String[] args ) { int size = 4; int [] intArr = new int [ size ]; char [] charArr = new char [ size ]; boolean [] boolArr = new boolean [ size ];
String[] strArr = new String[ size ]; for ( int i = 0; i < size ; i ++) { System. out .print( intArr [ i ] + ", " ); System. out .print( charArr [ i ] + ", " ); System. out .print( boolArr [ i ] + ", " ); System. out .print( strArr [ i ] + " " ); System. out .println(); } } } Solution: 0, , false, null 0, , false, null 0, , false, null 0, , false, null 24. What will be the output of the following program? [4] public class Problem { public static void main (String [] args ){ System. out .println( "# Circle objects:->" + Circle. getCount ()); Circle c1 = new Circle(); System. out .println( "radius:->" + c1 .getRadius() + ", " + "area:->" + c1 .getArea()); System. out .println( "# Circle objects:->" + Circle. getCount ()); Circle c2 = new Circle(10); System. out .println( "radius:->" + c2 .getRadius() + ", " + "area:->" + c2 .getArea()); System. out .println( "# Circle objects:->" + Circle. getCount ()); System. out .println( "# Circle objects from c1:- >" + c1 . getCount ()); System. out .println( "# Circle objects from c2:- >" + c2 . getCount ()); c2 . getDoubleRadius (); } } class Circle{ private double radius = 0; private static int count ; public Circle() { radius = 1.0;
count ++; } public Circle( double r ) { radius = r ; count ++; } public double getRadius() { return radius ; } public void setRadius( double r ) { radius = r ; } public double getArea() { return Math. PI * radius * radius ; } public static int getCount() { return count ; } public static double getDoubleRadius() { return 2* radius ; } } Solution: Error: Cannot make a static reference to the non-static field radius
CSE114 Spring 2022 Midterm 2
Please or to post comments