티스토리 뷰

사전 질문 복습

얻는 게 많은 시험이었다. 기본을 정말 붕어빵 끝 부분처럼 빠싹하게 알고싶다.

 

1번 문제
1. public class Score implements Comparable<Score> {
2.     private int point;
3.     public Score(int point) { this.point = point; }
4. // insert code here
5. }

Which method will complete this class?

 

A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}
 
답 : B
 

★ Comparable

- 객체의 정렬 기준을 정의하는 방법 중 하나가 정렬 대상 클래스를 자바에서 기본적으로 제공하고 있는 Comparable 인터페이스를 구현하도록 하도록 변경하는 것이다.

Comparable 인터페이스의 comparableTo( ) 메서드를 통해 인자로 넘어온 같은 타입의 다른 객체와 대소 비교가 가능하다.

 

출력하는 값Case 1. 메서드를 호출한 객체 < 인자로 넘어온 객체 : 음수Case 2. 메서드를 호출한 객체 = 인자로 넘어온 객체 : 0Case 3. 메서드를 호출한 객체 > 인자로 넘어온 객체 : 양수

 

★ Comparator

- 정렬 대상 클래스의 코드를 직접 수정할 수 없는 경우거나 다른 정렬 기준으로 정렬하고 싶을 때 사용한다.Comparator인터페이스의 구현체를 Arrays.sort( )나 Collections.sort( ) 와 같은 정렬 메서드의 추가 인자로 넘기면 정렬 기준을 누락된 클래스의 객체나 기존 정렬을 무시하고, 새로운 정렬 기준으로 넘길 수 있다. 

 

 

2번 문제
 class Atom {
      Atom() { System.out.print("atom "); }
 }

   class Rock extends Atom {
       Rock(String type) { System.out.print(type); }
     }

 public class Mountain extends Rock {
     Mountain() {
         super("granite ");
         new Rock("granite ");
     }
     public static void main(String[] a) { new Mountain(); }
 }

What is the result?
A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite

답 : F 

★ Super의 역할

- 상속받은 부모 클래스의 변수명이나 클래스 변수를 참조

- 부모 클래스 생성자를 호출한다. 

 

3번 문제
class Line {
     public class Point { public int x,y;}
     public Point getPoint() { return new Point(); }
}

class Triangle {
    public Triangle() {
       // insert code here
   }
 }

Which code, inserted at line 16, correctly retrieves a local instance of a Point object?
 
A. Point p = Line.getPoint();
B. Line.Point p = Line.getPoint();
C. Point p = (new Line()).getPoint();
D. Line.Point p = (new Line()).getPoint();

 

★ 내부 클래스

- 외부 클래스명.내부 클래스명 객체명 = new 외부클래스명.내부 클래스명();

  내부 클래스를 이용하는 이유는 '캡슐화' 때문.

  예를 들어, A라는 클래스가 있는데 이 클래스에는 b라는 작업이 많이 사용된다.

  이럴 때, B라는 클래스를 만들어 놓으면 간단하게 사용할 수 있다.

  그런데 A 이외에 다른 클래스에 B라는 작업이 필요 없다면 B 클래스를 노출 시키고 싶지 않을 것이다.

  즉, 내부 구현을 감추고 싶을 때 내부 클래스를 사용하면 될 것이다. 

 

4번 문제
StringBuilder sb1 = new StringBuilder("123");
String s1 = "123";
// insert code here
System.out.println(sb1 + " " + s1);

Which code fragment, inserted at line 24, outputs "123abc 123abc"?
A. sb1.append("abc"); s1.append("abc");
B. sb1.append("abc"); s1.concat("abc");
C. sb1.concat("abc"); s1.append("abc");
D. sb1.concat("abc"); s1.concat("abc");
E. sb1.append("abc"); s1 = s1.concat("abc");
F. sb1.concat("abc"); s1 = s1.concat("abc");
G. sb1.append("abc"); s1 = s1 + s1.concat("abc");
H. sb1.concat("abc"); s1 = s1 + s1.concat("abc");
 

★ StringBuilder란?

StringBuilder는 문자열을 버퍼에 담아 그 안에서 추가,수정, 삭제 작업을 할 수 있도록 도와주는 클래스이다. 

기존 String 변수에 새로운 값을 넣어서 수정할 수 도 있지만, 새로운 문자열로 변경될 경우,새로운 스트링 객체로 리턴된다. 그래서 StringBuilder를 이용하면 새로운 객체를 만들지 않고도 자유롭게 문자 변경 작업을 할 수 있는 것이 장점이다. 

 

답이 E인 이유는 StringBuilder에는 concat이 없고, String에는 append가 없다.

Concat함수는 연결을 해주는 함수고 Append는 문자열 끝에 문자열을 추가하는 함수이다.

 

칼럼이 같은 여러 개 데이터 프레임을 세로로 결합할 때, Concat과 Append를 많이 쓴다.append는 세로로만 결합할 수 있지만, concat은 가로,세로 모두 결합할 수 있다.concat함수가 더 빠르다.

 

5번 문제
interface Animal { void makeNoise(); }

class Horse implements Animal {
     Long weight = 1200L;
     public void makeNoise() { System.out.println("whinny"); }
 }

   public class Icelandic extends Horse {
       public void makeNoise() { System.out.println("vinny"); }
	   public static void main(String[] args) {
       Icelandic i1 = new Icelandic();
       Icelandic i2 = new Icelandic();
       Icelandic i3 = new Icelandic();
       i3 = i1; i1 = i2; i2 = null; i3 = i1;
     }
        }

When line 15 is reached, how many objects are eligible for the garbage collector?

 

A. 0
B. 1
C. 2
D. 3
E. 4
F. 6

 

★ garbage collector란?

- 프로그램을 개발할 때 유효하지 않은 메모리인 garbage가 발생하게 된다. Java는 개발자가 메모리를 직접 해지해 주는 일이 없다. 그 이유는 garbage collector 가 메모리를 알아서 정리해주기 때문이다. 

 

  • i1=A, i2=B and i3=C; 

After i3 = i1

  • i1=A, i2=B and i3=A

After i1 = i2

  • i1=B, i2=B and i3=A;

After i2 = null:

  • i1=B, i2=null and i3=A;

After i3 = i1

  • i1=B, i2=null and i3=B

총 4개

 

5번 문제
public class Pass {
     public static void main(String [] args) {
        	int x = 5;
        	Pass p = new Pass();
         p.doStuff(x);
         System.out.print(" main x = " + x);
     }

     void doStuff(int x) {
         System.out.print(" doStuff x = " + x++);
     }
 }

What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5

 

★ 인스턴스 변수 / 지역 변수

인스턴스 변수 : 클래스 내에서 선언된 것

메소드 내에서 선언한 것은 인스턴스 변수에 포함되지 않는다. 인스턴스 변수는 그 변수가 속한 객체 안에서 존재.

 

지역 변수 : 메소드 내에서 선언된 것

메소드 매개변수도 지역변수에 포함, 지역 변수는 임시 메소드가 스택에 들어 있는 동안만 살아 있다.

 

'인스턴스 변수'는 클래스 내에서 선언되고, '지역 변수' 는 메소드 내에서 선언

지역변수는 사용하기 전, 반드시 초기화해야한다.

기본 값이 없어서 초기화 하기 전, 사용하려고 하면 반드시 컴파일 과정에서 오류가 난다.

 

6번 문제

Which Man class properly represents the relationship “Man has a best friend who is a Dog”?

 

A. class Man extends Dog { }
B. class Man implements Dog { }
C. class Man { private BestFriend dog; }
D. class Man { private Dog bestFriend; }
E. class Man { private Dog<bestFriend> }
F. class Man { private BestFriend<dog> }

★인터페이스 정의와 구현

 

 public interface Pet {...} // 정의
     public class Dog extends Canine implements Pet {...} // 구현

 

7번 문제
 class Animal { public String noise() { return "peep"; } }

12. class Dog extends Animal {
13.     public String noise() { return "bark"; }
14. }

15. class Cat extends Animal {
16.     public String noise() { return "meow"; }
17. } ...

30. Animal animal = new Dog();
31. Cat cat = (Cat)animal;
32. System.out.println(cat.noise());

What is the result?
A. peep
B. bark
C. meow
D. Compilation fails
E. An exception is thrown at runtime.
 
 
Cat 자료형이 메모리에 올라간 적이 없다.
형변환 에러는 런타임시에 발생
 
 
8번 문제
 public class KungFu {
2.       public static void main(String[] args) {
3.           Integer x = 400;
4.           Integer y = x;
5.           x++;
6.           StringBuilder sb1 = new StringBuilder("123");
7.           StringBuilder sb2 = sb1;
8.           sb1.append("5");
9.           System.out.println((x==y) + " " + (sb1==sb2));
10.     }
11. }
A. true true
B. false true
C. true false
D. false false
E. Compilation fails.
F. An exception is thrown at runtime.

 

9번 문제
1.   public class GC {
2.       private Object o;
3.       private void doSomethingElse(Object obj) { o = obj; }
4.       public void doSomething() {
5.           Object o = new Object();
6.           doSomethingElse(o);
7.           o = new Object();
8.           doSomethingElse(null);
9.           o = null;
10.     }
11. }

When the doSomething method is called, after which line does the Object created in line 5 become available for garbage collection?
A. Line 5
B. Line 6
C. Line 7
D. Line 8
E. Line 9
F. Line 10

 

dosomethingElse(null);메소드를 호출하면서 null을 파라미터로 넘긴다.

그러면서 오브젝트 o가 null 값을 가지게 된다.

 

10번 문제 

 

 public class HeapObject implements Serializable , Cloneable {
       private final String name;
       public HeapObject(String name) {
           this. name = name;
       }

       @Override
       protected HeapObject clone() throws CloneNotSupportedException {
           return (HeapObject)super.clone();
       }

     public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
         HeapObject t1 = new HeapObject("test");
         HeapObject t2 = t1.clone();
         HeapObject t3 = serializeAndDeserialize(t1);
         HeapObject t4 = t1;
     }

     private static HeapObject serializeAndDeserialize(HeapObject t1) throws IOException, ClassNotFoundException {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(t1);
         ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
         return (HeapObject)ois.readObject();
     }
}

line 15에서 heap에 존재하는 HeapObject의 instance 수는?
A. 1
B. 2
C. 3
D. 4

 

★ clone 메서드

 

Java의 최상위 클래스인 Object에는 객체를 복제하는 clone 메서드가 존재한다.

이 메서드의 역할은 기존 객체의 데이터를 보존하기 위해서이다.

Java의 모든 클래스에는 Object에서 파생되기 때문에 모든 클래스의 인스턴스는 clone( )을 사용할 수 있다.

clone 메서드를 호출하려면 해당 객체의 클래스가 Cloneable 인터페이스를 구현해야한다.

 

 

11번 문제
public class MonitorCount {
	public static synchronized void foo1() {};
    public synchronized void foo2() {}
      public void foo3() {
         synchronized (this) {
         }
     }
           synchronized (getClass()) {
          }
     }
     public void foo5() {
         synchronized (new Object()) {
         }
     }
     public void foo6() {
         synchronized (new Object()) {
         }
     }
 }