[Java] 기본형vs참조형 / null 퀴즈
·
TIL/Java
출력되는 값은 무엇입니까? 0 int[] a = new int[2]; System.out.println(a[0]); 출력되는 값은 무엇입니까? null Person[] people = new Person[2]; System.out.println(people[0]); 출력되는 값은 무엇입니까? 0 Person person = new Person(); people[0] = person; person.age = a[0]; a[0] = 26; System.out.println(person.age); 출력되는 값은 무엇입니까? 27 a[0]++; people[1] = people[0]; people[1].age = a[0]; a[0] = 28; System.out.println(people[0].age); 출력되..
[Java] null
·
TIL/Java
자바에서 실수로 발생하는 대표적인 에러 중 하나를 살펴보자. 자바에서는 '비어있음'이 null이라는 값으로 표현된다. 단, null은 참조형 변수(Reference Type)만 가질 수 있는 값이다. Person p1 = null; System.out.println(p1); null 만약 null을 보관하고 있는 변수의 메소드를 호출하려고 하면 NullPointerException이라는 오류가 난다는 점을 주의하자 Person p1 = null; p1.getName(); Exception in thread "main" java.lang.NullPointerException 대처법 아래 코드는 오류가 날 것이다. people[1]과 people[4]는 null이기 때문에 p.getName()을 할 수가 없..