2021.01.20 국비교육 12일차

[TOC]

형변환

  • 묵시적 형변환

    • 자동 형 변환 또는 promotion이라고 한다.
    • 기본 데이터 형 및 참조 데이터 형 모두 가능
    • 작은 타입은 큰 타입으로 자동 형 변환 가능
    • 큰 타입에서 작은 타입으로 바꿀때는 조건 필요
  • 명시적 형변환

    • 강제 형 변환 or type casting이라고 한다.
    • 데이터 손실 방생할 수 있다.
    • 기본 데이터 형 및 참조 데이터 형 모두 가능
public class Ex02_4 {

    public static void main(String[] args) {

        //묵시적 변환
        short s = 12;
        int n = s;

        char c = 'A';
        int n2 = c+1;
        System.out.println(n2);

        int x = 123;
        float y = x +12.3F;
        System.out.println( y);

        //명시적 변환
        int c1 = 123;
        //short d = c1; // 에러발생
        short e = (short) c1;
        System.out.println(e);
    }

}
  • 큰 타입 데이터와 작은 타입 데이터가 연산 될 때 결과는 큰 타입으로 자동으로 변경
int n =10;
float f = 20.3f;
double dd = n + f; // 연산결과는 실수
  • int보다 작은 데이터형간의 연산결과는 int로 자동으로변경됨
short s1 = 10;
short s2 = 20;
short s3 = s1 + s2//에러
--> int s3 = s1 + s2;
--> short s3 = (short)(s + s2);
  • 문자열과 다른 데이터간에 + 연산자 사용시 문자열로 자동으로 변경
String str = "hello" + 1 + 2 + 3;

output: hello123

String str1 = 1 + 2 + 3 + "hello";

output : 6hello

String str2 ="hello" +  1 + 2 + 3 + "world";
  • 연습
int result1 = 10 + 3.14; // 실수 double
double result2 = 10 + 3.14;
float result3 = 10 + 3.14; // 실수 float
float result4 = 10 +3.14f;
float result5 = (float)(10+3.14); // 실수 --> float로 명시적 형변환
double result6 = 10; // 자동 형변환
public class Sample03_typeCasting {

    public static void main(String[] args) {

        //데이터 타입 변경(자동으로 변경) : 묵시적
        //1. byte -> short -> int -> long ->float -> double
        byte b = 10;
        short b2 = b;
        int b3 = b2;
        long b4 = b3;
        float b5 = b4;
        double b6 = b5;

        System.out.println(b6);

        //2. char --> int
        char n = 'A';
        int n2 = n + 1;
        System.out.println(n2);

        char c = (char)n2;
        System.out.println(c);

        //3. int보다 작은 타입의 연산결과는 자동 int로 저장
        short x = 10;
        short x2 = 20;
        int x3 = x + x2;
        short x4 = (short)(x + x2);

        //4. 문자열 + 문자열이 아닌데이터
        System.out.println("10" + 1 + 2 + 3);
        System.out.println(1 + 2+ 3 + "10");

        String k = "10";
        System.out.println(k + 10); // 1020

        //문자열 10을 정수 10으로 변환
        //자바 : Integer.parseInt
        //자바스크립트 : Number.parseInt
        int k2 = Integer.parseInt(k);
        System.out.println(k2 + 20); //30

        String num1 = "10";
        String num2 = "20";
        String rr1 = num1 + num2; //"1020"

        int intNum1 = Integer.parseInt(num1);
        int intNum2 = Integer.parseInt(num2);

        int rr2 = Integer.parseInt(num1) + Integer.parseInt(num2); //정수30
        int rr3 = Integer.parseInt(num1 + num2); //정수 1020

        //정수 10을 문자열 10으로 변환
        //자바스크립트 = toString()
        //자바 : String.valueOf(10) ==> "10"

        System.out.println(String.valueOf(10) + 10); //1010
        System.out.println(10+""+10); //1010

        //5.작은타입과 큰타입이 연산 --> 큰타입
        int p1 = 100;
        double p2 = 3.14;
        double p3 = p1+ p2;
    }
}
public class Sample_03_typeCasting2 {

    public static void main(String[] args) {

        // 데이터 타입 변경(명시적 형변환)

        int n = 10;
        short n2 = (short)n;
        System.out.println(n2);

        short x = 10;
        short x2 = 20;
        short x3 = (short)(x + x2); // 주의 - 명시적 형변환 불필요

    }

}
  • 권장하지 않는 방법
public class Sample02_variable5_2 {

    public static void main(String[] args) {    

        //한꺼번에 여러번수 선언 가능,권장 안함
        int n,m,p = 100;
        n = 10;
        m = 20;
        p = 30;
    }
}

상수

  • 값을 변경하지 못하는 것을 상수라고 한다.
  • final 키워드를 사용하여 상수 처리한다.
public class Sample04_final {

    public static void main(String[] args) {

        // 상수 : 값 변경 불가, 전부 대문자로
        //Byte.MIN_VALUE, Byte,MAX_VALUE
        final int SIZE = 100;
        //SIZE = 200; // 값 변경 불가
        System.out.println(SIZE);

    }

}

SCOPE

  • 변수는 블록내에서 생성되고 스코프내에서 관리
public class Test {

    public static void main(String[] args) {

        int a = 10;
        System.out.println("1====" + a);

        { //x 블럭 시작
            int b = 20; // x블럭안에 선언 - scope x블럭까지만
            System.out.println("2====" + a);

        } // x블럭 끝

        //System.out.println(b); // x블럭 밖에서 b사용 불가
    }
}

참조형 변수

public class Member_Instance_variable {
    //변수 선언 위치 - 함수 안, 또는 class 블럭 안
    int memberNum = 10; // class안에 선언된 변수는 반드시 객체 생성(new)을 해서 사용해야함
    public static void main(String[] args) {
        //class 블럭에 선언된 변수를 멤버변수, 인스턴수변수라고 호칭
        //1. 멤버 변수가 속한 클래스 객체 생성
        Member_Instance_variable ref = new Member_Instance_variable();
        System.out.println(ref); // 객체 참조하는 ref변수에 객체의 주소가 저장되어 있음
        //2. 참조변수이용하여 참조변수, 인스턴스변수 이름으로 사용
        System.out.println(ref.memberNum);


    }//main 함수블럭

}//class 블럭
public class Instance_Test_3 {
//선언 위치 : class 단 : 멤버변수, 인스턴스 변수라고 부름
//함수에서 사용시 그냥 사용 안됨, 객체생성(new)후 참조변수 이용하여 사용해야함
//멤버변수는 명시적 초기화가 필요하지 않음, 객체 생성시 자동 초기화
//String -> null, 정수 -> 0, 실수형 -> 0,.0 문자 -> 공백으로 자동초기화

    String name;
    char gender;
    int age;

    public static void main(String[] args) {
        //함수 안에 선언된 변수를 로컬 변수라고 한다.
        //1. 사용범위 : 함수안에 선언, main안에서만 사용
        //2. 사용전에 반드시 선언 및 초기화 값 필요
//        String name = "홍길동";
//        char gender = '남';
//        int age = 10;

//        System.out.println(name + "\t" + age + "\t" + gender);

        Instance_Test_3 ref = new Instance_Test_3();
        System.out.println(ref);
        System.out.println(ref.name);
        System.out.println(ref.name + "\t" + ref.age + "\t" + ref.gender);
        ref.name = "홍길동";
        ref.gender = '남';
        ref.age = 10;
        System.out.println(ref.name + "\t" + ref.age + "\t" + ref.gender);
    }

}

연산자

  • 연산되는 데이터는 피연산자(operand)라고 한다.

  • 산술연산자

    • 4칙연산과 나머지값을 구하는 연사자를 뜻한다
      • [ +, - *, /, %]
//산술연산자
public class Ex03_1 {

    public static void main(String[] args) {
        System.out.println(10 +5);
        System.out.println( 5 - 2);
        System.out.println(4*3);
        System.out.println(14/3);
        System.out.println(14/3.0);
        System.out.println(3.2/2);
        System.out.println(5%3);
    }
}
//비교연산자
public class Ex03_3 {

    public static void main(String[] args) {

        int a = 10;
        int b = 5;

        System.out.println(a == b);
        System.out.println(a > b);
        System.out.println(a >= b);
        System.out.println(a < b);
        System.out.println(a<= b);
        System.out.println(a != b);

        boolean result = a > b;
        System.out.println(result);
    }

}
//대입연산자
public class Ex03_4 {
    public static void main(String[] args) {

        int a = 10;
        int b = a;
        System.out.println(b);

        b += a;
        System.out.println(b);

        b -= a;
        System.out.println(b);

        b /=a;
        System.out.println(b);

        b %= a;
        System.out.println(b);
    }
}
//증감연산자
public class Ex03_5 {

    public static void main(String[] args) {

        int a =3;

        ++a;
        System.out.println(a);;

        a--;
        System.out.println(a);

        int x = 5;
        int y = ++x;
        System.out.println(x + " " + y );

        int x2 = 5;
        int y2 = x2++;
        System.out.println(x2 + " " + y);
    }
}
//논리 연산자
public class Ex03_6 {

    public static void main(String[] args) {

        boolean a = true;
        boolean b = false;

        System.err.println(a&&a);
        System.err.println(a&&b);
        System.err.println(b&&a);
        System.err.println(b&&b);

        System.err.println(a||a);
        System.err.println(a||b);
        System.err.println(b||a);
        System.err.println(b||b);

        System.err.println(!a);
        System.err.println(!b);
    }
}

문자열 비교

public class StringEqualsTest {

    public static void main(String[] args) {

        String m1 = "hello";
        String m2 = "hello";
        String m3 = new String("hello");
        ///== 문자열 비교 사용금지
        System.out.println("== 사용결과" + (m2 == m3));

        /// 문자열 비교 equals 사용
        System.out.println("equals사용결과: " + m2.equals(m3));

        //m1과 m3비교, m1m2비교 결과 출력
        System.out.println("equals사용결과: " + m1.equals(m3));

        System.out.println("equals사용결과: " + m1.equals(m2));
    }

}

+ Recent posts