본문 바로가기
자바(Java)/자바 AP

[자바AP연습문제]02.Using Objects

by 긱펀 2024. 3. 21.
반응형

[자바AP연습문제]02.Using Objects

 

* 2.Using Objects Summary를 복습하려면 아래의 "더보기" 클릭

더보기

In this unit, you learned to use objects (variables of a class type) that have been written for you in Java. You learned to use constructors and methods with and without parameters of objects, and built-in Java classes like String, Integer, Double, and Math.

  • class - defines a new data type. It is the formal implementation, or blueprint, of the attributes and behaviors of the objects of that class.
  • object - a specific instance of a class with defined attributes. Objects are declared as variables of a class type.
  • constructors - code that is used to create new objects and initialize the object’s attributes.
  • new - keyword used to create objects with a call to one of the class’s constructors.
  • instance variables - define the attributes for objects.
  • methods - define the behaviors or functions for objects.
  • dot (.) operator - used to access an object’s methods.
  • parameters (arguments) - the values or data passed to an object’s method inside the parentheses in the method call to help the method do its job.
  • return values - values returned by methods to the calling method.
  • immutable - String methods do not change the String object. Any method that seems to change a string actually creates a new string.
  • wrapper classes - classes that create objects from primitive types, for example the Integer class and Double class.
  • null is used to indicate that an object reference doesn’t refer to any object yet.

 

*The following String methods and constructors, including what they do and when they are used, are part of the Java Quick Reference in the AP exam:

  • String(String str) : Constructs a new String object that represents the same sequence of characters as str.
  • int length() : returns the number of characters in a String object.
  • String substring(int from, int to) : returns the substring beginning at index from and ending at index (to -1). The single element substring at position index can be created by calling substring(index, index + 1).
  • String substring(int from) : returns substring(from, length()).
  • int indexOf(String str) : returns the index of the first occurrence of str; returns -1 if not found.
  • boolean equals(String other) : returns true if this (the calling object) is equal to other; returns false otherwise.
  • int compareTo(String other) : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other.

 

*The following Integer methods and constructors, including what they do and when they are used, are part of the Java Quick Reference.

 

  • Integer(value): Constructs a new Integer object that represents the specified int value.
  • Integer.MIN_VALUE : The minimum value represented by an int or Integer.
  • Integer.MAX_VALUE : The maximum value represented by an int or Integer.
  • int intValue() : Returns the value of this Integer as an int.

 

*The following Double methods and constructors, including what they do and when they are used, are part of the Java Quick Reference Guide given during the exam:

  • Double(double value) : Constructs a new Double object that represents the specified double value.
  • double doubleValue() : Returns the value of this Double as a double.

 


*The following static Math methods are part of the Java Quick Reference:

  • int abs(int) : Returns the absolute value of an int value (which means no negatives).
  • double abs(double) : Returns the absolute value of a double value.
  • double pow(double, double) : Returns the value of the first parameter raised to the power of the second parameter.
  • double sqrt(double) : Returns the positive square root of a double value.
  • double random() : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!).

(int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. The range is the (max number - min number + 1). For example, to get a number in the range of 5 to 10, use the range 10-5+1 = 6 and the min number 5: (int)(Math.random()*6) + 5).


 

[문제1]

 

[문제2]

 

 

 

[문제3]

Consider the following class. Which of the following successfully creates a new Cat object?

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Cat {
    private String color;
    private String breed;
    private boolean isHungry;
 
    public Cat()
    {
        color = "unknown";
        breed = "unknown";
        isHungry = false;
    }
 
    public Cat(String c, String b, boolean h)
    {
        color = c;
        breed = b;
        isHungry = h;
    }
}
 
public class Main {
  public static void main(String[] args) {
    I.   Cat a = new Cat();
    II.  Cat b = new Cat("Shorthair"true);
    III. String color = "orange";
         boolean hungry = false;
         Cat c = new Cat(color, "Tabby", hungry);
  }
}
cs

 

 

[문제4]

Consider the following class. Which of the following code segments will construct a Movie object m with a title of “Lion King” and rating of 8.0?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Movie {
    private String title;
    private String director;
    private double rating;
    private boolean inTheaters;
 
    public Movie(String t, String d, double r)
    {
        title = t;
        director = d;
        rating = r;
        inTheaters = false;
    }
 
    public Movie(String t)
    {
        title = t;
        director = "unknown";
        rating = 0.0;
        inTheaters = false;
    }
}
 
public class Main {
  public static void main(String[] args) {
    A. Movie m = new Movie(8.0"Lion King");
    B. Movie m = Movie("Lion King"8.0);
    C. Movie m = new Movie();
    D. Movie m = new Movie("Lion King""Disney"8.0);
    E. Movie m = new Movie("Lion King");
  }
}
cs

 

 

[문제5]

A. An attribute of breed is String.
B. color, breed, and age are instances of the Cat class.
C. Cat is an instance of the myCat class.
D. age is an attribute of the myCat object.
E. An attribute of Cat is myCat.

 

 

[문제6]

Which of the following code segments will correctly create an instance of a Person object?

1
2
3
4
5
6
7
8
9
10
11
public class Person
{
    private String name;
    private int age;
 
    public Person(String a, int b)
    {
        name = a;
        age = b;
    }
}
cs

 

A. new Person john = Person("John", 16);

B. Person john("John", 16);

C. Person john = ("John", 16);

D. Person john = new Person("John", 16);

E. Person john = new Person(16, "John");

 

 

[문제7]

What is the value of len after the following executes?

1
2
String s1 = "Hey, buddy!";
int len = s1.length();
cs

 

A. 8

B. 10

C. 11

D. 12

E. 13

 

 

[문제8]

What is the value of pos after the following code executes?

1
2
String s1 = "ac ded ca";
int pos = s1.indexOf("d");
cs

 

A. 3

B. 4

C. 5

D. -1

E. 1

 

 

[문제9] What is the value of s1 after the following code executes?

1
2
3
String s1 = "Hey";
String s2 = s1.substring(0,1);
String s3 = s2.toLowerCase();
cs

 

A. Hey

B. he

C. H

D. h

 

 

[문제10]

Consider the following class. Which of the following code segments would successfully create a new Movie object?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Movie
{
    private String title;
    private String director;
    private double rating;
    private boolean inTheaters;
 
    public Movie(String t, String d, double r)
    {
        title = t;
        director = d;
        rating = r;
        inTheaters = false;
    }
 
    public Movie(String t)
    {
        title = t;
        director = "unknown";
        rating = 0.0;
        inTheaters = false;
    }
}
cs

 

A. Movie one = new Movie("Harry Potter", "Bob");

B. Movie two = new Movie("Sponge Bob");

C. Movie three = new Movie(title, rating, director);

D. Movie four = new Movie("My Cool Movie", "Steven Spielburg", "4.4");

E. Movie five = new Movie(t);

 

 

[문제11]

Given the BankAccount class definition below, what is the output of the code in the main method?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class BankAccount
{
    private int accountID;
    private double total;
 
    public BankAccount(int id, double initialDeposit)
    {
        accountID = id;
        total = initialDeposit;
    }
 
    public void deposit(double money)
    {
        total = total + money;
    }
 
    public void withdraw(double money)
    {
        total = total - money;
    }
 
    public void printCurrentTotal()
    {
        System.out.print(total);
    }
 
    public static void main(String[] args)
    {
        BankAccount newAccount = new BankAccount(12345100.00);
        newAccount.withdraw(30.00);
        newAccount.deposit(40.00);
        newAccount.printCurrentTotal();
    }
}
cs

 

A. 100.00

B. 110.00

C. 90.00

D. 10.00

 

 

[문제12]

Given the following code segment, what is the value of num when it finishes executing?

Math.random() returns a random decimal number between 0 and up to 1 (0 =< n < 1), for example 0.4.

1
2
double value = Math.random();
int num = (int) (value * 5+ 5;
cs

 

A. a random number from 0 to 4

B. a random number from 1 to 5

C. a random number from 5 to 9

D. a random number from 5 to 10

 

 

[문제13]

Given the following code segment, what is the value of num when it finishes executing? Math.random() returns a random decimal number between 0 and up to 1, for example 0.4.

1
2
double value = Math.random();
int num = (int) (value * 11- 5;
cs

 

A. a random number from 0 to 10

B. a random number from 0 to 9

C. a random number from -5 to 4

D. a random number from -5 to 5

 

 

[문제14]

After the following code is executed, which of I, II and/or III will evaluate to true?

1
2
3
4
5
6
7
String s1 = "xyz";
String s2 = s1;
String s3 = s2;
 
I.   s1.equals(s3)
II.  s1 == s2
III. s1 == s3
cs

 

A. I, II, III

B. I only

C. II only

D. III only

E. II and III only

 

 

[문제15]

What is output from the following code?

1
2
3
4
5
String s = "Georgia Tech";
String s1 = s.substring(0,7);
String s2 = s1.substring(2);
String s3 = s2.substring(0,3);
System.out.println(s3);
cs

 

A. org

B. eor

C. eorg

D. orgi

E. You will get an index out of bounds exception

 

 

[문제16]

Given the following code segment, what is the value of s1 after the code executes?

1
2
3
4
5
6
7
String s1 = "Hi There";
String s2 = s1;
String s3 = s2;
String s4 = s1;
s2 = s2.toLowerCase();
s3 = s3.toUpperCase();
s4 = null;
cs

 

A. null

B. hi there

C. HI THERE

D. Hi There

E. hI tHERE

 

 

[문제17]

There is a method called checkString that determines whether a string is the same forwards and backwards. The following data set inputs can be used for testing the method. What advantage does Data Set 2 have over Data Set 1?

Data Set 1 Data Set 2
aba
abba
aBa
bcb
bcd

 

A. Data Set 2 contains one string which should return true and one that should return false.

B. All strings in Data Set 2 have the same number of characters.

C. The strings in Data Set 2 are all lowercase

D. Data Set 2 contains fewer values than Data Set 1.

E. There are no advantages.

 

 

[문제18]

A car dealership needs a program to store information about the cars for sale.For each car, they want to keep track of the following information: the number of doors (2 or 4),its average number of miles per gallon, and whether the car has air conditioning. Which of the following is the best design?

 

A. Use one class, Car, which has three attributes: int numDoors, double mpg, and boolean hasAir.

B. Use four unrelated classes: Car, Doors, MilesPerGallon, and AirConditioning

C. Use a class, Car, which has three subclasses: Doors, MilesPerGallon, and AirConditioning

D. Use a class Car, which has a subclass Doors, with a subclass AC, with a subclass MPG.

E. Use three classes: Doors, AirConditioning, and MilesPerGallon, each with a subclass Car.

 

 

[문제19]

Assume that SomeClass and MainClass are properly defined in separate files. What is the output of the code in main()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SomeClass
{
    public SomeClass()
    {
        System.out.print("Hello ");
    }
 
    void printSomething(String name)
    {
        System.out.print("Hello " + name + " ");
    }
}
 
public class Main {
  public static void main(String[] args) {
    SomeClass someClass = new SomeClass();
    someClass.printSomething("Bob");
  }
}
cs

 

A. Hello Bob

B. Hello Hello Bob

C. Hello Bob Hello Bob

D. Hello Bob Hello

 

 

[문제20]

What is the output of the following code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Test
{
    String someFunc(String str)
    {
        return someOtherFunc(str + " Hoo");
    }
 
    String someOtherFunc(String str)
    {
        return "Hoo " + str;
    }
 
    public static void main(String[] args)
    {
        Test x = new Test();
        System.out.print("Woo " + x.someFunc("Woo"));
    }
}
cs

 

A. Woo Hoo Hoo Woo

B. Hoo Woo Hoo

C. Woo Hoo Woo Hoo

D. Woo Woo Hoo Hoo

 

 

[문제21]

Given the following code segment, which of the following is true?

1
2
3
4
5
6
7
8
String s1 = new String("Hi There");
String s2 = new String("Hi There");
String s3 = s1;
 
I.   (s1 == s2)
II.  (s1.equals(s2))
III. (s1 == s3)
IV.  (s2.equals(s3))
cs

 

A. II and IV

B. II, III, and IV

C. I, II, III, IV

D. II only

E. IV only

 

 

[문제22]

What does the following code print?

1
2
System.out.println("13" + 5 + 3);
 
cs

 

A. 21

B. 1353

C. It will give a run-time error

D. 138

E. It will give a compile-time error

 

 

[문제23]

Assume that SomeClass and MainClass are properly defined in separate files. What is the output of main()?

1
2
3
4
5
6
7
8
9
10
11
12
13
class SomeClass
{
    int someVar;
}
 
public class MainClass
{
    public static void main(String[] args)
    {
        SomeClass x;
        System.out.println(x.someVar);
    }
}
cs

 

A. unknown value

B. 0

C. compile error

D. runtime error


[문제 정답은 아래 "더보기" 클릭]

더보기

[문제1 정답]

B

(name is an attribute of the pet object or Dog class.)

 

 

[문제2 정답]

C

(myParty is an object that is an instance of the Party class.)

 

[문제3 정답]

I and III

(I and III call the correct constructors)

 

 

[문제4 정답]

D. Movie m = new Movie("Lion King", "Disney", 8.0);

(This creates a Movie object with the correct title and rating.)

 

 

[문제5 정답]

D. age is an attribute of the myCat object.(Attributes of the Cat class and myCat object are color, breed, age.)

(A: The data type of breed is String.

B: color, breed, and age are attributes of the Cat class.

C: myCat is an instance of the Cat class.

E: Attributes of the Cat class are color, breed, age. )

 

 

[문제6 정답]

 D

 

[문제7 정답]

 C

(The length method returns the number of characters in the string, including spaces and punctuation.)

 

[문제8 정답]

 A

(The method indexOf returns the first position of the passed str in the current string starting from the left (from 0)

 

[문제9 정답]

A

(Strings are immutable, meaning they don't change. Any method that that changes a string returns a new string. So s1 never changes unless you set it to a different string.)

 

[문제10 정답]

B

(This creates a Movie object with the title "Sponge Bob")

 

[문제11 정답]

B

(The constructor sets the total to 100, the withdraw method subtracts 30, and then the deposit method adds 40)

1
2
3
4
BankAccount newAccount = new BankAccount(12345100.00);
newAccount.withdraw(30.00); // total = 70.00 (100.00 - 30.00 = 70.00)
newAccount.deposit(40.00); // 70.00 + 40.00 = 110.00
newAccount.printCurrentTotal(); // 110.00
cs

 

 

[문제12 정답]

 C

(Math.random returns a value from 0 to not quite 1. When you multiply it by 5 you get a value from 0 to not quite 5. When you cast to int you get a value from 0 to 4. Adding 5 gives a value from 5 to 9.)

 

if you chose D, it would be true if Math.random returned a value between 0 and 1, but it won't ever return 1. The cast to int results in a number from 0 to 4. Adding 5 gives a value from 5 to 9.

 

 

[문제13 정답]

 D

(Math.random returns a random value from 0 to not quite 1. After it is multipied by 11 and cast to integer it will be a value from 0 to 10. Subtracting 5 means it will range from -5 to 5.)

 

[문제14 정답]

 A

(The "equals" operation on strings returns true when the strings have the same characters. The == operator returns true when they refer to the same object. In this case all three references actually refer to the same object so both == and equals will be true.)

 

[문제15 정답]

A

(The method substring(a,b) means start at a and stop before b. The method substring(a) means start at a and go to the end of the string. The first character in a string is at index 0.)

 

 

[문제16 정답]

D

(Strings are immutable meaning that any changes to a string creates and returns a new string, so the string referred to by s1 does not change.)

 

 

[문제17 정답]

A

(All of the strings in Data Set 1 should return true, so the false condition is never tested.)

 

 

[문제18 정답]

 A

(Having one class with all the attributes needed is the most efficient design in this case.)

 

 

[문제19 정답]

 B

(The constructor is called first and prints out one "Hello " followed by the printSomething() method which prints out "Hello Bob ".)

 

 

[문제20 정답]

 C

(We first print 'Woo ' then 'Hoo ' then the appended "Woo Hoo")

 

 

[문제21 정답]

 B

(String overrides equals to check if the two string objects have the same characters. The == operator checks if two object references refer to the same object. So II is correct since s1 and s2 have the same characters. Number II is correct since s3 and s1 are referencing the same string, so they will be ==. And s2 and s3 both refer to string that have the same characters so equals will be true in IV. The only one that will not be true is I, since s1 and s2 are two different objects (even though they have the same characters).

 

 

[문제22 정답]

 B

(This is string concatenation. When you append a number to a string it get turned into a string and processing is from left to right.)

 

 

[문제23 정답]

C

(This will give an error that x has not been initialized. It needs to be initialized with a call to the SomeClass constructor.)

1
2
int a;
System.out.println(a); // error because of non-initialized value of a
cs

 

*클래스 필드 초기화에 대한 복습

  • 클래스로부터 객체가 생성될 때 필드는 기본 초기값으로 자동 설정된다.(기본 초기값 참고링크: https://vo.la/YZSrD
  • 만약 다른 값으로 초기화를 하고 싶다면 두가지 방법이 있다.
  • 하나는 필드를 선언할 때 초기값을 주는 방법이고, 또 다른 하나는 생성자에서 초기값을 주는 방법이다.
  • 필드를 선언할때 초기값을 주게 되면 동일한 클래스로부터 생성되는 객체들은 모두 같은 데이터를 갖게 된다.
  • 물론 객체 생성 후 변경할 수 있지만, 객체 생성시점에는 필드의 값이 모두 같다. 

(클래스 필드의 초기화 참고 코드)

class SomeClass{  
  int x;
  int s1() {
    System.out.println(x);
    return x;
  }
}

public class Main {
  static int a;
  public static void main(String[] args) {
    SomeClass s = new SomeClass();
    System.out.println(s.s1());
  }
}

 

728x90
반응형

댓글