This is a closed notes, closed book exam.
String s; create an object of type
String? If yes, what is the string, if no explain.
NO. It creates a reference to an object of type string, it does not create the object. It does NOT reference a null string or an empty string. The reference is null, not the object.
False (sorry about the double negative). Java does use pointers, it just calls them references. There are no pointers to primitive types such as int, and double, and you cannot perform arithmetic on pointers/references. In Java, a reference is either null or points to (references) a legitimate object of the type specified in the reference variable declaration.
// WARNING: This might be considered a trick question by some.
import java.awt.*;
class Quiz1Prob3 {
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(10,20,100,50);
Rectangle r2 = r1;
System.out.println("r1 is now\n" + r1);
fiddle(r1);
System.out.println("r1 is now\n" + r1);
r2.translate(0,5); // move down 5 pixels - r1 and r2 reference the same object
System.out.println("r1 is now\n" + r1);
}
static void fiddle(Rectangle rect)
{
rect = new Rectangle(1,1,1,1);//the object reference by r1 in main
// is unaffected
}
}
To get you started,
the first call to println() produces:
r1 is now java.awt.Rectangle[x=10,y=20,width=100,height=50] r1 is now java.awt.Rectangle[x=10,y=20,width=100,height=50] r1 is now java.awt.Rectangle[x=10,y=25,width=100,height=50]
THERE ARE MORE PROBLEMS ON THE BACK
Each of the remaining problems include a program with a single syntax error. Locate and describe the error, then modify the line or lines so that the syntax error is eliminated using as few character insertions and/or deletions as possible.
class Quiz1Prob4 {
public static void main(String[] args)
{
// Foo foo1 = new Foo();
Foo foo1 = new Foo(0); //there was no constructor with no-args
Foo foo2 = new Foo(10);
System.out.println(foo1.value);
System.out.println(foo2.value);
}
}
class Foo {
// alternatively you could have added a no-arg constructor here
Foo(int x){ value = x; }
int value;
}
class Quiz1Prob5 {
public static void main(String[] args)
{
Foo2 foo = new Foo2();
System.out.println(foo.value);
}
}
class Foo2 {
// private int value;
int value; // either make value not-private or remove the reference to it in main
}
class Quiz1Prob6 {
public static void main(String[] args)
{
int x = 10, y = 20;
double z = 30;
// System.out.println(foo(x,y)); // this call is ambiguous
System.out.println(foo(x,(double)y)); // cast one of the params to double
System.out.println(foo(x,z));
System.out.println(foo(z,x));
}
static double foo(int x, double y)
{
return x*y - x/y;
}
static double foo(double x, int y)
{
return x*y - x/y;
}
}
class Quiz1Prob7 {
public static void main(String[] args)
{
System.out.println(increment()); // can't call non-static method
}
// int increment()
static int increment() // just make this static
{
value = value + 1;
return value;
}
static int value;
}