Skip to content

Commit e6e4395

Browse files
committed
[#2] [woody] 자바 데이터타입, 변수 그리고 배열
1 parent a7c1c16 commit e6e4395

File tree

1 file changed

+327
-0
lines changed

1 file changed

+327
-0
lines changed

Week2/woody/week2.md

Lines changed: 327 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,327 @@
1+
2+
3+
## [Week2] 자바 데이터 타입, 변수 그리고 배열
4+
5+
6+
7+
### 학습 내용
8+
9+
- 프리미티브 타입 종류와 값의 범위 그리고 기본 값
10+
- 프리미티브 타입과 레퍼런스 타입
11+
- 리터럴
12+
- 변수 선언 및 초기화하는 방법
13+
- 변수의 스코프와 라이프타임
14+
- 타입 변환, 캐스팅 그리고 타입 프로모션
15+
- 1차 및 2차 배열 선언하기
16+
- 타입 추론, var
17+
18+
19+
20+
### 프리미티브 타입 종류와 값의 범위 그리고 기본값
21+
22+
The values of the `boolean` type encode the truth values `true` and `false`(1 bit), and the default value is `false`.
23+
24+
The integral types:
25+
26+
- `byte`, 8-bit(1 byte) , default value zero
27+
28+
값의 범위 : -128 ~ 127
29+
30+
- `short` 16-bit(2 bytes) , default value zero
31+
32+
값의 범위 : -2^15 ~ 2^15 - 1
33+
34+
- `int`, 32-bit(4 bytes) , default value zero
35+
36+
값의 범위 : -2^31 ~ 2^31 - 1
37+
38+
- `long`, 64-bit(8 bytes) , default value zero
39+
40+
값의 범위 : -2^63 ~ 2^63 - 1
41+
42+
- `char, 16-bit (2 bytes) unsigned integers representing Unicode code, default value = null code point (`'\\u0000'`)
43+
44+
값의 범위 : \u0000' to ‘\uffff'
45+
46+
The floating-point types:
47+
48+
- `float`, 4 bytes, default value = positive zero
49+
50+
값의 범위 : single-precision 32-bit
51+
52+
- `double`, 8 bytes, default value = positive zero
53+
54+
값의 범위 : double-precision 64-bit![Screen Shot 2021-05-08 at 6.20.47 AM](/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.20.47 AM.png)
55+
56+
참조 : https://www.javatpoint.com/float-vs-double-java
57+
58+
- (+) 좀 더 예쁘게 정리된 그림![Screen Shot 2021-05-08 at 6.21.36 AM](/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.21.36 AM.png)
59+
60+
참조 : http://nlp.jbnu.ac.kr/PL/ch02.pdf
61+
62+
63+
64+
### 프리미티브 타입과 레퍼런스 타입
65+
66+
1. Primitive types:
67+
68+
값을 변수에 대입해서 사용한다.
69+
70+
- Numeric types:
71+
- `byte` (8-bit 2's complement)
72+
- `short` (16-bit 2's complement)
73+
- `int` (32-bit 2's complement)
74+
- `long` (64-bit 2's complement)
75+
- `char` (16-bit unsigned Unicode)
76+
- `float` (32-bit IEEE 754 single precision FP)
77+
- `double` (64-bit IEEE 754 double precision FP)
78+
- `boolean` type
79+
- `returnAddress`: pointer to instruction
80+
81+
2. Reference types:
82+
83+
heap 영역에 할당된 주소 값만을 가지고 있고 실제 값을 가지지 않는다.
84+
85+
- 클래스
86+
- 배열
87+
- 인터페이스
88+
- 열거형
89+
- String
90+
91+
92+
93+
### 리터럴
94+
95+
자바가 다루는 실제 데이터를 말한다.
96+
97+
<img src="/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.22.18 AM.png" alt="Screen Shot 2021-05-08 at 6.22.18 AM" style="zoom:50%;" />
98+
99+
100+
101+
참조 : https://techvidvan.com/tutorials/literals-in-java/
102+
103+
여기서는 변수에 넣는 20이라는 변하지 않는 데이터를 리터럴이라고 한다.
104+
105+
리터럴의 종류는 아래와 같다.
106+
107+
1. Integer literals
108+
2. Floating literals
109+
3. Boolean literals
110+
4. Character literals
111+
5. String literals
112+
6. Null literal - null 값을 나타내는 하나의 리터럴로 취급
113+
114+
115+
116+
### 변수 선언 및 초기화하는 방법
117+
118+
멤버변수의 경우 초기화 하지 않아도 자동으로 변수 타입에 맞는 기본 값으로 초기화가 이루어 진다.
119+
120+
반면 지역 변수의 경우에는 반드시 초기화를 해주어야 한다.
121+
122+
```json
123+
class A {
124+
private int a; // 기본값 0으로 자동 초기화
125+
private int b = 3; // 명시적으로 초기화
126+
127+
public int plusFour(int c){
128+
int b = 4; // 지역 변수는 반드시 초기화를 시켜주어야 한다.(기본값으로 자동초기화 X)
129+
return c + b;
130+
}
131+
}
132+
```
133+
134+
(+) 멤버 변수 초기화
135+
136+
1. 명시적 초기화
137+
138+
- 변수 선언과 동시에 초기화 값을 명시적으로 할당하는 것
139+
140+
2. 생성자
141+
142+
- 생성자 내부에서 멤버변수에 값을 할당하는 것
143+
144+
3. 초기화 블럭 [[참고](https://stackoverflow.com/a/3987586)]
145+
146+
- instance initialization blocks
147+
- static initialization blocks
148+
149+
```json
150+
public class Test {
151+
152+
static int staticVariable;
153+
int nonStaticVariable;
154+
155+
// 클래스 생성시 초기화
156+
static {
157+
staticVariable = 5;
158+
}
159+
160+
// 인스턴스 생성시 초기화
161+
{
162+
nonStaticVariable = 7;
163+
}
164+
}
165+
```
166+
167+
168+
169+
### 변수의 스코프와 라이프 타임
170+
171+
변수의 스코프 = 변수를 사용할 수 있는 범위
172+
173+
변수의 라이프 타임 = 변수가 메모리에서 살아있는(?) 시간
174+
175+
**Instance Variables**
176+
177+
- 스코프 : static method를 제외한 클래스 전체 영역
178+
- 라이프 타임 : 해당 인스턴스가 메모리에서 사라지기 전까지
179+
180+
**Class** **Variables**
181+
182+
- 스코프 : 클래스 전체 영역
183+
- 라이프 타임 : 프로그램 실행 내내
184+
185+
**Local** **Variables**
186+
187+
- 스코프 : 지역 변수가 선언된 메소드, 생성자 등 블럭 내부
188+
- 라이프 타임 : 지역변수가 선언된 블럭이 control flow 내부에 존재할 때 (해당 블럭을 벗어나기 전까지)
189+
190+
###
191+
192+
### 타입 변환, 캐스팅 그리고 타입 프로모션
193+
194+
**타입 변환(Type Conversion)**
195+
196+
말 그대로 하나의 타입을 다른 타입으로 변환시키는 것을 타입 변환이라고 한다. 타입 변환에는 컴파일러가 자동으로 타입 변환을 수행하는 자동 타입 변환과 타입 캐스트 연산자()를 통해 타입 변환을 강제하는 강제 타입 변환, 두 가지 종류가 있다.
197+
198+
199+
200+
**자동 타입 변환(Type Promotion = Widening or Automatic Type Conversion = Implicit type conversion )**
201+
202+
아래와 같은 순서로 자동 형변환이 이루어진다. 사이즈가 작은 타입이 큰 타입으로 변환될 경우 발생하기 때문에 데이터 손실이 발생하지 않는다.<img src="/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.24.40 AM.png" alt="Screen Shot 2021-05-08 at 6.24.40 AM" style="zoom:50%;" />
203+
204+
참조 : https://www.geeksforgeeks.org/type-conversion-java-examples/#:~:text=Type promotion in Expressions&text=Some conditions for type promotion,long%2C float or double respectively.
205+
206+
207+
208+
**강제 타입 변환(Explicit type casting or narrowing)**
209+
210+
반대로 사이즈가 큰 타입에서 작은 타입으로 변환되어야 할 경우 타입 캐스트 연산자를 통해 강제로 형변환을 해주기도 한다. 숫자형 데이터 타입을 타입 캐스팅해줄 경우 데이터 손실이 발생할 수도 있다.<img src="/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.25.19 AM.png" alt="Screen Shot 2021-05-08 at 6.25.19 AM" style="zoom:50%;" />
211+
212+
참조 : https://www.geeksforgeeks.org/type-conversion-java-examples/#:~:text=Type promotion in Expressions&text=Some conditions for type promotion,long%2C float or double respectively.
213+
214+
(+) 모든 Numeric 기본형 타입들은 호환이 가능하지만 Non-numeric에서 Numeric 기본형으로 혹은 반대로의 전환은 불가능하다.
215+
216+
217+
218+
**클래스 간의 타입 캐스팅**
219+
220+
상속관계의 클래스타입(Non-numeric)끼리는 타입 캐스팅이 가능하다. Numeric 기본형간의 형변환과 달리 상하관계가 존재한다.<img src="/Users/woody/Library/Application Support/typora-user-images/Screen Shot 2021-05-08 at 6.25.55 AM.png" alt="Screen Shot 2021-05-08 at 6.25.55 AM" style="zoom:50%;" />
221+
222+
참조 : https://www.geeksforgeeks.org/upcasting-vs-downcasting-in-java/
223+
224+
1. 업캐스팅(up casting)
225+
226+
명시적인 타입 캐스팅이 따로 필요없이 자식 클래스가 부모 클래스로 형변환이 가능하다.
227+
228+
```json
229+
// Upcasting
230+
Parent p = new Child();
231+
```
232+
233+
2. 다운 캐스팅(down casting)
234+
235+
반대로 부모 클래스로 선언되어있던 변수를 다시 자식 클래스로 변환해주기 위해서는 명시적으로 타입 캐스팅을 해주어야 한다.(이때, 변수가 참조하고 있는 실제 데이터 타입은 Child 타입 혹은 이보다 더 하위의 클래스 타입이어야 한다)
236+
237+
```json
238+
// Trying to Downcasting Implicitly
239+
// Child c = new Parent(); - > compile time error
240+
241+
// Downcasting Explicitly
242+
Child c = (Child)p;
243+
```
244+
245+
246+
247+
### 1차 및 2차 배열 선언하기
248+
249+
배열은 하나의 변수로 동일한 타입의 데이터를 연속된 메모리 공간에 저장하기 위한 자료구조다.
250+
251+
- 캐시 지역성(cache locality)을 높일 수 있는 수단이 된다. 특히 for문으로 배열을 순회할 때, 높은 캐시 hit을 보인다. (* 캐시 지역성 = 메모리 상 인접한 데이터의 재사용률이 높음)
252+
- 배열 선언 시 변수에 첫 원소에 대한 주소값을 저장하기 때문에, index를 사용하여 빠르게 접근이 가능하다.
253+
- 초기화 없이 배열의 크기만 할당했을 경우, primitive type의 경우 초기값으로 채워지게 되고 reference type의 경우 null로 채워진다.
254+
255+
1. 1차 배열
256+
257+
```json
258+
int[] arr; // 초기화 없이 변수만 선언
259+
int[] arr = new int[3]; // 선언과 함께 배열의 크기까지 할당, 초기값으로 채워짐
260+
int[] arr = {1,2,3,4,5}; // 선언 + 크기 지정 + 초기화
261+
```
262+
263+
1. 2차 배열
264+
265+
```json
266+
int[][] arr;
267+
int[][] arr = new int[4][3];
268+
int[][] arr = { {1,2},{3,4},{5,6}};
269+
```
270+
271+
272+
273+
### 타입 추론, var
274+
275+
타입 추론이란 데이터 타입을 명시하지 않더라도, 컴파일 단계에서 컴파일러가 타입을 유추하는 기능을 말한다.
276+
277+
Java 10에 var이라는 키워드가 추가되면서 어떤 데이터 타입이든 var 키워드로 선언이 가능해졌다. (단, 멤버 변수나 정적 변수에는 사용이 불가능하다, 반드시 초기화를 해주어야 한다)
278+
279+
280+
281+
## 참조
282+
283+
프리미티브 타입 종류와 값의 범위 그리고 기본값
284+
285+
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.3
286+
287+
프리미티브 타입과 레퍼런스 타입
288+
289+
https://dzone.com/articles/introduction-to-java-bytecode
290+
291+
레퍼런스 타입
292+
293+
https://jinbroing.tistory.com/3
294+
295+
변수의 초기화
296+
297+
https://doublesprogramming.tistory.com/73
298+
299+
변수의 스코프와 라이프 타임
300+
301+
https://www.learningjournal.guru/article/programming-in-java/scope-and-lifetime-of-a-variable/
302+
303+
타입 변환
304+
305+
http://www.tcpschool.com/java/java_datatype_typeConversion
306+
307+
https://www.geeksforgeeks.org/type-conversion-java-examples/#:~:text=Type promotion in Expressions&text=Some conditions for type promotion,long%2C float or double respectively.
308+
309+
https://www.examtray.com/java/last-minute-java-type-casting-or-type-conversion-or-type-promotions-tutorial
310+
311+
클래스 간의 타입 캐스팅
312+
313+
https://kamang-it.tistory.com/entry/Java-19타입형-변환Type-Casting
314+
315+
https://www.geeksforgeeks.org/upcasting-vs-downcasting-in-java/
316+
317+
배열
318+
319+
https://seducinghyeok.tistory.com/18
320+
321+
타입 추론
322+
323+
https://www.geeksforgeeks.org/var-keyword-in-java/
324+
325+
우와...
326+
327+
https://catsbi.oopy.io/6541026f-1e19-4117-8fef-aea145e4fc1b

0 commit comments

Comments
 (0)