반응형

1. 기본형 vs 참조형

 

-기본형 : int / boolean / char / double 

int a = 3;
int b = a;

System.out.println(a);  // 3 출력
System.out.println(b);  // 3 출력

a = 4;
System.out.println(a);  // 4 출력
System.out.println(b);  // 3 출력

b = 7;
System.out.println(a);  // 4 출력
System.out.println(b);  // 7 출력

 

-참조형 : Person, String , int[] 등 클래스 기반 자료형

Person p1, p2;
p1 = new Person("김신의", 28);

p2 = p1;
p2.setName("문종모");

System.out.println(p1.getName()); //문종모
System.out.println(p2.getName()); //문종모

p1은 '김신의'라는 이름을 가진 Person 인스턴스가 저장되어있음

p2 = p1 => p2에게 같은 영역을 가리키라

p2.setName("문종모") 를 하면 그 영역에 있는 인스턴스의 name -> 문종모  로 바뀜

p2, p1은 모두 같은 영역을 가리키고 있으니 두 출력 값은 모두 '문종모'

 

배열 또한 객체이기에 참조형

int[] a = new int[3];
int[] b = a;

a[0] = 1;
b[0] = 2;

System.out.println(a[0]); //2
System.out.println(b[0]); //2

 

 

2. null 

비어있음 -> null 로 표현

단, null은 참조형 변수(Reference Type)만 가질 수 있는 값

Person p1 = null;
System.out.println(p1); //null

//만약, null을 보관하고 있는 변수의 메소드를 호출하려고 하면 오류 발생
Person p1 = null;
p1.getName(); //Exception in thread "main" java.lang.NullPointerException

//대처법
Person[] people = new Person[5];
people[0] = new Person("김신의", 28);
people[2] = new Person("문종모", 26);
people[3] = new Person("서혜린", 21);

for (int i = 0; i < people.length; i++) {
    Person p = people[i];
    if (p != null) {
        System.out.println(p.getName());
    } else {
        System.out.println(i + "번 자리는 비었습니다.");
    }
}

/*김신의
1번 자리는 비었습니다.
문종모
서혜린
4번 자리는 비었습니다.*/

 

3. 숏서킷 연산(Short-Circuit Evaluation)

-> 실의 결과값이 이미 결정된 경우 미리 멈추는 것

 

-And (&&)

boolean newBoolean = m1() && m2() && m3();

-> newBoolean이 true가 되기 위해서는  m1()m2()m3()가 모두 true를 리턴해야함

 

-Or (||)

boolean newBoolean = m1() || m2() || m3();

-> newBoolean이 false이기 위해서는 m1()m2()m3()의 리턴값이 모두 false이어야 함

 

4. 변수 안전하게 만들기(final)

-변수 정의 시 final을 써주면, 그 변수는 상수가 됨 -> 한번 정의하면 다시 바꿀 수 없음

 

-참조형

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public static void main(String[] args) {
        final Person p1 = new Person("김신의");
        p1.setName("문종모");
        System.out.println(p1.getName());
    }
}
//문종모

->p1의 이름을 못 바꾸도록 만들고 싶으면 Person 클래스 내에서 name을 final로 정의해주면 됨.

 

5. 인스턴스 변수 vs 클래스 변수

 

-인스턴스 변수

public class Person {
    int count;
}

//새로운 Person 인스턴스를 생성할 때마다 각 인스턴스의 count변수를 계속 바꿔야함
public static void main(String[] args) {
    Person p1 = new Person();
    p1.count++;

    Person p2 = new Person();
    p1.count++;
    p2.count = p1.count;

    Person p3 = new Person();
    p1.count++;
    p2.count++;
    p3.count = p2.count;

    Person p4 = new Person();
    p1.count++;
    p2.count++;
    p3.count++;
    p4.count = p3.count;

    System.out.println(p1.count); //4
    System.out.println(p2.count); //4
    System.out.println(p3.count); //4
    System.out.println(p4.count); //4
}

 

-클래스 변수 버전

public class Person {
    static int count;
}

//count는 특정 인스턴스에 해당되는게 아니라, Person 클래스 전체에 해당되는 것
//count 부를 때 대문자로 쓴 클래스 이름을 사용해서 Person.count 써준다

public static void main(String[] args) {
    Person p1 = new Person();
    Person.count++;

    Person p2 = new Person();
    Person.count++;

    Person p3 = new Person();
    Person.count++;

    Person p4 = new Person();
    Person.count++;

    System.out.println(Person.count);
} //4

 

-> Person.count++ 매번해주는 것을 개선시켜주자 

public class Person {
    static int count;

    public Person() {
        count++;
    }
}

public static void main(String[] args) {
    Person p1 = new Person();
    Person p2 = new Person();
    Person p3 = new Person();
    Person p4 = new Person();

    System.out.println(Person.count);
}//4

 

-> 변수가 클래스 자체에 해당될 때는 static 써서 클래스 변수로 만들어주자!

 

-상수

상수는 인스턴스에 해당되는 것이 아니며, 여러 복사본 대신 한 값만 저장해둔다

public class CodeitConstants {
    public static final double PI = 3.141592653589793;
    public static final double EULERS_NUMBER = 2.718281828459045;
    public static final String THIS_IS_HOW_TO_NAME_CONSTANT_VARIABLE = "Hello";

    public static void main(String[] args) {
        System.out.println(CodeitConstants.PI + CodeitConstants.EULERS_NUMBER);
    }
}//5.859874482048838

 

6.인스턴스 메소드 vs 클래스 메소드 

-클래스 메소드 : 인스턴스가 아닌 클래스에 속한 메소드

-> 인스턴스를 생성하지 않고도 바로 실행할 수 있다

 

<클래스 메소드 예시>

-Math 클래스 

import java.lang.Math;

public class Driver {
    public static void main(String[] args) {
        System.out.println(Math.abs(-10));   // 절댓값
        System.out.println(Math.max(3, 7));  // 두 값 중 최댓값
        System.out.println(Math.random());   // 0.0과 1.0 사이의 랜덤값
    }
}

10
7
0.40910432549890663

Math 클래스에 있는 abs()max()random() 등의 메소드가 바로 '클래스 메소드'

 

-main 메소드

public static void main(String[] args) {
    ...
}

 

-클래스 변수를 다룰 때

public class Counter {
    static int count;

    public static void increment() {
        count++;
    }

    public static void main(String[] args) {
        System.out.println(Counter.count);

        Counter.increment();
        System.out.println(Counter.count);

        Counter.increment();
        System.out.println(Counter.count);

        Counter.increment();
        System.out.println(Counter.count);
    }
}
0
1
2
3

 

언제 클래스 메소드를 쓰나?

-> 생성된 인스턴스가 하나도 없더라도 메소드를 호출하고 싶다면 -> static메소드 사용

반응형

'Language Study > Java' 카테고리의 다른 글

6. 자바, 더 간편하게  (0) 2019.09.08
제주에서 자바_Week4  (0) 2019.08.12
제주에서 자바_Week3_4  (0) 2019.08.11
##자바 헷갈리는 이론  (0) 2019.08.01
제주에서 자바_Week3_3  (0) 2019.07.31

+ Recent posts