Difference between revisions of "컴퓨터프로그래밍및실습 (2022년)/0905"

From DISLab
Jump to navigation Jump to search
 

Latest revision as of 21:11, 21 July 2022

변수

  • 변수란 기억 장소(메모리)에 대한 별칭이다.

변수의 선언

int age;  // 정수(int) 값을 저장할 수 있는 age 변수 선언
double value; // 실수(double) 값을 저장할 수 있는 value 변수 선언

int x, y, z;  // 여러 개를 선언할 수 있음

변수 이름을 붇이는 규칙

  1. 첫 번째 글자는 문자이거나 $, _ 이어야 하고 숫자로 시작할 수 없다. (필수)
  2. 영어 대소문자가 구분된다. (필수)
  3. 첫 문자는 영어 소문자로 시작하되, 다른 단어가 붙을 경우 첫 문자는 대문자로 한다. (관례) (maxSpeed, firstName, carBodyColor)
  4. 문자 수(길이)의 제한은 없다.
  5. 자바 예약어는 사용할 수 없다. (필수)
분류 예약어
기본 데이터 타입 boolean, byte, char, short, int, long, float, double
접근 지정자 private, protected, public
클래스와 관련된 것 class, abstract, interface, extends, implements, enum
객체와 관련된 것 new, instanceof, this, super, null
메소드와 관련된 것 void, return
제어문과 관련된 것 if, else, switch, case, default, for, do, while, break, continue
논리값 true, false
예외 처리와 관련된 것 try, catch, finally, throw, throws
기타 transient, volatile, package, import, synchronized, native, final, static, strictfp, assert


변수의 사용

int score;    // 변수 선언
score = 90;   // 값 저장

int score = 90; /// 선언과 동시에 값 저장

Literal

  • 리터럴(literal) : 소스 코드 내에서 직접 작성된 값
    • 정수 리터럴 : 0, 75, -100 (10진수), 02, -04 (8진수), 0x5, 0xA, 0xB3, 0xac08 (16진수)
    • 실수 리터럴 : 0.25, -3.14 (10진수), 5E7, 0.12E-5 (0.12×10-5)
    • 문자 리터럴 : 'A', '한', '\t', '\tn'
Escape 문자 용도 Unicode
\t 수평 탭 0x0009
\n 줄 바꿈 0x000A
\r 리턴 0x000D
\" "(큰 따옴표) 0x0022
\ '(작은 따옴표) 0x0027
\\ \ 0x005C
\u16진수 16진수에 해당하는 유니코드 0x0000 ~ 0xFFFF

변수의 초기화

  • 초기화하지 않고 사용하면 오류
int value;
int result = value + 10; // value 값을 초기화하지 않아 오류가 남
  • 초기화하여 사용한 예
int value = 30;
int result = value + 10;

변수의 사용 범위

  • 변수는 블록 범위 내에서 정의, 사용할 수 있음
public class VariableScopeExample {
    public static void main(String[] args) {
        int v1 = 15;
        if (v1 > 10) {
            int v2 = v1 - 10;
        }
        int v3 = v1 + v2 + 5; // v2 변수를 사용할 수 없기 때문에 컴파일 에러가 생김
    }
}

데이터 타입 (Data Type)

기본(원시: primitive) 타입

값의 종류 기본 타입 메모리 사용 크기 저장되는 값의 범위
정수 byte 1 byte (8 bits) -27 ~ 27-1 (-128 ~ 127)
char 2 bytes (16 bits) 0 ~ 216-1 (\u0000 ~ \uFFFF, 0 ~ 65535)
short 2 bytes (16 bits) -215 ~ 215-1 (-32,768 ~ 32,767)
int 4 bytes (32 bits) -231 ~ 231-1 (-2,147,483,648 ~ 2,147,483,647)
long 8 bytes (64 bits) -263 ~ 263-1
실수 float 4 bytes (32 bits) (+/-)1.4E-45 ~ (+/-)13.4028235E38
double 8 bytes (64 bits) (+/-)4.9E-324 ~ (+/-)1.7976931348623157E308
논리 boolean 1 byte (8 bits) true, false

정수 타입

  • byte, char, short, int, long
  • 음수는 2의 보수로 표현함

byte

이진수 십진수
01111111 127
01111110 128
... ...
00000001 1
00000000 0
11111111 -1
11111110 -2
... ...
10000001 -127
10000000 -128

  • 예제 코드
public class ByteExample {
    public static void main(String[] args) {
        byte var1 = -128;
        byte var2 = -30;
        byte var3 = 0;
        byte var4 = 30;
        byte var5 = 127;
        // byte var6 = 128; // 컴파일 에러

        System.out.println(var5);
        var5++;
        System.out.println(var1); // var1은 왜 음수가 되는가?
    }
}
  • 실행 결과
127
-128

char

  • 예제 코드
public class CharExample {
    public static void main(String[] args) {
        char c1 = 'A';
        char c2 = 65;
        char c3 = '\u0041'; // 10진수로 표현하면 65

        char c4 = '가';
        char c5 = 44032;
        char c6 = '\uac00'; // 10진수로 표현하면 44032

        int uniCode = c1;
        
        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
        System.out.println(uniCode);
    }
}
  • 실행 결과
A
A
A
가
가
가
65
  • String과 char
String name = "홍길동";

char c1 = '';  // 컴파일 에러
char c2 = ' '; // 에러가 나지 않음. 스페이스 문자

String str = ""; // 빈 문자열

int

  • 10진수로 10인 정수(int)의 경우 4 바이트로 다음과 같이 표현
00000000 00000000 00000000 00001010
1 byte 1 byte 1 byte 1 byte

  • 예제 코드 (int & long)
public class IntExample {
    public static void main(String[] args) {
        int var1 = 10;  // 10진수로 저장
        int var2 = 012; // 8진수로 저장
        int var3 = 0xA; // 16진수로 저장

        System.out.println(var1);
        System.out.println(var2);
        System.out.println(var3);
    }
}
  • 실행 결과
10
10
10

long

  • 예제 코드
public class LongExample {
    public static void main(String[] args) {
        long var1 = 10;
        long var2 = 20L;
        // long var3 = 1_0000_0000_0000; // 컴파일 에러
        long var4 = 1_0000_0000_0000L;

        System.out.println(var1);
        System.out.println(var2);
        System.out.println(var4);
    }
}
  • 실행 결과
10
20
1000000000000

실수 타입(float & double)

  • + m × 10n
    • + : 부호
    • m : 가수(mantissa)
    • n : 지수(exponent)
타입 부호 지수 가수 비트 수 바이트 수
float 1 bit 8 bit 23 bit 32 bit 4 byte
double 1 bit 11 bit 52 bit 64 bit 8 byte

  • 예제 코드
public class FloatDoubleExample {
    public static void main(String[] args) {
        // 실수값 저장
        double var1 = 3.14;
        // float var2 = 3.14; // 컴파일 에러 (Type mismatch)
        float var3 = 3.14F;

        // 정밀도 테스트
        double var4 = 0.1234567890123456789;
        float var5 = 0.1234567890123456789F;

        System.out.println("var1: " + var1);
        System.out.println("var3: " + var3); // 교재 오류
        System.out.println("var4: " + var4);
        System.out.println("var5: " + var5);

        // e 사용하기
        int var6 = 3_000_000;
        double var7 = 3e6;
        float var8 = 3e6F;
        double var9 = 2e-3;

        System.out.println("var6: " + var6);
        System.out.println("var7: " + var7);
        System.out.println("var8: " + var8);
        System.out.println("var9: " + var9);
    }
}
  • 실행 결과
var1: 3.14
var3: 3.14
var4: 0.12345678901234568
var5: 0.12345679
var6: 3000000
var7: 3000000.0
var8: 3000000.0
var9: 0.002


논리 타입(boolean)

boolean stop = true;
if (stop) {
    System.out.println("중지합니다.");
} else {
    System.out.println("시작합니다.");
}

타입 변환

자동 변환 타입

  • 큰 타입에서 작은 타입으로의 변환
  • byte(1) < short(2) < int(4) < long(8) < float(4) < double(8)
byte byteValue = 200;
int intValue = byteValue; // 자동 형 변환이 일어난다. 00000000 00000000 00000000 00001010 <- 00001010

int intValue = 200;
double doubleValue = intValue; // 200.0 <- 200

char charValue = 'A';
int intValue = charValue;  // 65 <- 'A'

byteValue = 65;
charValue = byteValue; // 컴파일 오류. 1 바이트 크기의 데이터를 2 바이트 크기의 메모리에 저장 시도
char charData = (char) byteData; // 강제 형변환

강제 타입 변환

  • 큰 크기의 타입에서 작은 크기의 타입에 대입할 경우
// 값을 잃음
int intValue = 103029770; // 00000100 00100100 00011100 00001010
byte byteValue = (byte) intValue; // 00001010 <- 00000100 00100100 00011100 00001010

// 값을 잃지 않음
intValue = 10;
byteValue = (byte) intValue; // 00001010 <- 00000000 00000000 00000000 00001010

long longValue = 300;
int intValue = (int) longValue;

intValue = 'A';
char charValue = (char) intValue; // 문자는 2 바이트 값이므로 값 유지됨
System.out.println(charValue);

double doubleValue = 3.14;
intValue = (int) doubleValue; // 3 <-- 3.14
  • 최대값 & 최소값
기본 타입 최대값 상수 최소값 상수
byte Byte.MAX_VALUE Byte.MIN_VALUE
short Short.MAX_VALUE Short.MIN_VALUE
int Integer.MAX_VALUE Integer.MIN_VALUE
long Long.MAX_VALUE Long.MIN_VALUE
float Float.MAX_VALUE Float.MIN_VALUE
double Double.MAX_VALUE Double.MIN_VALUE

정수 타입을 실수 타입으로 변환할 때 정밀도 손실 발생

  • 예제 코드
public class FromIntToFloatDouble {
    public static void main(String[] args) {
        int num1 = 123_456_780;

        float num2 = num1;
        int num3 = (int) num2;      // 정밀도 손실 발생

        int result = num1 - num3;
        System.out.println(result);

        double num4 = num1;
        int num5 = (int) num4;      // 정밀도 손실 없음

        result = num1 - num5;
        System.out.println(result);
    }
}
  • 실행 결과
-4
0

연산식에서의 자동 타입 변환

  • 4 바이트 보다 작은 정수(byte, char, short)는 4 바이트 크기의 int로 변환된 후 연산된다.
  • 정수 연산에서 피연산자 중 하나가 long이면 long으로 변환된 후 연산된다.
  • float 끼리의 연산은 float이지만, 피연산자 중 하나가 double이면 double로 변환된 후 연산된다.
  • 실수 리터럴은 double이다.
  • 예제 코드
public class OperationPromotionExample {
    public static void main(String[] args) {
        byte byteValue1 = 10;
        byte byteValue2 = 20;
        // byte byteValue3 = byteValue1 + byteValue2; // 컴파일 에러. byte는 int로 변환된 후 연산됨
        int intValue1 = byteValue1 + byteValue2;
        System.out.println(intValue1);

        char charValue1 = 'A';
        char charValue2 = 1;
        // char charValue3 = charValue1 + charValue2; // 컴파일 에러. char는 int로 변환된 후 연산됨
        int intValue2 = charValue1 + charValue2;
        System.out.println("유니코드=" + intValue2);
        System.out.println((char)intValue2);

        int intValue3 = 10;
        int intValue4 = intValue3 / 4;
        System.out.println(intValue4);

        int intValue5 = 10;
        // int intValue6 = 10 / 4.0; // 컴파일 에러
        double doubleValue = intValue5 / 4.0;
        System.out.println(doubleValue);
    }
}
  • 실행 결과
30
유니코드=66
B
2
2.5