SAMPLE  JAVA   EXAM        QUESTIONS

Question 1: Write a complete subroutine that finds the largest value in an array of ints. The subroutine should have one parameter, which is an array of type int[]. The largest number in the array should be returned as the value of the subroutine.

Answer:

          public static int getMax(int[] list) {
          
                // Find and return the largest item in the array, list.
             
             int max = list[0];  // This is the largest item seen so far.
             
             for (int i = 1; i < list.length; i++) {
                   // Look at each item in the array.  If the item is
                   // bigger than max, then set max equal to the item.
                 if (list[i] > max)
                    max = list[i];
             }
             
             // At this point, max is the largest item in the whole array.
             
             return max;
             
          } // end subroutine getMax

 

Question 2: Suppose that the following class is being used to store data about some lakes:

          class LakeData {
             String name;    // The name of the lake.
             double volume;  // Cubic miles of water in the lake.
             int depth;      // Maximum depth, in feet.
          }

Suppose that data about 50 lakes has already been stored in the array

             LakeData[] lakes = new LakeData[50];

(a) Write a code segment that will print the name of every lake in the array that has a depth of 100 feet or greater.

(b) Write a code segment that will compute and print the total volume of the water in all 50 lakes.

Answer:

   (a)       System.out.println("Lakes with depth of 100 feet or more are:");
             for (int i = 0; i < 50; i++) {
                if (lakes[i].depth >= 100)
                   System.out.println(lakes[i].name);
             }
             
             
   (b)       double total;  // Amount of water in lakes.
             for (int i = 0; i < 50; i++)
                total += lakes[i].volume;
             System.out.println("The total volume is " + total);
            

Question 3: Suppose that a class, Employee, is defined as follows:

                class Employee {
                   String lastName;
                   String firstName;
                   double hourlyWage;
                   int yearsWithCompany;
                }

Suppose that data about 100 employees is already stored in an array:

                Employee[] employeeData = new Employee[100];

Write a code segment that will output the first name, last name, and hourly wage of each employee who has been with the company for more than 20 years. (Assume that there is a console variable to use for output.)

Answer: (The data for the i-th employee is stored in an object that can be referred to as employeeData[i]. The four pieces of data about that employee are members of this object and can be referred to as:

The code segment uses a for loop to consider each employee in the array.)

        for (int i=0; i < 100; i++) {
            if ( employeeData[i].yearsWithCompany > 20 )
                console.putln(employeeData[i].firstName + " " +
                              employeeData[i].lastName + ": " +
                              employeeData[i].hourlyWage);
        }

Question 4: A checkers board is an 8-by-8 grid of squares that contains empty spaces, red pieces, and black pieces. (For this problem, ignore the possibility of "kings.") Assume that the contents of a checkers board are stored in an array

                    int[][] board = new int[8][8];

The value of board[row][col] represents the square in row number row and column number col. A value of 1 represents a red piece and a value of 2 represents a black piece. An empty square is represented by a value of zero.

Write a code segment that will determine whether the board contains more red pieces, more black pieces, or the same number of red pieces and black pieces. You can print out your answer on a console.

Answer:

        int redCount = 0;   // number of red pieces
        int blackCount = 0; // number of black pieces

        for (int row = 0; row < 8; row++)
           for (int col = 0; col < 8; col++) {
              if (board[row][col] == 1)
                 redCount++;
              else if (board[row][col] == 2)
                 blackCount++;
           }

        if (redCount > blackCount)
            console.putln("There are more red pieces.");
        else if (redCount < blackCount)
            console.putln("There are more black pieces.");
        else
            console.putln("The numbers of red and black pieces are equal.");

Question 5: Write a for statement that will compute the sum of the first 100 integers, that is, 1*1 + 2*2 + 3*3 + ... + 100*100. You should not write a complete program, but you should declare any variables that you use.

Answer:

            int sum = 0;  // the sum of all the squares
            for (int N = 1; N <= 0; N++)
               sum += N*N;

Question 6: Write  a subroutine(method) for the Pythagorean Theorem

Answer: Parameters are used for communication between a subroutine and the rest of the program. A parameter provides a value to be used in the computation performed by the subroutine. There are two types of parameters: formal parameters, which are names used in the definitions of subroutines, and actual parameters, which are the values provided when the subroutine is called. For example, in the subroutine definition

            static double pythagorus(double x, double y) {
                return Math.sqrt(x*x + y*y);
             }

x and y are formal parameters. When the subroutine is called in the statement:

            hypotenuse = pythagorus(opp,adj);


Question 7: Show the exact output that would be produce when the following program is executed. (If you explain your reasoning, you might get more partial credit for an incorrect answer.)

              public class TestQuestion {
                 public static void main(String[] args) {
                    int x, y;
                    x = 1;
                    y = 1;
                    while (y < 16) {
                       y = 2*y;
                       x = x + y;
                       System.out.println("x = " + x + " and y = " y);
                    } // end while
                 } // end main
              } // end class TestQuestion

Answer: The table on the left shows the values that the variables y and x take on as the program is executed. The output from the program is shown on the right.

       y   |   x         OUTPUT:
    -------|-------      -------------------------------
       1   |   1
       2   |   3             x = 3 and y = 2
       4   |   7             x = 7 and y = 4
       8   |  15             x = 15 and y = 8
      16   |  31             x = 31 and y = 16

Question 8: Fill in the following subroutine so that it counts the number of times that the character ch occurs in the string str. That is, you want to count the number of values of i such that str.charAt(i) == ch. The answer should be returned as the value of the subroutine.

        public static int countCharInString(String str, char ch) {
          .
          .
          .
        }

Answer:

        public static int countCharInString(String str, char ch) {
           int count = 0;
           for (int i = 0; i < str.length(); i++) {
              if (str.charAt(i) == ch)
                 count++;
           }
           return count;
        }

Question 9: Suppose that g is an object of type Graphics. Recall that g.drawRect(x,y,w,h) will draw a rectangle with its upper left corner at the point (x,y). The width of the rectangle is w and the height is h. Write a loop that will draw 10 small squares in a line, like this:

line of 10 squares

Use the g.drawRect method to draw the squares. Assume that the first square has its upper left corner at (0,0). Each square is 15 pixels by 15 pixels, and there are 15 pixels between the squares. You can use a for loop or a while loop.

Answer:Here are three possible answers, two using for loops and one using a while loop.

         1)  The first version counts off ten squares.  The variable x
             keeps track of the left edge of the square.  After each square
             is drawn, x is incremented by 30.  (That's allowing 15 pixels 
             for the square and 15 pixels between the squares.)
             
                int x = 0;
                for (int count = 0; count < 10; count++) {
                   g.drawRect(x,0,15,15);
                   x = x + 30;
                }
                
                
         2)  In the second version, x is used as the for loop
             variable.  Since there are 10 squares, we can calculate that
             the last value of x is 270.
             
                for (int x = 0; x <= 270; x = x + 30) {
                   g.drawRect(x,0,15,15);
                }
                   
                   
         3)  The third version is similar to the second, except that
             a while loop is used.
             
                int x = 0;
                while (x < 300) {
                   g.drawRect(x,0,15,15);
                   x = x + 30;
                }

Question 10: Suppose that the price of admission to a museum depends on the customer's age. Children 12 years old or younger pay $2.00. Senior citizens aged 62 or over pay $3.00. General admission for everyone else is $5.00. Write a program segment that will ask the user to enter his or her age, and then print a message stating the user's price of admission. Use an if statement. You don't have to write a complete program, but you should declare any variables that you use.

Answer: I use TextIO.put() in my answer, but you could use System.out.print() instead.

              int age; // the customer's age
              
              TextIO.put("What is your age? ");
              age = TextIO.getlnInt();
              
              if (age <= 12) {
                 TextIO.putln("Your admission price is $2.00");
              }
              else if (age >= 62) {
                 TextIO.putln("Your admission price is $3.00");
              }
              else {
                 TextIO.putln("Your admission price is $5.00");
              }

question: create a class for a circle which has three object data x,y and r. It has two methods circumference and circle. Implement as well.

 

public class Circle {
    public double x, y;   // The coordinates of the center
    public double r;      // The radius
    // Methods that return the circumference and area of the circle
    public double circumference() { return 2 * 3.14159 * r; }
    public double area() { return 3.14159 * r*r; }
}

or 

public class Circle1 {
    public double x, y;   // The coordinates of the center
    public double r;      // The radius
    // Methods that return the circumference and area of the circle
    

     public circle(double xpos, double ypos, double rad)

    {   x = xpos;

         y = ypos;

         r = rad;

    }

    public double circumference() { return 2 * 3.14159 * r; }
    public double area() { return 3.14159 * r*r; }
}

Accessing Object Data

Now that we've created an object, we can use its data fields. The syntax should be familiar to C programmers:

 

Circle c = new Circle();
c.x = 2.0;  // Initialize our circle to have center (2, 2) and radius 1.0.
c.y = 2.0;
c.r = 1.0;

Circle1 d = new Circle1(3,4,23.5);

Using Object Methods

This is where things get interesting! To access the methods of an object, we use the same syntax as accessing the data of an object:

 

Circle c = new Circle();
double a;
c.r = 2.5;
a = c.area();
or a = d.area();

  

QUESTION 11

Assume that a Fraction class has been defined as follows:

class Fraction {
private int numerator;
private int denominator;
public Fraction (int a, int b) {
numerator = a;
denominator = b;
reduce();
}

// Returns this fraction's numerator
public int getNumerator () {
return numerator;
}

// Returns this fraction's denominator;
public int getDenominator () {
return denominator;
}

// Prints this fraction.
public void print () {
System.out.println(numerator + "/" + denominator);
}

// Reduces this Fraction to its simplest form.
// For example, 6/8 would be reduced to 3/4.
public void reduce () {
// Details omitted (but you do not have to complete this method).
}

// Returns true if this Fraction equals otherFrac, and false otherwise.
public boolean equals (Fraction otherFrac) {
// Must first reduce both myself and fraction otherFrac.
reduce();
otherFrac.reduce();
// Now see if we're equal.
if (numerator == otherFrac.getNumerator() &&
denominator == otherFrac.getDenominator())
return true;
else
return false;
}

// Divides this fraction in half.
public void halve () {
denominator = denominator * 2;
reduce();
}
}

(a) What variables does the method reduce have to examine and 
possibly change?


(b) How can the equals method compare two Fractions for equality 
when it only has one Fraction parameter?

(c) For each code fragment below, circle the right answer to 
indicate whether it will run successfully or produce an error message. 
If it runs successfully, state what the output will be. If it produces 
an error message, explain the problem (but do not simply give the 
contents of the error message).

Fraction f1 = new Fraction(3, 5);
Fraction f2 = new Fraction(3, 5);
Fraction f3 = f1;
if (f1 == f2)
System.out.println("alpha");
if (f1 == f3)
System.out.println("beta");
if (f1.equals(f2))
System.out.println("gamma");
if (f1.equals(f3))
System.out.println("delta");

Runs successfully

Produces an error message

Fraction[] list;
list = new Fraction[15];
System.out.print("The numerators are: ");
for (int i=0; i<15; i++)
System.out.print(list[i].getNumerator());

Runs successfully

Produces an error message

Fraction apple = new Fraction (1, 2);
Fraction peach = new Fraction (4, 5);
Fraction pear = apple;
peach.halve();
pear.halve();
apple.print();
peach.print();
pear.print();

Runs successfully

Produces an error message