본문 바로가기
정보처리기사/실기

10장 오답

by 애기 개발자 2024. 7. 22.
반응형
public class Main {
public static void main(String[] args) {
byte a = 15, b = 19;
System.out.print("%d", ~a);
System.out.print("%d", a^b);
System.out.print("%d", a&b);
System.out.print("%d", a|b);
}
}

 

-16
28
3
31

 

15는 2진수로 1111

2의 보수로 계산하면 0001 0000 이 된다

= -16

 

 


 

 

public class Main {
public static void main(String[] args) {
int a, b, c, hap;
a = b = c = 2;
hap = ++a | b-- & c--;
System.out.println(hap, a, b, c);
}
}
3 3 1 1

비트 연산자는 우선순위가 &, ^, | 이다.

 

그러므로 b-- & c-- 를 먼저한 후 ++a를 해 준다.

 


#include <stdio.h>
#include <stdbool.h>
main() {
int a, b;
bool c, d;
a = 10; b = 0;
a *= b = 5;
c = (a != b);
d = (a == b);
printf("%d, %d, %d", a, c, d);
}
  50, 1, 0

 

a *= b = 5는 a = a * (b = 5) 와 같다.

즉, 10*5이므로 a=50이 된다.


public class Main {
public static void main(String[] args) {
String str;
str = "Power overwhelming!";
System.out.println("%8.4s", str);
}
}

 

    Powe

 

%8.4s : 8자리를 확보하고, 앞에 4칸의 공백

 

그래서 앞에 4칸을띄우고, Powe가 출력 된다.

 


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 Main {
public static void main(String[] args) {
Connection conn1 = Connection.get();
conn1.count();
Connection conn2 = Connection.get();
conn2.count();
Connection conn2 = Connection.get();
conn2.count();
System.out.println(conn1.getCount());
}
}

 

3

 

객체 변수 Connection _inst = null로 초기화 하였음

객체생성 예약어인 'new' 가 생략되었음. 즉, 생성이 아닌 선언만 된것.

 

객체변수를 선언만 하게 된다면, heap이 아닌 stack 영역에 내용 없이 저장되어 사용이 불가능해짐

 

하지만 밑의 _inst = new Connection() 을 사용하여 heap영역에 선언되고 사용이 가능해짐

_inst는 stack 영역에저장되어 있고, new Connection을통해 heap 영역을 가르킬 수 있게된 것.

 

그 후 앞으로 선언되는 conn1, conn2, conn3은 모두 stack영역에서 동일한 heap주소를 가르키게 된다.

 

그러므로 모두 같은 값을 바라보게 되어 count++이 같은 값을 3번 하므로 3이 출력된다.

     

반응형

댓글