Docsity

Quiz 6 with Solution - Java Programming | COP 2250, Quizzes of Javascript programming

Toggle sidebar
bg1
Quiz 6
Name: Panther ID:
Please use 10 minutes to finish this quiz.
1. Consider the following two classes: Test and TestDriver
public class Test {
private int i;
private static int j = 0;
public Test()
{
i += 2;
j += 3;
}
public String toString()
{
return (“i: ” + i + “ j: ” + j);
}
}
class TestDriver{
public static void main(String[]args)
{
System.out.println(new Test());
System.out.println((new Test()).toString());
System.out.println((new Test()).toString());
System.out.println(new Test());
}
}
[4 pts] What is the output produced by the program?
i: 2 j: 3
i: 4 j: 6
i: 6 j: 9
i: 8 j: 12
[2 pts] Will the output be different if these four lines are arranged to different order?
Why?
NO. Because when object is passed as parameter of print(ln), it will automatically be
converted to object.toString().
pf2

Partial preview of the text

Download Quiz 6 with Solution - Java Programming | COP 2250 and more Quizzes Javascript programming in PDF only on Docsity!

Quiz 6

Name: Panther ID:

Please use 10 minutes to finish this quiz.

1. Consider the following two classes: Test and TestDriver

public class Test { private int i; private static int j = 0; public Test() { i += 2; j += 3; } public String toString() { return (“i: ” + i + “ j: ” + j); } } class TestDriver{ public static void main(String[]args) { System.out.println(new Test()); System.out.println((new Test()).toString()); System.out.println((new Test()).toString()); System.out.println(new Test()); } }

[4 pts] What is the output produced by the program?

i: 2 j: 3

i: 4 j: 6

i: 6 j: 9

i: 8 j: 12

[2 pts] Will the output be different if these four lines are arranged to different order?

Why?

NO. Because when object is passed as parameter of print(ln), it will automatically be

converted to object.toString().

2. String and Integer classes both implements Comparable interface which contains only

one abstract method, compareTo. Consider the following program.

public class Test { public static void main(String[]args) { String s1 = “3456”; String s2 = “13456”; if(s1.compareTo(s2) > 0 ) System.out.println(“s1 is larger than s2”); else System.out.println(“s1 is less than s2”); if(new Integer(s1).compareTo(new Integer(s2)) >

System.out.println(“Integer s1 is larger than Integer s2”); else System.out.println(“Integer s1 is less than Integer s2”); } }

[4 pts] What is the output produced by the program? Explain.

s1 is larger than s Integer s1 is less than Integer s

For String’s compareTo method, it will compare based on lexicographic order, while for

Integer’s compareTo method, it will compare based on the integer value.

Bonus

[5 pts] Explain why a static method cannot refer to an instance variable.

Because instance variable could only be available until an object gets instantiated while

static method could be called through the class directly.