Midterm 1 Practice Problems
Solutions will be posted under Other Content on Blackboard as we get closer to the exam.
These problems are not comprehensive, so make sure to review all of the relevant materials.
It is recommended that you write the answers to these by hand so that you have practice for the actual exam.
-
What is the output of the following Java code fragment?
int a = 7; int b = a / 2; double c = a / 2; double d = a / 2.0; String e = "b" + a; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e);
-
What is the output of the following Java program?
public class Problem2 { public static void method1() { System.out.print("X "); } public static void method2() { System.out.print("Y "); } public static void main(String[] args) { for (int i = 0; i < 4; i++) { if (i <= 2) { method1(); } else { method2(); } } } }
-
What is the output of the following?
int i, j; for (i = 0; i <= 4; i += 2) { for (j = 1; j < i; j++) { System.out.println(i + " " + j); } System.out.println(i + j); }
-
What is the output of the following Java program?
public class Problem4 { public static void main(String[] args) { int x = 1; int y = 2; int z = 3; z = mystery(x, z, y); System.out.println(x + " " + y + " " + z); mystery(y, y, x); System.out.println(x + " " + y + " " + z); } public static int mystery(int z, int x, int y) { z--; x = 2*y + z; y = x - 1; System.out.println(x + " " + y + " " + z); return x; } }
-
What is the output of the following code fragment?
int val = 14; if (val < 10 && val <= 20) { System.out.println("bye"); } else if (val != 10) { System.out.println("eek"); if (!(val < 10)) { System.out.println("ack"); } } else if (val >= 10) { System.out.println("bat"); } if (val / 2 == 7) { System.out.println("yak"); }
-
Write a static method named
processNamethat takes as a parameter a string representing a name and does the following:-
If the name is a one-word name (e.g., “Oprah” or “Bono”), the method should return the number of characters in the name.
-
If the name has more than one word (e.g., “Barack Obama” or “Sarah Jessica Parker”), the method should return the number of spaces in the name.
For example:
processName("Oprah")should return5processName("Bono")should return4processName("Barack Obama")should return1processName("Sarah Jessica Parker")should return2
You may assume that multi-word names have one space between each pair of words in the name, and that there are no leading or trailing spaces in the string.
-
-
What is the output of the following Java program?
public class Problem6 { public static void main(String[] args) { int[] x = {5, 6, 7}; int y = 4; mystery(x, y); System.out.println(Arrays.toString(x) + " " + y); } public static void mystery(int[] z, int y) { for (int i = 0; i < z.length; i++) { z[i] += y; } y *= 2; System.out.println(Arrays.toString(z)); } }
-
Write a static method
minGapthat takes an array of integers as a parameter and that returns the minimum gap between adjacent values in the array. The gap between two adjacent values in an array is defined as the second value minus the first value. For example, suppose that you have the following array:int[] values = {1, 3, 7, 2, 12};
The first gap is
2(3-1), the second gap is4(7-3), the third gap is-5(2-7), and the fourth gap is10(12-2).Thus, the call
minGap(values)should return-5, because that is the smallest gap in the array. Note that we are not taking the absolute values of the gaps before we compare them, which is why a gap of -5 is smaller than gaps of 2 or 4.If the method is passed an array with fewer than 2 elements, it should return 0.
-
Consider the following lines of Java code:
int[] a = {5, 4, 3, 2, 1}; int[] b = {5, 4, 3, 2, 1}; int[] c = a; for (int i = 0; i < b.length; i++) { c[i] = b[i]; } b[3] += b.length; a[3]--; System.out.println(a[3] + " " + b[3] + " " + c[3]);
-
Draw a single memory diagram that shows the final result of these lines. Include both the stack and the heap in your diagram. You may assume that these lines are part of the
mainmethod. -
Indicate what will be printed by the final line of code shown above.
-
-
Write a static method
shiftRightthat takes an array of integers and shifts all of the array elements one position to the right, with the original last element wrapping around to become the new first element. For example, consider this array:int[] values = {0, 2, 4, 6, 8, 10};
After calling
shiftRight(values), the contents of thevaluesarray should be{10, 0, 2, 4, 6, 8}. -
Write a method with the header
public static int indexLast(int[] arr1, int[] arr2)
that takes two arrays of integers and that returns the index of the last occurrence of the sequence represented by the first array in the second array, or -1 if the sequence represented by the first array does not appear in the second array. For example, suppose that you have these arrays:
list1: {1, 3, 6} list2: {1, 3, 5, 7, 8, 12, 1, 3, 17, 1, 3, 6, 9, 1, 3, 6}
then the call
indexLast(list1, list2)should return13because the last occurrence of the sequence of values inlist1appears inlist2starting at index 13. You may assume that both arrays have at least one element. -
Write a mutator for the
Rectangleclass from lecture that doubles the width of aRectangleobject. -
What is the output of the following Java code fragment?
Rectangle r1 = new Rectangle(5, 10); Rectangle r2 = new Rectangle(5, 10); Rectangle r3 = r2; System.out.println((r1 == r2) + " " + (r2 == r3));
-
Create a Java class called
Triangle. The class should have:-
two floating-point fields: one for the base of the triangle and one for its height
-
a constructor that takes an initial value for each of the fields
-
accessor and mutator methods for each field
-
a method called
areathat computes and returns the area of the triangle, which should be a floating-point value that is 0.5 times the product of its base and height. -
an appropriate
toString()method. For example, the code:Triangle t = new Triangle(3.0, 4.0); System.out.println(t);
should output:
triangle with base 3.0 and height 4.0
-
an appropriate
equals()method, that can be used to determine if twoTriangleobjects have the same base and same height.
Make sure to employ appropriate encapsulation. Protect the fields from direct access by clients, and make sure that only positive values are assigned to the fields.
-
-
Write a client program for your
Triangleclass. Put it in a class calledTriTester, and give it two methods:-
a static method called
processTriangle()that takes aTriangleobject as a parameter, prints it, and prints its area. For example, the code:Triangle t = new Triangle(3.0, 4.0); TriTester.processTriangle(t);
should output:
triangle with base 3.0 and height 4.0 (area = 6.0)
Take advantage of the methods in the
Triangleobject. -
a
main()method that does the following:-
creates three
Triangleobjects:tri1(with base 3.0 and height 4.0),tri2(with base 6.0 and height 6.0), andtri3(also with base 3.0 and height 4.0) -
uses
processTriangle()to process each of the triangles -
tests whether
tri1andtri2are equal and reports the result -
tests whether
tri1andtri3are equal and reports the result.
-
Here is the desired output of the program:
tri1: triangle with base 3.0 and height 4.0 (area = 6.0) tri2: triangle with base 6.0 and height 6.0 (area = 18.0) tri3: triangle with base 3.0 and height 4.0 (area = 6.0) tri1 and tri2 are not equal tri1 and tri3 are equal
-
-
Write a subclass of
TrianglecalledEquilateralTriangle. Its constructor should take a single parametersiderepresenting the length of a side. However, the new class should not have any new fields. Rather, it should use the attributes that are inherited fromTriangle, and you should initialize those attributes by calling the superclass constructor and passing it the appropriate values. (You should approximate the height of the triangle as 0.866 times the side length.) For example, the following code:EquilateralTriangle tri1 = new EquilateralTriangle(6.0); System.out.println(tri1);
should initially produce the following output:
triangle with base 6.0 and height 5.196
-
Override the appropriate method in
EquilateralTriangleso that this code:EquilateralTriangle tri1 = new EquilateralTriangle(6.0); System.out.println(tri1);
will now produce output that looks like this:
equilateral triangle with side 6.0
Questions 17-19 are based on the following Java classes:
public class A extends B { public void twist() { System.out.println("ho!"); } } public class B { public void twist() { System.out.println("ouch!"); } public void shout() { System.out.println("oh!"); } } public class C extends A { public void gasp() { System.out.println("why?"); } }
-
You create the following objects of the above classes:
A a1 = new A(); B b1 = new B(); C c1 = new C();
(Note: The above constructor calls are fine, because Java gives us a constructor with no parameters when we don’t define our own constructor.)
Explain why each of the following method calls either would or would not compile:
a1.shout() a1.gasp() b1.twist() c1.toString()
-
Given the objects created in the previous problem, what would the output be of the following statements?
c1.twist(); c1.shout();
-
Given the above class definitions, which of the following assignment statements would be allowed, and which would not be allowed?
A a1 = new C(); A a2 = new B(); B b1 = new C(); Object o = new A();
Explain your answers briefly.
-
Recall the
ArrayBagclass from lecture. Give this class an accessor method calledcount()that takes an arbitrary objectitemand returns the number of times thatitemoccurs in theArrayBag. -
Consider the following method:
public static int test(int a, int b) { if (a < b) { return 0; } else { return 1 + test(a-b, b); } }
What is returned by the call
test(15, 4)?How many times is the method called during the execution of
test(15, 4)– including the initial call? -
Trace the following recursive method
mystery. Determine whatmystery(5)will return. Briefly describe in general terms whatmysterydoes.public static int mystery(int a) { if (a == 0) { return 1; } return 2 * mystery(a-1); }
Note: you will not have to write a recursive method for this first midterm, but you will be expected to understand and trace one!
-
When performing operations on matrices, we may want to transpose a matrix. This means to flip a matrix along its diagonal. Some examples:
Matrix A: Matrix A Transposed: 0 1 2 0 3 6 3 4 5 1 4 7 6 7 8 2 5 8 Matrix B: Matrix B Transposed: 0 1 0 2 4 2 3 1 3 5 4 5
Write a static method
transposethat takes a 2D integer array as an input matrix, and returns the transposed matrix. -
You are designing a class that extends
BigIntcalledSignedBigInt. ASignedBigIntcan be a positive or negative value, but otherwise acts the same as aBigInt. Using proper encapsulation, you will need to to write theSignedBigIntclass according to the specifications below:-
one boolean field to indicate whether our SignedBigInt object is positive or not
-
one integer field to count the number of negative SignedBigInt objects that have been created
-
two constructors - one default constructor that sets the SignedBigInt object to be positive, and one that takes in an array of digits and a boolean indicating the sign of the value.
-
accessor methods for each field
-
toString()andmul(SignedBigInt val)methods (Hint: take advantage of inheritance and polymorphism! You may assume that an accessor method for digits called getDigits() has been added to BigInt) -
a method called
sequence(int a, boolean sign)that returns a SignedBigInt of sequential digits withasignificant digits and the corresponding sign. For example:sequence(4, true); //returns SignedBigInt representing 1234 sequence(12, false); // returns SignedBigInt representing -123456789012
-
a client class called MakeSignedBigInt that simulates the following behavior in its main method:
Is your number positive? (y/n) n Enter 5 digits: 1 2 3 4 5 You created a SignedBigInt -12345 Create new SignedBigInt? (y/n) y Is your number positive? (y/n) y Enter 5 digits: 5 4 3 2 1 You created a SignedBigInt 54321 Create new SignedBigInt? (y/n) nYou may assume that the user will always enter valid inputs. You should create a SignedbigInt object in your program.
-