Exam Ni Juan Java
Exam Ni Juan Java
Documentation concerning the methods you may need for the classes Picture, Pixel,
FileChooser, Color, String, and Student is provided at the back of the exam.
Total
1
Part 1: Multiple Choice
Choose the best answer from the choices given. Choose only ONE answer. Each question is
worth 1 mark unless otherwise indicated.
You may assume that there are no syntax errors intended in any of the code provided in the
questions of Part 1, unless the question specifically refers to compilation.
(a) M
(b) a
(c) y
(d) 3
(e) none of the above
2
5. What will be printed when the following code segment is executed?
String s = "May 31";
System.out.println(s.indexOf("13"));
(a) 2
(b) 13
(c) -1
(d) 6
(e) none of the above
(a) Same
(b) Different
(a) Same
(b) Different
3
(a) HoMer
(b) homer
(c) None of the above
4
10. (2 marks) What will be the value of num after the following code segment is executed?
int num = 10;
if (num > 15)
num = num - 10;
num = num - 1;
(a) 15
(b) 10
(c) 9
(d) 0
(e) none of the above
11. (2 marks) What will be the value of num after the following code segment is executed?
int num = 10;
if (num > 10)
num = num - 10;
else
num = num - 1;
(a) 10
(b) 0
(c) 9
(d) -1
(e) none of the above
12. (2 marks) What will be the value of num after the following code segment is executed?
int num = -3;
if (num > 10)
num = num - 10;
else if (num > 0)
num = num - 1;
else
num = 0;
(a) -3
(b) -13
(c) -4
(d) 0
(e) none of the above
5
13. (2 marks) What will be the value of num after the following code segment is executed?
int num = 15;
if (num >= 20)
num = num - 20;
if (num >= 10)
num = num - 10;
if (num >= 5)
num = num - 5;
(a) 0
(b) 5
(c) 10
(d) 15
(e) none of the above
14. (2 marks) What will be the value of num after the following code segment is executed?
int num = 5;
if (num > 10)
if (num < 20)
num = num - 10;
else
num = num - 1;
(a) 4
(b) 5
(c) -5
(d) -6
(e) none of the above
15. (2 marks) What will be output when the following code segment is executed?
for (int k = 2; k < 16; k = k + 4)
System.out.print(k);
(a) 26101416
(b) 261014
(c) 2610
(d) Nothing will be output
(e) None of the above answers
6
16. (2 marks) What will be output when the following code segment is executed?
for (int k = 2; k < 10; k = k * 3)
System.out.print(k);
(a) 2
(b) 26
(c) 2610
(d) 261012
(e) none of the above
7
19. Consider the following code segment:
import java.util.StringTokenizer;
StringTokenizer token = new StringTokenizer("CS 1026b is fun");
System.out.print(token.nextToken() + "/" );
System.out.print(token.nextToken() + "/");
System.out.print(token.nextToken());
8
23. Consider the following code segment:
Picture p = new Picture(100,100);
Pixel[] pixelArray = getPixels();
int index = pixelArray.length;
pixelArray[index].setRed(200);
This code segment will
(a) not compile
(b) compile but will result with a null pointer exception at runtime
(c) compile and run correctly
(d) compile but will result with an array out of bounds exception at runtime
(e) none of the above
24. In a class definition, a public method that returns the value of an attribute is called a
(a) constructor
(b) accessor method
(c) modifier method
(d) main method
(e) none of the above
25. In a class definition, a public method that is allowed to change the value of an attribute
is called a
(a) constructor
(b) accessor method
(c) modifier method
(d) main method
(e) none of the above
26. In a class definition, a public method whose purpose is to initialize the values of
attributes is called a
(a) constructor
(b) accessor method
(c) modifier method
(d) main method
(e) none of the above
27. Suppose we have two methods with the same name defined in a class, with the headers
public void someMethod(int x, int y)
public void someMethod(double x, double y)
This is
(a) illegal, and will cause a compiler error
(b) called overheating
(c) called overloading
(d) called overriding
(e) none of the above
9
10
Consider the following class definition for the next 13 questions. Some of the code has
been omitted. Some lines have been labeled for reference in the questions that follow.
28. The import statement at the line labeled /*1*/ allows class Mnop to use
(a) all classes in the package java.awt
(b) all classes in the textbook’s bookclasses folder
(c) all classes in the package java.io
(d) more than one of the above
(e) none of the above answers
11
29. The identifier Mnop in the line labeled /*2*/ is the name of a
(a) class
(b) object
(c) object method
(d) constructor
(e) none of the above
33. The identifier Mnop in the line labeled /*6*/ is the name of a
(a) class
(b) object
(c) object method
(d) constructor
(e) none of the above
34. The identifiers aNumber and aMessage in the line labeled /*6* / are
(a) actual parameters
(b) formal parameters
(c) attributes
(d) both (a) and (c)
(e) both (b) and (c)
12
35. The identifiers s and t in the line labeled /*7*/ are
(a) actual parameters
(b) formal parameters
(c) attributes
(d) local variables
(e) none of the above
39. Which of the following methods can not be invoked on an object of the class Mnop?
(a) abcd
(b) efgh
(c) main
(d) exactly two of the above
(e) none of the above answers
40. When the missing code for the methods in the class has been filled in, the body of which
methods will need to contain a return statement in order to compile?
(a) abcd
(b) efgh
(c) ijkl
(d) exactly two of the above
(e) none of the above answers
.
13
41. (2 marks) Consider the following method defined in some class:
public boolean what( int [] arr) {
for (int i= 0; i < arr.length; i ++)
{
if (arr[i] < 0)
return false;
}
return true;
}
What does this method do?
(a) it initializes each element of the array arr to 0
(b) it returns true if each element of arr is positive
(c) it returns true if at least one element of arr is negative
(d) it always returns false
(e) none of the above
14
44. Which of the following is/are stored as text files?
(a) a .java file
(b) a .jpg file
(c) both (a) and (b)
(d) none of the above answers
int n = 3;
(a) *
**
***
(b) ***
**
*
(c) ***
***
***
(d) *
*
*
15
47. (2 marks) Consider the following code segment:
16
Part 2: Write your answers in the spaces provided in each question.
1. [5 marks]
a) What will be output by the following code segment?
Answer:
0
1
2
3
4
5
Answer:
17
2. [3 marks] In the following program, the user is prompted to enter a number between 0 and
100 inclusive. If the number entered is not in the correct range, the program asks the user to
enter the number again. Fill in the blanks so that the program works as described.
while (cont)
{
num = SimpleInput.getIntNumber("Enter number between 0 and 100: ");
3. [7 marks] Consider the incomplete Java program below that is intended to read 10 integers
from the keyboard using SimpleInput.getIntNumber for each, store them in an
array of size 10, and then print them in reverse order. Fill in the blanks so that the program
functions as described.
public class GetAndReverseNumbers
{
public static void main(String [] args)
{
int [] intArr = new int [10];
18
4. [11 marks] Write a complete Java program that reads 10 filenames of .jpg files from the
keyboard using SimpleInput.getString for each, creates a Picture object from each
image, stores them in an array of Picture objects, and then displays the pictures in reverse
order. The class has been started for you. You must use at least one for loop in your
implementation. (Hint: see Question 3 for help with your program structure.)
19
5. [ 12 marks]
a) You have been provided below with incomplete code for a method
countBlackPixels that returns the number of black pixels in the Picture object on
which it is invoked. Complete the method by filling in the blank spaces.
int counter = 0;
if (pixelObj.getColor() == java.color.BLACK)
counter ++;
}
}
return counter;
b) Now write a method in the space below, that returns the number of pixels that are not black
in the Picture object on which it is invoked. You must invoke the method
countBlackPixels of part a) in your implementation. (Hint: the number of non-black
pixels is the total number of pixels minus the number of black pixels)
int counter = 0;
return counter;
}
20
6. [11 marks]
a) Write a new method for the Picture class that compares the size of two pictures. The
method will be called equalPictureSize and will take one parameter that is a
Picture object. It will be invoked on a Picture object. If this picture has the same width
and height as the parameter picture, the method returns true, otherwise it returns
false.
return false;
}
b) Complete the Java code segment below so that if the pictures referenced by pic1 and
pic2 are not the same size, it will print an appropriate error message. Your code must
invoke the method equalPictureSize of part a)
if (pic2.equalPictureSize(pic1)== false)
System.out.println(“Error”);
21
7. [8 marks] Recall that we had a method for the Picture class that did vertical mirroring from
left to right:
22
b) We have started a test program TestMirroring for you below. Add code to the main
method so that it displays the original picture mirrored from left to right, and then the original
picture mirrored from right to left.
public class TestMirroring {
public static void main(String[] args) {
String fileName = FileChooser.pickAFile() ;
Picture pic = new Picture(fileName);
/* add your code here */
pic.show();
pic.verticalMirror();
pic.show();
8. [21 marks] The following is the start of a definition for a class Course that models a
university course. You may assume that the class Student already exists, defined as in our
lecture notes, with the methods listed in the handout at the back of the exam.
a) The following is the body of another constructor for the Course class. Fill in the
constructor’s header in the appropriate place below:
23
// another constructor for Course
/ * Fill in the header for the constructor here */
public Course (String course, String instructor)
{ this.courseName = course;
this.instructorName = instructor;
this.studentArray = new Student[MAX_STUDENTS];
}
24
b) Write an accessor (getter) method for the courseName attribute.
d) Write a method printStudents that prints a list of the names of all the students in the
course. Note that the length of the array referenced by studentArray is always
MAX_STUDENTS, but there will be some null entries in the array if there are fewer
than MAX_STUDENTS in the course.
25
Page for Rough Work
26
Java API Documentation for CS026b Final Exam
java.awt.Color
Partial Constructor Summary
Color(int r, int g, int b)
Constructor creates a Color object with red, green and blue intensities of r, g and b respectively
Partial Method Summary
Color brighter()
Create a new Color object that’s a brighter version of this Color
Color darker()
Create a new Color object that’s a darker version of this Color
int getBlue()
Return the blue intensity of this Color object
int getGreen()
Return the green intensity of this Color object
int getRed()
Return the red intensity of this Color object
String toString()
Return a string representation of this Color object
Partial Constant Summary for the Color Class
BLACK, black -- A Color object with red, green and blue intensities of 0
BLUE, blue -- A Color object with blue intensity 255, and red and green intensities of 0
GREEN, green -- A Color object with green intensity 255, and red and blue intensities of 0
RED, red -- A Color object with red intensity 255, and green and blue intensities of 0
WHITE, white -- A Color object with red, green and blue intensities of 255
FileChooser
Partial Method Summary
static String getMediaPath(String s)
Get the full path name for the file specified in s
static String pickAFile()
Let the user choose a file, and return the full file name (path included)
Picture
Constructor Summary
Picture()
Constructor that takes no arguments
Picture(int width, int height)
Constructor that takes the width and height
Picture(Picture copyPicture)
Constructor that takes a picture and creates a copy of that picture
Picture(.String fileName)
Constructor that takes a file name and creates the picture
Partial Method Summary
void copyPicture(SimplePicture sourcePicture)
Method to copy the sourcePicture object into the current picture
int getHeight()
Method to get the height of the picture in pixels
Pixel getPixel(int x, int y)
Method to get a pixel object for the given x and y location
Pixel[] getPixels()
Method to get a one-dimensional array of Pixels for this simple picture
int getWidth()
Method to get the width of the picture in pixels
27
void repaint()
Method to force the picture to redraw itself.
void show()
Method to show the picture in a picture frame
void write(String fileName)
Store the picture in .jpg format in the file whose name is specified by fileName
Pixel
Partial Method Summary
double colorDistance(Color c)
Method to get the color distance between the color of this pixel and the Color argument.
double getAverage()
Method to return the average of the color intensities in this pixel.
int getBlue()
Method to get the amount of blue at this pixel.
java.awt.Color getColor()
Method to get a color object that represents the color at this pixel.
int getGreen()
Method to get the amount of green at this pixel.
int getRed()
Method to get the amount of red at this pixel.
int getX()
Method to get the x location of this pixel.
int getY()
Method to get the y location of this pixel.
void setBlue(int value)
Method to set the blue to a new blue value
void setColor(java.awt.Color newColor)
Method to set the pixel color to the passed in color object.
void setGreen(int value)
Method to set the green to a new green value
void setRed(int value)
Method to set the red to a new red value
String toString()
Method to return a string description of this pixel
String
Partial Constructor Summary
String()
Initialize a newly-created string object to the empty character sequence
String(char[] value)
Initialize a new String object that contains the characters from the array parameter
String(String original)
Initialize a new string object so that it contains a copy of the String original
Partial Method Summary
char charAt(int index)
Return the character at position index in the string. (First char is at index 0.)
int compareTo(String anotherString)
Compares this string to anotherString lexicographically (according to the Unicode collating sequence; returns
a negative number if “this” is less than “anotherString; returns a value greater than 0 if “this” is greater than
“anotherString”; returns 0 if the strings are the same.
boolean endsWith(String suffix)
Returns true if this string ends with the string in suffix; returns false otherwise.
boolean equals(Object obj)
Compares this string to another object; returns true if they’re the same, and false otherwise.
int indexOf(char ch)
Returns the position of the first occurrence of character ch in this string; returns –1 if ch is not found.
28
int indexOf(char ch, int fromIndex)
Returns the position of the first occurrence of the character ch in this string, starting the search at the specified
index; returns –1 if ch is not found.
int indexOf(String str)
Returns the position of the first occurrence of String str in this string; returns –1 if str is not found.
int indexOf(String str, int fromIndex)
Returns the position of the first occurrence of the String str in this string, starting the search at the specified
index; returns –1 if str is not found.
int length()
Returns the number of characters in this string.
boolean startsWith(String prefix)
Returns true if this string begins with the String specified in prefix; returns false otherwise.
String substring(int startIndex)
Returns a new String that is a substring of this string, beginning at position startIndex in this string, and
continuing to the end of this string.
String substring(int startIndex, int endIndex)
Returns a new String that is a substring of this string, beginning at position startIndex in this string, and ending
at position (endIndex-1).
String toLowerCase()
Returns a copy of this string in which all upper case letters have been converted to their lower-case
equivalents.
String toString()
Returns a string copy of this string.
String toUpperCase()
Returns a copy of this string in which all lower case letters have been converted to their upper-case
equivalents.
Student
Constructors
Student(String theName)
Student(String theName, double[] grades)
Partial Method Summary
String getName()
Returns the student name
double[] getGrades()
double getGrade(int index)
boolean setName(String name)
boolean setGrade(int index, double newGrade)
boolean setGradeArray(double[] newArray)
void changeGrades(double [] newGradeArray)
double getAverage()
String toString()
Returns a string description of the student name and grades
SimpleInput
Partial Method Summary
static double getNumber(String message)
Returns the number input from the user as a double; message is displayed to the user in the dialogue
static int getIntNumber(String message)
Returns the number input from the user as an int; message is displayed to the user in the dialogue
static String getString(String message)
Returns the string input from the user; message is displayed to the user in the dialogue
29