2021.08.08
Jump to Java 2장 자바 시작하기 및 자바의 정석 요약본 참고해서 작성.
변수란 ? 하나의 값을 저장할 수 있는 기억공간
변수 명 규칙
변수명은 숫자로 시작할 수 없다.
_(underscore) 와 $ 문자 이외의 특수문자는 사용할 수 없다.
자바의 키워드는 변수명으로 사용할 수 없다. (예: int, class, return 등)
자바 키워드(예약어) 예시 :
abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while
기본형(Primitive type) 8 개 : boolean(1), char(2), byte(1), short(2), int(4), long(8), float(4), double(8) -> 실제 값을 저장
참조형(Reference type) : 그 외 나머지, 객체의 주소 저장(64bit OS는 8byte)
명명규칙 - 권장사항
리터럴(literal)이란 소스 코드의 고정된 값을 대표하는 용어
상수와 리터럴이란? 참고함
final int MAX = 100;
에서 MAX는 상수, 100은 리터럴
- 클래스나 구조체 같은 파생된 객체도 리터럴 가능하지만 상수의 값(참조변수 주소값)이 변하지 않을 뿐 그 주소가 가리키는 데이터들까지 상수는 아님.
final Test t1 = new Test(); t1 = new Test(); //는 불가능하지만 t1.num = 10; //는 가능
- 데이터가 변하지 않도록 설계를 한 클래스를 불변 클래스라 칭한다.(immutable class) : 자바의 String, Color 같은 클래 스 -> 따라서 우리는 "abc" 와 같은 문자열을 자바에서는 '객체 리터럴' 짧게는 '리터럴'
Jump to Java 3장 자료형
숫자
int octal = 023; // 십진수: 19
int hex = 0xC; // 십진수: 12
boolean : true or false
문자(char)
char a1 = 'a'; // 문자값
char a2 = 97; // 아스키코드
char a3 = '\u0061'; // 유니코드
문자열(String)
문자열 초기화 방법
String a = "Happy Java";
String a = new String("Happy Java");
가급적 첫번째 방식(literal 표기)을 사용하는 것이 좋다. 가독성에 이점이 있고 컴파일 시 최적화에 도움을 주기 때문이다.
primitive 자료형은 new 키워드로 생성할 수 없다.
primitive 자료형은 리터럴(literal)로 값을 세팅할 수 있다. (※ 리터럴은 계산식 없이 소스코드에 표기하는 상수 값을 의미한다.)
문자열 연산
"" + 7 + 7 -> "77"
7 + 7 + "" -> "14"
유용한 메소드들
== 은 두개의 자료형이 동일한 객체인지를 판별, 대신 equals 사용.
String a = "happy java" 와 String a = new String("happy java")는 같은 값을 갖게 되지만 완전히 동일하지는 않다. 첫번째 방식은 literal String이라고 불리우는데 "happy java" 라는 문자열을 intern pool 이라는 곳에 저장하고 다음에 다시 동일한 문자열이 선언될때는 cache 된 문자열을 리턴한다. 두번째 방식은 항상 새로운 String 객체를 만든다. ↩
System.out.println(a.equals(b));
indexOf : 시작 위치
System.out.println(a.indexOf("Java"))
replaceAll : 다른 문자로 치환
String a = "Hello Java";
System.out.println(a.replaceAll("Java", "World")); //출력 : Hello World
System.out.println(a.substring(0, 4));//출력 : Hell
StringBuffer
String이랑 StringBuffer에 사용되는 자료구조는 무엇일까? 내 추측은 String은 배열, StringBuffer는 아마 링크드리스트?? 나중에 찾아봐야지
배열
String[] weeks = {"월", "화", "수", "목", "금", "토", "일"};//선언 시 초기화
String[] weeks = new String[7];//선언 후 초기화
System.out.println(weeks.length);//길이
리스트
ArrayList, LinkedList 등, 우선은 ArrayList만
생성, add
ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add(0, "133"); // 첫번째 위치에 133 삽입.
ArrayList<String> pitches = new ArrayList<String>();
이런식으로 객체를 포함하는 자료형도 어떤 객체를 포함하는지에 대해서 명확하게 표현하는것을 권고get, size, contains, remove(객체 or index)
System.out.println(pitches.get(1));
System.out.println(pitches.size());
System.out.println(pitches.contains("142"));//true or false
System.out.println(pitches.remove("129"));//true
System.out.println(pitches.remove(0));//138
제네릭스(Generics)
ArrayList<String> aList = new ArrayList<String>();//제네릭스
ArrayList aList = new ArrayList();//제네릭스 아님
ArrayList aList = new ArrayList();
aList.add("hello");
aList.add("java");
String hello = (String) aList.get(0);
String java = (String) aList.get(1);
맵(Map)
HashMap, LinkedHashMap, TreeMap 등
put, get, containsKey, remove, size
HashMap<String, String> map = new HashMap<String, String>();
map.put("people", "사람");
System.out.println(map.get("people"));
System.out.println(map.containsKey("people"));//true
System.out.println(map.remove("people"));//"사람"
System.out.println(map.size());
LinkedHashMap과 TreeMap