자격증/정보처리기사 실기 - 기출문제

[정보처리기사 실기] 2021년 3회 01 - 프로그래밍 [JAVA]

쏠솔랄라 2025. 7. 17. 08:34

 

 

 

01 다음 JAVA로 구현된 프로그램을 분석하여 그 실행 결과를 쓰시오. (단, 출력문의 출력 서식을 준수하시오.)

class Connection {
	private static Connection _inst = null;
	private int count = 0;
	public static Connection get() {
		if(_inst == null) {
			_inst = new Connection();
			return _inst;
		}
		return _inst;
	}
	public void count() { count++; }
	public int getCount() { return count; }
}

public class Test {
	public static void main(String[] args) {
		Connection conn1 = Connection.get();
		conn1.count();
		Connection conn2 = Connection.get();
		conn2.count();
		Connection conn3 = Connection.get();
		conn3.count();	
		System.out.print(conn1.getCount());
	}
}

 

 

 

 

 

 

해설

 

  코드   실행순서 및 해석
1 class Connection {    
2      private static Connection _inst = null;   Connection이라는 클래스에 _inst라는 개체변수를 선언하고 null로 값을 지정
3      private int count = 0;   정수형 변수 int를 선언하고 0을 넣는다
4      public static Connection get() { 3
10
17
get() 호출
5           if(_inst == null) { 4 _inst가 null일 때
11
18
_inst는 null이 아니므로 if를 실행하지 않음
6                _inst = new Connection(); 5 _inst는 new라는 예약어를 사용해 Connection() 생성
→ heap 영역에 저장
7                return _inst; 6 주소값 100 반환
8           }    
9           return _inst; 12
19
_inst의 주소값 100 반환
10      }    
11      public void count() { count++; } 9
15
22
void: 반환값은 없으며
count의 값을 1증가시켜라
12      public int getCount() { return count; } 24 호출 → count리턴 → 3
13 }    
14 public class Test {    
15      public static void main(String[] args) { 1 실행
16      Connection conn1 = Connection.get(); 2 예약어 없이 선언만 해 준다
→ Connection의 get() 메서드 실행
  7 conn1에 주소값 100을 넣어준다
17      conn1.count(); 8 conn1.count() 호출 후 되돌아옴
18      Connection conn2 = Connection.get(); 9 conn2 선언(생성 x)
→ Connection의 get() 메서드 실행
13 get()에서 100을 반환했으므로
conn2에 100을 넣는다
19      conn2.count(); 14 conn2.count() 호출 후 되돌아옴
20      Connection conn3 = Connection.get(); 16 conn3 선언(생성 x)
→ Connection의 get() 메서드 실행
20 get()에서 100을 반환했으므로
conn2에 100을 넣는다
21      conn3.count(); 21 conn3.count() 호출 후 되돌아옴
22      System.out.print(conn1.getCount()); 23 getCount() 출력
23      }    
24 }    

 

* 자바의 stack 영역 : 정적으로 할당된 메모리 영역, 임시로 사용되는 매개변수의 영역

boolean, char, short, int, long, float, double, …

<stack 영역>

변수
_inst null → 100
count 0 → 1 → 2 → 3
conn1 100
conn2 100
conn3 100

conn1, 2, 3 모두 heap 영역의 주소 100을 동일하게 가리키게 됨

 

* heap 영역 : 동적으로 할당된 메모리 영역

모든 오브젝트 타이의 데이터가 할당, 생성된 객체가 저장

heap 영역  
주소 내용
100 private static Connection _inst
private int count = 0
static public Connection get() {…}
public void count() {…}

200  
300