Variable이란?
- 자료를 저장하기 위한 메모리 공간으로 타입에 따라 크기가 달라짐
- 메모리 공간에 값을 할당 후 사용
Type이란?
| 기본형 | 참조형 |
|---|---|
| 미리 정해진 크기의 데이터 표현 | 크기가 미리 정해질 수 없는 데이터의 표현 |
| 변수 자체에 값 저장 | 변수에는 실제 값을 참조할 수 있는 주소만 저장 |
기본형의 갯수(8개)
논리형(Boolean)
정수형(byte, short, int, long(끝에L))
실수형(float(끝에 F), double)
문자형(char)
Q. byte는 8비트인데 2^7까지만 처리하는 이유?
A. 맨 앞 비트는 부호비트 !
다음 코드의 실행 결과?
public static void main(String[] args) {
int i1 = Integer.MAX_VALUE;
int i2 = i1 + 1;
System.out.println(i2);
}
-> overflow발생 ! (정수 계산 시 주의)
따라서, -2147483648가 출력
public static void main(String[] args) {
float f1 = 2.0f
float f2 = 1.1f
float f3 = f1 - f2;
System.out.println(f3);
double d1 = 2.0;
double d2 = 1.1;
double d3 = d1 - d2;
System.out.println(d3)
// 정확한 값 계산하기
System.out.println(((int) (d1 * 100) - (int) (d2 * 100)) / 100.0);
BigDecimal b1 = new BigDecimal("2.0");
BigDecimal b2 = new BigDecimal("1.1");
System.out.println("BigDecimal을 이용한 빼기 : " + b1.subtract(b2));
}
-> 실수의 연산은 정확하지 않다. - 유효 자리수를 이용한 반올림 처리
형변환이란?
형 변환 방법
타입의 표현 범위가 커지는 방향으로 할당할 경우는 묵시적 형 변환 발생
ex) long(64비트) -> float(32비트)
추가로 short(16비트) <-> char(16비트)는 불가
why? short는 부호비트를 사용하지만 char는 모든 비트를 사용하므로
public class Main {
public static void main(String[] args) {
int i1 = Integer.MAX_VALUE;
int i2 = i1 + 1; // overflow
System.out.println(i2); // -2147483648
long l1 = i1 + 1; // overflow
System.out.println(l1); // -2147483648
long l2 = (long) (i1 + 1); // overflow 먼저 계산하므로
System.out.println(l2); // -2147483648
long l3 = (long) i1 + 1;
System.out.println(l3); // 2147483648
int i3 = 1000000 * 1000000 / 100000; // 깨지고 나눔
int i4 = 1000000 / 100000 * 100000;
System.out.println(i3 + " : " + i4); // -7273 : 1000000
}
}
public class Main {
public static void main(String[] args) {
byte b1 = 10;
byte b2 = 20;
byte b3 = b1 + b2; // 에러발생 int이하이므로
int i1 = 10;
long l1 = 20; // 자동 형변환
int i2 = i1 + l1; // 큰 타입 long으로
float f1 = 10.0; // 기본 double이므로 F로 !
float f2 = f1 + 20.0; // 큰 타입 double로
}
}
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println((a > b) & (b > 0)); // false
System.out.println((a += 10) > 15 | (b -= 10) > 15); // true
System.out.println("a = " + a + ", b = " + b); // 20, 10
a = 10;
b = 20;
System.out.println((a += 10) > 15 || (b -= 10) > 15); // true
System.out.println("a = " + a + ", b = " + b); // 20, 20
}
}
why? ||연산은 앞이 true이면 뒤의 연산을 실행하지않음. but |연산은 두개의 연산 모두 실행.
- if문에 들어갈 수 있는 type?
boolean, Boolean, boolean getResult()- switch문에 들어갈 수 있는 type?
byte, short, char, int, String, int getNumber()
- long타입은 안됨. 또한 정수형의 모든 타입 x
public class Main {
public static void main(String[] args) {
int num = 3;
switch (num) {
case 1:
System.out.println(num);
case 2:
System.out.println(num);
case 3:
System.out.println(num); // 실행
case 4:
System.out.println(num); // 실행
case 5:
break; // 중단
case 6:
break;
default:
System.out.println(num);
}
int month = 3;
int day = -1;
switch (month) {
case 2:
day = 29;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
default:
day = 31;
break;
}
System.out.printf("%d월은 %d까지 있다.%n", month, day);
}
}
반복문의 4가지 구성요소
- 변수 초기화
- 반복 조건
- 증감식
- 실행문
public static void byFor() {
int sum = 0;
int cnt = 100;
double avg = 0;
Random rand = new Random();
for (int i = 0; i < cnt; i++) {
sum += rand.nextInt(6) + 1;
}
}
public static void byWhile() {
int sum = 0;
int cnt = 100;
double avg = 0;
Random rand = new Random();
int i = 0;
while (i < cnt) {
sum += rand.nextInt(6) + 1;
i++;
}
}
배열이란 ? 동일한 타입의 데이터 0개 이상을 하나의 연속된 메모리 공간에서 관리하는 것
타입[] 변수명; or 타입 변수명[]
ex) int a; int[] arr
- a의 타입 ? int
- arr의 타입 ? int[] (참조형 타입)
- arr이 저장하는 데이터의 타입 ? int
배열의 생성과 초기화
- new 키워드와 함께 저장하려는 데이터의 타입 및 길이 지정
- 배열의 생성과 동시에 저장 대상 자료형에 대한 기본값으로 default초기화 진행
- 메모리의 연속된 공간 차지 -> 크기 변경 불가 !!
자료형 기본값 boolean false char 공백문자 byte, short, int 0 long 0L flaot 0.0f double 0.0 참조형 변수 null
출력을 편하게 하는 법
Arrays.toString()
String org = "Hello";
char[] chars = new char[org.length()];
for (int i = 0; i < chars.length; i++) {
chars[i] = org.charAt(i);
}
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]);
}
// -> API
chars = org.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]);
}
for (int i : arr) {
//~~~
}
Array는 변경불가 !
public static void main(String[] args) {
int[] scores = { 90, 80, 100 };
// TODO: 95점을 추가로 관리하기 부적절한 코드는?
// scores[3] = 95; // #1
// scores = new int[] {90, 80, 100, 95}; // #2
// scores = {90, 80,100, 95 }; // #3
// scores = Arrays.copyOf(scores, 5); // #4
// scores[3]=95;
// int[] scores2 = new int[4]; // #5
// System.arraycopy(scores, 0, scores2, 0, scores.length);
// scores2[3] = 95;
}
->
1: 넘치는 idex
3: new int[] 선언