오늘의 과정 목록
- 데이터 저장을 위한 변수 및 데이터 타입
(문자타입, 논리타입, 형변환, 배열, 문자열, 참조 데이터 타입)- 콘솔을 통한 데이터 입출력
- 데이터 조작을 위한 각종 연산자
(대입 연산자, 산술 연산자)
문자타입
char charVariable;
charVariable = 'A';
// charVariable = 'Ab'; - 문자 하나만 넣을 수 있기 때문에
System.out.println(charVariable);
charVariable = 97;
System.out.println(charVariable);
논리타입
boolean booleanVariable = true;
System.out.println(b);
+ 상대적으로 boolean, int를 많이 사용하며 double이 그 다음, long(아주 가끔씩), 나머지는 거의 쓰이지 않는다고 한다.
+ Java에는 unsigned 정수 타입이 없다.
형변환
자동 형변환(Automatic or Implicit Casting)
// 0 0 0 0 1 0 1 0 (8자리)
// -> [0 0 0 0 0 0 0 0] 0 0 0 0 1 0 1 0 (16자리)
byteVariable = 10;
shortVariable = byteVariable;
System.out.println(shortVariable);
floatVariable = 3.14F;
doubleVariable = floatVariable;
System.out.println(doubleVariable);
명시적 형변환(Explicit or Manual Casting) (OR 강제 형변환.
// 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
// -> 데이터가 초가된다. 뒤에 있는 데이터 부터 들어가게 된다.
// 0 0 0 0 1 0 1 0 (기존 앞의 데이터가 손상됨)
// -> 값이 작기 때문에 눈에 보이는 변화는 없다.
byteVariable = (byte) shortVariable;
floatVariable = (float) doubleVariable;
// byteVariable = shortVariable;
/*
오류) Type mismatch: cannot convert from short to byte
해석) 유형 불일치: int에서 short로 변환할 수 없습니다
*/
//charVariable = shortVariable;
// Type mismatch: cannot convert from short to char -> 데이터 타입의 크기만 보는게 아니라 타입의 종류를 봐야 한다.
charVariable = (char)shortVariable;
//shortVariable = charVariable; // 같은 크기라도 형태까지 잘 봐줘야 한다.
shortVariable = (short)charVariable;
배열
배열 선언 및 초기화, 초기값 지정
// 배열 선언
int[] scores; // scores 주소가 저장이 됨.
// 배열 생성
scores = new int[3]; // 3이라는 공간이 만들어 졌음)
System.out.println(scores); // [I@76ccd017 주소
// 배열 선언과 동시에 생성
int[] myArray = new int[5];
int[] numbers = {1, 2, 3};
// 리터럴로 선언되어 그 주소가 numbers에 들어감.
// 원래 있는 주소 메인이 종료되면 리터럴에 있는 메모리 주소는 가비지 컬렉션에 의해 날라감.
int[] ages = new int[] {15, 18, 21, 24};
// 리터럴이 따로 있고 새로운 주소new를 만들어 넣음.
// 새로운 주소를 만들어 사용 새로운 주소에 저장되기 때문에 날라가도 주소에 저장되어 있음.
System.out.println(numbers);
System.out.println(ages);
배열의 단점
int studentNumber1 = 1;
int studentNumber2 = 2;
int studentNumber3 = 3;
int studentNumber4 = 4;
int studentNumber5 = 5;
Hello
char char1 = 'H';
char char2 = 'e';
char char3 = 'l';
char char4 = 'l';
char char5 = 'e';
인덱스
int[] myArray = {1, 2, 3, 4, 5};
/*
배열이 5개의 요소로 있으므로, 인덱스는 0부터 4까지이다.
{ 1, 2, 3, 4, 5}
[0번, 1번, 2번, 3번, 4번]
*/
배열의 특정 인덱스에 접근
int number = myArray[0];
/*
인덱스 0번. 즉 1의 값을 불러낼 수 있다.
*/
배열의 특정 인덱스에 값 할당
myArray[2] = 99;
/*
배열의 세 번째 위치에 99를 할당한다.
즉 {1,2,99,4,5}로 원래 자리하고 있었던 3 대신 99의 값이 들어간다.
*/
배열의 크기
int lastElement = myArray[myArray.length - 1];
int lastElement = myArray[myArray.length - 50];
/*
오류) java.lang.ArrayIndexOutOfBoundsException
해석) 배열의 인덱스를 벗어난 위치에 접근함.
*/
문자열 (String)
문자열 선언, 생성 및 초기화
선언: String 참조형 데이터 타입을 이용하여 선언한다.
생성 : new 키워드를 사용하여 문자열을 생성한다.
초기화 : 문자열을 “”로 표기하여 초기화한다.
// 문자열 선언
String myString;
// 문자열 생성
myString = new String();
// 문자열 초기화
myString = "My String Value";
변성(Immutability)
주요 기능과 메서드
String longComment1 = "내가 그린 기린 그림은 잘 그린 기린 그림이고 ";
String longComment2 = "네가 그린 기린 그림은 잘 못 그린 기린 그림이다.";
String longComment = longComment1 + longComment2;
System.out.println(longComment);
// 출력결과 : 내가 그린 기린 그림은 잘 그린 기린 그림이고 네가 그린 기린 그림은 못 그린 기린 그림이다.
boolean isEqual = longComment1.equals(longComment2);
System.out.println(isEqual);
// 출력결과 : false
/*
해석) boolean을 통해 true와 false로 문자열 비교 값을 출력할 수 있다.
문자열.equals(비교할 문자열) 공식을 사용하여 비교하였을 때 같지 않으므로 false가 나왔다.
*/
int commentLenght = longComment.length();
System.out.println(commentLenght);
// 출력결과 : 54
/*
해석) 문자열.length(). 반드시 length뒤에 '()'괄화가 와야 한다.
longComment의 길이가 54
String str = "Hello World";
String lowerStr = str.toLowerCase();
String upperStr = str.toUpperCase();
System.out.println(lowerStr);
System.out.println(upperStr);
// 출력 결과: hello world
/*
해석) toLowerCase()은 대문자를 소문자로
toUpperCase()은 소문자를 대문자로 변환한다.
*/
System.out.println(a1.indexOf("기린"));
System.out.println(a1.indexOf("기린", 7));
// 출력 결과 : 6
// 18
/*
해석) 문자열.indexOf(찾는 단어), 문자열.indexOf(찾는 단어, 숫자)
첫 기린의 단어가 나오는 인덱스 값이 6이다.
인덱스 7번째 이후에 나오는 첫 기린의 인덱스 값이 18이다.
*/
String painting = longComment.substring(3, 8); // 3번 인덱스부터 8번 인덱스까지 자르겠다.
System.out.println(painting);
참조 데이터 타입(Reference types)
객체의 참조(메모리 주소)를 저장한다.
클래스, 인터페이스, 배열, 열거형 등이 포함되어 있으며, null값을 가질 수 있다.
+ 이때 null값이란 아무것도 참조하지 않는 것으로 존재 자체가 없다.
참조 데이터 타입의 변수를 사용하기 전에 반드시 객체를 할당해야 한다. 그렇지 않으면 NullPointerException이 발생한다.
모든 클래스 및 배열 타입은 참조 데이터 타입에 해당되며, new 연산자를 사용하여 생성하는 모든 데이터 타입이 이에 해당된다.
객체 또는 배열에 대한 참조(주소)를 저장한다.
String str = "Hello, World!";
Scanner scanner = new Scanner(System.in);
콘솔을 통한 데이터 입출력
출력
// println(), print() 출력
System.out.print("출력입니다.");
System.out.println("출력입니다.");
// 출력결과 : 출력입니다.출력입니다.
입력
Scanner sc = new Scanner(System.in);
System.out.print("문장을 입력하세요 : ");
String string = sc.nextLine();
System.out.println("입력하신 문장은 '" + string + "' 입니다.");
System.out.println();
System.out.print("정수를 입력하세요 : ");
int number = sc.nextInt();
System.out.println("입력하신 정수는 '" + number + "' 입니다.");
System.out.println();
System.out.println("실수를 입력하세요 : ");
double d = sc.nextDouble();
System.out.println("입력하신 실수는 '" + d + "' 입니다.");
System.out.println();
/*
출력결과 : 문장을 입력하세요 : 안녕하세요
입력하신 문장은 '안녕하세요' 입니다.
정수를 입력하세요 : 123456
입력하신 정수는 '123456' 입니다.
실수를 입력하세요 :
3.14
입력하신 실수는 '3.14' 입니다.
*/
+ Scanner 클래스 메소드
next(): 다음 토큰을 문자열로 반환한다. 토큰은 공백 (스페이스, 탭, 엔터 등)으로 구분된다.
nextLine(): 다음 행 전체를 문자열로 반환한다.
nextInt(): 입력된 다음 토큰을 int로 반환한다.
nextDouble(): 입력된 다음 토큰을 double로 반환한다.
nextFloat(): 입력된 다음 토큰을 float로 반환한다.
nextLong(): 입력된 다음 토큰을 long으로 반환한다.
nextBoolean(): 입력된 다음 토큰을 boolean으로 반환한다.
hasNext(): 다음 토큰이 있는 경우 true를 반환한다.
hasNextInt(), hasNextDouble(), hasNextFloat(), hasNextLong(), hasNextBoolean(): 각각 다음 토큰이 해당 타입으로 해석될 수 있는 경우 true를 반환한다.
close(): 해당 Scanner의 사용을 종료한다.
데이터 조작을 위한 각종 연산자
산술연산자
사칙연산과 관련된 연산자.
+ : 좌항에 우항을 더한 값을 반환한다.
- : 좌항에 우항을 뺀 값을 반환한다.
* : 좌항에 우항을 곱한 값을 반환한다.
/: 좌항에 우항을 나눈 값을 반환한다. 두 항이 모두 정수일 때 나눈 값의 정수 부분만 반환하고 두 항 중 하나라도 실수라면 나눈 값이 그대로 저장된다.
% : 좌항에 우항을 나눈 나머지를 반환한다.
int result;
int a = 15;
int b = 9;
// +
result = 10 + 20; // result : 30
result = a + b; // result : 24
// -
result = 10 - 20; // result : -10 // 음수저장
result = a - b; // result : 6
// *
result = 10 * 20; // result : 200
result = a * b; // result : 135
// /
result = 16 / 5; // result : 3 (실제값 = 3.2이지만 정수 / 정수이기 때문에 실수인 0.2 부분은 떨어진다)
System.out.println(result);
System.out.println(16 / 5.0); // result : 3.2 (double / double 16이 int에서 double로 자동 형변환이 되어 16.0으로 계산이 된다)
result = a / b; // result : 1
System.out.println(result);
// %
result = 16 % 5; // result : 1
System.out.println(result);
result = a % b; // result : 6
System.out.println(result);
대입연산자
result = 5;
result += 3; // result = 8 (== result = result + 3;)
result -= 2; // result = 6
result *= 2; // result = 12
result /= 5; // result = 2
result %= 3; // result = 2 (몫 : 0 | 나머지 : 2)
// 10 += 3; ->
//오류)The left-hand side of an assignment must be a variable 무조건 변수이어야 한다.