Midterm #2 Sample Questions Solutions

Similar documents
ASSIGNMENT 5 TIPS AND TRICKS

Final Exam Practice Questions

Chapter 8. Characters and Strings

Chapter 2 Bits, Data Types, and Operations

Chapter 2 Bits, Data Types, and Operations

Introduction to Decision Structures. Boolean & If Statements. Different Types of Decisions. Boolean Logic. Relational Operators

Chapter 2 Bits, Data Types, and Operations

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

1.1. INTRODUCTION 1.2. NUMBER SYSTEMS

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Number Systems for Computers. Outline of Introduction. Binary, Octal and Hexadecimal numbers. Issues for Binary Representation of Numbers

Watch the following for more announcements

CS341 *** TURN OFF ALL CELLPHONES *** Practice NAME

Exercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014

The Binary Number System

CPS 104 Computer Organization and Programming Lecture-2 : Data representations,

5/17/2009. Digitizing Discrete Information. Ordering Symbols. Analog vs. Digital

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Final CSE 131 Fall 2014

Bits and Bytes. Data Representation. A binary digit or bit has a value of either 0 or 1; these are the values we can store in hardware devices.

Fundamentals of Programming (C)

Final CSE 131 Fall 2015

Oberon Data Types. Matteo Corti. December 5, 2001

Fundamentals of Programming

Do not start the test until instructed to do so!

Midterm CSE 131 Winter 2012

Binary Numbers. The Basics. Base 10 Number. What is a Number? = Binary Number Example. Binary Number Example

Chapter 2 Bits, Data Types, and Operations

Do not start the test until instructed to do so!

CSE 30 Fall 2013 Final Exam

Chapter 2 Number System

Midterm CSE 131 Winter 2013

Do not start the test until instructed to do so!

+ Inheritance. n Superclass (base class) higher in the hierarchy. n Subclass (child class) lower in the hierarchy

Variables and data types

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CSE 30 Spring 2006 Final Exam

Chapter 2 Bits, Data Types, and Operations

Data Representation and Binary Arithmetic. Lecture 2

CS170 Introduction to Computer Science Midterm 2

Midterm CSE 131 Winter 2014

Final CSE 131 Winter 2010

void mouseclicked() { // Called when the mouse is pressed and released // at the same mouse position }

Number Representations

Lecture (09) x86 programming 8

Midterm CSE 131 Fall 2014

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Under the Hood: Data Representation. Computer Science 104 Lecture 2

CSE 30 Fall 2012 Final Exam

1 Short Answer (10 Points Each)

Final CSE 131 Winter 2012

EE 109 Unit 2. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

PureScan - ML1. Configuration Guide. Wireless Linear Imager Wireless Laser scanner - 1 -

Chapter 3. Information Representation

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

Fundamental Data Types

Week 1 / Lecture 2 8 March 2017 NWEN 241 C Fundamentals. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

Midterm CSE 131 Winter 2015

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

COE318 Lecture Notes Week 4 (Sept 26, 2011)

CSE 30 Winter 2014 Final Exam

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

CS 159 Credit Exam. What advice do you have for students who have previously programmed in another language like JAVA or C++?

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

CPSC 213. Introduction to Computer Systems. Procedures and the Stack. Unit 1e

Number Systems Base r

Experiment 3. TITLE Optional: Write here the Title of your program.model SMALL This directive defines the memory model used in the program.

Number System (Different Ways To Say How Many) Fall 2016

EXPERIMENT 8: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

EXPERIMENT 7: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

CSE 30 Winter 2009 Final Exam

DATA REPRESENTATION. Data Types. Complements. Fixed Point Representations. Floating Point Representations. Other Binary Codes. Error Detection Codes

CSE 30 Fall 2006 Final Exam

CPSC 213. Introduction to Computer Systems. Procedures and the Stack. Unit 1e

CSE 30 Fall 2007 Final Exam

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras

Remedial classes. G51PRG: Introduction to Programming Second semester Lecture 2. Plan of the lecture. Classes and Objects. Example: Point class

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

EE 109 Unit 2. Binary Representation Systems

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

Unit 3. Analog vs. Digital. Analog vs. Digital ANALOG VS. DIGITAL. Binary Representation

CSE 30 Spring 2007 Final Exam

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 02, FALL 2012

plc numbers Encoded values; BCD and ASCII Error detection; parity, gray code and checksums

Introduction to Programming Using Java (98-388)

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

1. Character/String Data, Expressions & Intrinsic Functions. Numeric Representation of Non-numeric Values. (CHARACTER Data Type), Part 1

Simple Data Types in C. Alan L. Cox

ENCM 339 Fall 2017 Lecture Section 01 Lab 3 for the Week of October 2

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

Pace University. Fundamental Concepts of CS121 1

1 Short Answer (10 Points Each)

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Source coding and compression

Table of Contents Sleep Settings How to Configure the Scanner. 7 Chapter 2 System Setup

Transcription:

Midterm #2 Sample Questions Solutions 1. Short answer questions #1 (10 points) Answer 4 of the first 5 questions (#'s 1 through 5) (a) What class or classes can access and use public member variables and methods? What class or classes can access and use private member variables and methods? (2 points) Public classes, methods and data fields can be accessed from any class. Private makes methods and data fields accessible only from within its own class. (b) Why declare a member variable private? (2 points) Member variables should be declared private to prevent data from being tampered with directly. Instead, access to these variables should be controlled by getter and setter methods. Because access is mediated through these methods, classes become easier to maintain for example, adding validation can achieved by changing a single method, rather than changing all of programs that directly access the member variable. (c) What technique or mechanism can you use to give controlled access to a private member variable? That is, if you have a private member variable in your class, how can a programmer using the class read the private member variable and/or change it? (2 points) As above, we can create methods to allow access to private member variables: getters (accessors) allow the reading of private member variables setters (mutators) allow the changing/setting of private member variables (d) Name 3 ways that declaring and using a constructor is different from declaring or using a regular method. What is a constructor used for? (2 points) A constructor is a special method that used to create objects of the type that the constructor is named after / declared in. 1. The constructor's name is the same as the class that is defined in 2. It is not necessary to declare a return type 3. When using a constructor, the keyword, new, is required new ClassName() (e) What is null? When does it come up / when do we see it produced? (2 points) null is a special value in Java that signifies that a reference is not yet pointing to an object. It is the default value for data fields that are reference types.

2. Short answer questions #2 (10 points) (a) Describe the rules governing what you can do within a static method specifically, its access to instance or static variables, and the ability to call instance or static methods. Briefly describe why. (2 points) A static method can only access static variables and invoke static methods. This is because static methods do not have to be called on instance. Consequently, instance methods and instance variables cannot be used by a static method (it cannot be guaranteed that an object exists that those instance methods and variables can be called / accessed from) (b) Which is faster, binary search or linear search? Why...and under what conditions? Are there any assumptions that are made about the Array being searched? (2 points) Binary search is faster because linear search may have to search the entire Array, while binary search does not rather it eliminates large portions of the Array from having to be searched (for example, the initial step should immediately discard half of the Array). However, binary search assumes that the elements in the Array are already sorted. (c) What's the difference between a class and an object? (2 points) A class is a blueprint for creating objects. It defines what fields and methods an object of the Class's type can have. (A class can also be considered a custom type). An object is a bundling of data and related actions that you can perform with / on that data. It's the actual manifestation or instance of a class. (d) What is the StringBuilder class? How is it different from using a regular String? (2 points) The StringBuilder class is a class that mimics a String object. However, the StringBuilder class is mutable, so operations such as concatenation and removing characters can be achieved without having to create entirely new Strings. (e) What does the keyword, this, signify? When should it be used? (2 points) this refers to the current instance of a class that is the object that the methods was called on. It should be used when there's ambiguity between parameters and data fields. It can be used from one constructor to call another constructor.

3. Read the code in the left column. Write the output of the code in the right column. Compile error, nothing and the actual output are all valid answers. (10 points) Code (syso is short for System.out.println()) // imagine you have a stack of ints that // supports push, pop, peek and empty. What is // the output of the code below? syso(stack.empty()); stack.push(4); stack.push(2); stack.push(12); stack.push(5); syso(stack.peek()); syso(stack.pop()); stack.pop(); stack.pop(); syso(stack.peek()); public class Foo { public static void main(string[] args) { Foo f1 = new Foo(4); Foo f2 = new Foo(); Output (compile error, nothing and actual output are valid) true 5 5 4 4 0 5 5 System.out.println(f1.n); System.out.println(f2.n); f1 = f2; addfive(f1); System.out.println(f1.n); System.out.println(f2.n); public static void addfive(foo f) { f.n += 5; int n; Foo() { public Foo(int n) { this.n = n;

4. Circle the errors below and briefly describe why there are errors. (5 points) Find 5 of the 6 errors in the code below. They can be compile time, run time or logical errors. import java.lang.reflect.array; import java.util.arrays; public class Stacky { private int[] elements; private int size; a public void Stacky(int capacity) { b elements = new double[capacity]; // this controls the size of the stack... so it should // *always* accurately determine where the end of the stack is size = 0; public void push(int x) { if (size >= elements.length) { int[] newelements = new int[size * 2]; for(int i = 0; i < newelements.length; i++) { elements[i] = newelements[i]; c elements = newelements; d elements[size - 1] = x; public int pop() { size += 1; e return elements[size]; f public static int getsize() { return this.size; (a) constructors should not have a return type (b) should be int, not double (c) copy should be from elements into newelements (d) assignment should be to current size, then index should be increased (e) size should be decreased for pop (f) getsize should not be static (because it needs to access an instance variable) 5. True or False: (10 points)

(a) F You must declare a visibility modifier (public, private or protected) before member variables and methods. Without a modifier, you will get a compiler error. (you can leave out the visibility modifier for default visibility) (b) T A static method can be invoked both from the class name as well as from an instance: ClassName.myStaticMethod(); ClassName instance = new ClassName(); instance.mystaticmethod(); (c) F In the following code, the variables greeting1 and greeting2 both have a reference that points to the same copy of "I am a string" in memory. Greeting1 = "I am a string"; Greeting2 = new String("I am a string"); (new creates a new String instance... see letter j; if they were both literals, they would be the same) (d) T In a program that uses Processing, the setup() method is called exactly once, and the draw() method is called repeatedly after the setup method. (e) T Is the output of the code below true or false? String s1 = "abc"; String s2 = "adb"; System.out.println(s1.compareTo(s2) < 0); (f) F If a local int variable in a method is not explicitly initialized within that method, it receives a default value of 0. (g) T Binary search requires an Array to be presorted. (h) F Assuming that the Foo class is defined and contains a public member variable, n, both variables, foo1 and foo2 are instances of the Foo class, and the constructor takes the argument passed in and sets the member variable, n... the code below will print out: // 25 // 12 Foo foo1 = new Foo(12); Foo foo2 = foo1; foo1.n = 25; System.out.println(foo1.n); System.out.println(foo2.n); (i) F If a single constructor is defined in a class, it will have that constructor, as well as the default, no argument constructor available for use. (j) F (new String("hello")) == (new String("hello")) Answer 3 of the last 4 questions (#'s 6 through 9)

(These are longer than what will be on the test!!!) 6. Two Dimensional Arrays (20 points) - Write the following two methods that work on 2D Arrays... (a) // takes 2D array and reverses the order of the elements in the columns // Array passed in (does not return a new Array!) public static void reversecolumnsinplace(int[][] arr) Example: Initial declaration of m Calling method with m m is now... int[][] m = { {1, 2, 3, 4, {2, 3, 4, 5, {3, 4, 5, 6 ; reversecolumnsinplace(m); // m looks like: {3, 4, 5, 6, {2, 3, 4, 5, {1, 2, 3, 4 (b) // give back the row with the largest sum; it's ok to return a reference // rather than a new Array System.out.println(Arrays.toString(getRowWithMaxSum(m))); Example: Initial declaration of m Calling method with m Value returned is int[][] m = { {1, 2, 3, 4, {2, 3, 4, 5, {3, 4, 5, 6 ; getrowwithmaxsum(m); // an Array is // returned {3, 4, 5, 6, public static void reversecolumnsinplace(int[][] arr) { int otherrow = arr.length - 1; for(int row = 0; row < arr.length / 2; row++) { for(int col = 0; col < arr[row].length; col++) { int temp = arr[row][col]; arr[row][col] = arr[otherrow][col]; arr[otherrow][col] = temp; otherrow--; public static int[] getrowwithmaxsum(int[][] arr) { int maxsum = 0; int rowmaxsum = -1; for(int i = 0; i < arr.length; i++) { int sum = 0; for(int j = 0; j < arr[i].length; j++) { sum += arr[i][j]; if (sum > maxsum i == 0) { maxsum = sum; rowmaxsum = i; return arr[rowmaxsum];

7. Sorting Magical Sticks (20 points) (a) Finish the missing implementation of bubble sort method below (b) Create a class MagicalStick, based on the usage of the main method below public class SortMagicalSticks { public static void main(string[] args) { MagicalStick[] magicstuff = new MagicalStick[4]; magicstuff[0] = new MagicalStick(7, "wiggle ears"); magicstuff[1] = new MagicalStick(10, "levitate"); magicstuff[2] = new MagicalStick(8, "turn into panda"); magicstuff[3] = new MagicalStick(9, "lazer beamz"); bubblesort(magicstuff); System.out.println("Sorted by length..."); for(magicalstick s: magicstuff) { System.out.println(s.getLength() + " " + s.getpower()); public static void bubblesort(magicalstick[] sticks) { // implement bubblesort according to the pseudocode below: // keep track of swaps // while no swaps have happened // assume no swaps // for every index, up to second to last // compare element at index with next element to sort by length // if element at index is greater // then swap elements // keep track of the fact that a swap happened // implement that class that would be in MagicalStick.java public static void bubblesort(magicalstick[] sticks) { boolean swapoccurred = true; while(swapoccurred) { swapoccurred = false; for(int i = 0; i < sticks.length - 1; i++) { if(sticks[i].getlength() > sticks[i + 1].getLength()) { MagicalStick temp = sticks[i]; sticks[i] = sticks[i + 1]; sticks[i + 1] = temp; swapoccurred = true; class MagicalStick { private int length; private String power; MagicalStick(int len, String pow) { length = len; power = pow; public String getpower() { return power; public int getlength() { return length;

8. My Very Own String Class (20 points) - Create your own version of a String class called MyString. Implement the following methods and constructors (if necessary, see the unicode character chart on the last page): // the constructor, initializes object with the char[] Array supplied MyString(char[] chars) // returns the character at the specified index public char charat(int index) // give back the number of characters public int length() // return a new MyString object that made from a substring of the original, // starting at the index, begin (inclusive), going up to, but not including // the index, end (exclusive) public MyString substring(int begin, int end) // gives back a new MyString object that is all lowercase (only letters are // affected)... when adding an int to a char, you'll have to cast the result // to char if you're assigning the result to a char variable public MyString tolowercase() //Example Usage char[] c = {'v', 'o', 'w', 'e', 'l'; MyString s = new MyString(c); System.out.println(s.charAt(0)); // v System.out.println(s.length()); // 5 System.out.println(s.substring(1, 4)); // MyString object with 'o' 'w' 'e' public class MyString { private char[] chars; public MyString(char[] chars) { this.chars = new char[chars.length]; System.arraycopy(chars, 0, this.chars, 0, chars.length); public char charat(int index) { return chars[index]; public int length() { return chars.length; public MyString substring(int begin, int end) { char[] sub = new char[end - begin]; int index = 0; for(int i = begin; i < end; i++) { sub[index] = chars[i]; index++; return new MyString(sub); public MyString tolowercase() { char[] lower = new char[chars.length]; for(int i = 0; i < chars.length; i++) { if (chars[i] >= 97 && chars[i] <= 122) { lower[i] = (char) (chars[i] - 32); return new MyString(lower); public char[] getchars() { return chars;

9. Triangle Maker (20 points) (a) Write a program that asks for the coordinates of 3 points, and prints out: i. the perimeter of the resulting triangle (the sum of all sides) ii. whether or not the resulting triangle is isosceles (two sides are equal) iii. example interaction below: Enter point 1 as x,y > 0,0 Enter point 2 as x,y > 4,10 Enter point 3 as x,y > 8,0 The triangle's perimeter is 29.540659228538015 The triangle is isosceles. (b) Requirements i. The input must be in the format x,y (hint: there's a method that helps you extract x and y) ii. Expect that the inputs are integers (hint: Integer.parseInt may come in handy) iii. You must create 3 classes: iv. Triangle - A class that represents a triangle; it should contain 3 Point objects in an Array, and the class should be fully encapsulated (points should not be available by direct data field access)... as well as a couple of methods for finding the perimeter and determining if a triangle is isosceles v. Point - A class that represents a point in a 2d plane; it's ok to make the x and y value accessible directly. A method should exist in this object that calculates distance vi. TriangleMaker - the entry point into your program, it should be responsible for all input and output public class Point { public int x; public int y; Point(int x, int y) { this.x = x; this.y = y; public static double distance(point p1, Point p2) { return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); // continued on next page

public class Triangle { private Point[] points = new Point[3]; public Triangle(Point p1, Point p2, Point p3) { points[0] = p1; points[1] = p2; points[2] = p3; public double getperimeter() { return Point.distance(points[0], points[1]) + Point.distance(points[1], points[2]) + Point.distance(points[2], points[0]); public boolean isisosceles() { double sidea = Point.distance(points[0], points[1]); double sideb = Point.distance(points[1], points[2]); double sidec = Point.distance(points[2], points[0]); System.out.println(sideA); System.out.println(sideB); System.out.println(sideC); if (sidea == sideb sideb == sidec sidec == sidea) { return true; else { return false; import java.util.scanner; public class TriangleMaker { public static void main(string[] args) { Scanner input = new Scanner(System.in); Point[] points = new Point[3]; for(int i = 1; i < 4; i++) { System.out.print("Enter point " + i + " as x,y\n> "); String[] pointparts = input.nextline().split(","); points[i - 1] = new Point(Integer.parseInt(pointParts[0]), Integer.parseInt(pointParts[1])); Triangle t = new Triangle(points[0], points[1], points[2]); System.out.println("The triangle's perimeter is " + t.getperimeter()); System.out.println("The triangle is" + (t.isisosceles()? "" : " not") + " isoceles");

Char Dec Char Dec Char Dec Char Dec ------------------------------------------- (nul) 0 (sp) 32 @ 64 ` 96 (soh) 1! 33 A 65 a 97 (stx) 2 " 34 B 66 b 98 (etx) 3 # 35 C 67 c 99 (eot) 4 $ 36 D 68 d 100 (enq) 5 % 37 E 69 e 101 (ack) 6 & 38 F 70 f 102 (bel) 7 ' 39 G 71 g 103 (bs) 8 ( 40 H 72 h 104 (ht) 9 ) 41 I 73 i 105 (nl) 10 * 42 J 74 j 106 (vt) 11 + 43 K 75 k 107 (np) 12, 44 L 76 l 108 (cr) 13-45 M 77 m 109 (so) 14. 46 N 78 n 110 (si) 15 / 47 O 79 o 111 (dle) 16 0 48 P 80 p 112 (dc1) 17 1 49 Q 81 q 113 (dc2) 18 2 50 R 82 r 114 (dc3) 19 3 51 S 83 s 115 (dc4) 20 4 52 T 84 t 116 (nak) 21 5 53 U 85 u 117 (syn) 22 6 54 V 86 v 118 (etb) 23 7 55 W 87 w 119 (can) 24 8 56 X 88 x 120 (em) 25 9 57 Y 89 y 121 (sub) 26 : 58 Z 90 z 122 (esc) 27 ; 59 [ 91 { 123 (fs) 28 < 60 \ 92 124 (gs) 29 = 61 ] 93 125 (rs) 30 > 62 ^ 94 ~ 126 (us) 31? 63 _ 95 (del)127