Beruflich Dokumente
Kultur Dokumente
Page 2 of 4
Part2. Essay: Answer the following questions. (30 marks 40 minutes)
3. (a) What does casting mean in Java? Give a casting example for primitive types.(7 marks for a and b)
(b) When is a cast required?
7 marks
Casting means converting from one type to another. (2 marks)
e.g. double d = 2.1; int x = (int) d; (2 marks)
A cast is required if the type you are assigning (on the right-hand side of = ) occupies a larger space
in memory than the type you are assigning to (on the left-hand of =) (3 marks)
4. (a) What is a constructor in Java? (6 marks for a and b)
(b) What is a default constructor?
6 marks
A constructor is a special type of subroutine called at the creation of an object. Constructors are
used to give an object an initial state when it is created (3 marks)
A default constructor is a special constructor provided by java in the case that we dont write any
constructor. The default constructor has no arguments. (3 marks)
5. Briefly explain the basic steps for creating a stream in Java. (7 marks)
7 marks
Step 1. Open the stream: you need to define some objects here(2 marks)
Step 2. Until there is no more data, keep reading in a read, or writing in a write: You need to use
the methods of the objects defined in step 1 to read the stream. (3 marks)
Step 3. Close the stream(2 marks)
Page 3 of 4
Part 3. Problem solving: Answer the following questions. (55 marks 65 minutes)
(a)
public class Circle {(1 marks)
private double radius; (1 mark)
public Circle() {radius = 1.0;} (2 marks)
public Circle(double r) {radius = r;} (2 marks)
public double getRadius() {return radius;} (2.5 marks)
public double getArea() {return radius*radius*3.14159} (2.5 marks)
}
(b)
public class Cylinder extends Circle {(2 marks)
private double height; (1 mark)
public Cylinder() {height = 1.0;} (2 marks)
public Cylinder(double radius, double h) {(2 marks for the constructor)
super(radius);
height = h;
}
public double getHeight() {return height;} (2 marks)
public double getVolume() {return getArea() * height;} (3 marks)
public String toString() { return "Cylinder: radius=" + getRadius() + ", height=" + getHeight()
+ ", base area=" + getArea() + ", volume=" + getVolume();(4 marks)
Page 4 of 4
}
}
2. Write a Java program that asks the user to enter his/her first name and last name as two separate
inputs, and then concatenates the first name and last name separated by a space. The program
should finally display a greeting message to the concatenated name, e.g. Hi Ahmed Ali. You dont
need to write any import statements. (13 marks)
11 marks for all statements (as distributed below)
+ 2 mark for overall logical flow and structure of the program
Page 5 of 4