[자바] 기본타입은 null 이 허용되지 않는다.

손경이·2023년 11월 14일
0

자바

목록 보기
17/17

2023.11.14 [테킷 백엔드 부트캠프 희성 강사님 강의]

기본타입은 null 이 허용되지 않는다.

  • 기본타입 8개
    • boolean, char, byte, short, int, long, float, double
  • 기본 타입 외에 참조 타입은 null을 넣을 수 있다.
  • /calc?a=10&b=20, url은 무조건 다 문자열이다.

💞 String showCalc(int a, int b)

  • 매개변수에 아무값이 안들어오면 null을 넣는다. int가 기본형이라서 불가능(기본형은 null을 허용하지 않음)

💞 String showCalc2(Integer a, Integer b)

  • 매개변수에 아무값이 안들어오면 null을 넣는다. Integer가 참조형이라서 가능
  • return "a : " + a + ", b : " + b;
    -> a : null, b : null

💞 들어오는 queryString 순서는 바껴도 됨


💞 int 보다는 double, double 보다는 String이 더 다양한 데이터를 받을 수 있다.

  • int는 정수 허용
@GetMapping("/calc3")
@ResponseBody
String showCalc3( // 값이 안 들어오면 0이 기본값으로 들어온다.
// int는 정수 허용
@RequestParam(defaultValue = "0") int a,
@RequestParam(defaultValue = "0") int b
) {
return "계산 결과 : %d".formatted(a + b); // %d 10진수 정수
}
  • double은 정수, 실수 허용
@GetMapping("/calc4")
@ResponseBody
String showCalc4( // 값이 안 들어오면 0이 기본값으로 들어온다.
// double은 정수, 실수 허용
@RequestParam(defaultValue = "0") double a,
@RequestParam(defaultValue = "0") double b
) {
return "계산 결과 : %f".formatted(a + b); // %f 실수
}
  • String은 문자열, 정수, 실수 다 허용
@GetMapping("/calc5")
@ResponseBody
String showCalc5( // 값이 안 들어오면 "-"이 기본값으로 들어온다.
// String은 문자열, 정수, 실수 다 허용
@RequestParam(defaultValue = "-") String a,
@RequestParam(defaultValue = "-") String b
) {
return "계산 결과 : %s".formatted(a + b); // %s 문자열
}

오류나는 예시

@GetMapping("/calc8")
@ResponseBody
Person showCalc8(String name, int age) {
// 값이 없으면 기본형인 int로 인해서 오류 난다. String은 값이 없으면 null이 나온다.
return new Person(name, age); // 브라우저가 이해할 수 있게 번역된다.
}

0개의 댓글