(신규개발자) 자바의 정석, 1주차 ch2-5

ch2-11 기본형과 범위

논리형 boolean 1 byte
문자형 char 2 bytes
정수형 byte 1 byte, short 2 byte, int 4 bytes, long 8 bytes
실수형 float 4 bytes, double 8 bytes

범위
1 byte = 8 bit 2^8-1
1 sign bit + 7 bit + and - of 2^7-1

-1 붙는건 0 때문에
int 는 2^31 임으로 대략 20억임 즉 int는 -20억~20억

실수형
float 4byte/32bit : S 부호 + 지수 E(8) + 가수 M(23) = 32 bit ; 정밀도 7자리 ; 10^7 < 2 ^24 < 10^8 > 그래서 정밀도 7자리
double 8byte/64bit : S 부호 + 지수 E(11) + 가수 M(52) = 64 bit ; 정밀도 15자리

ch2-12,13 printf 이용한 출력

printf 지시자
%b boolean
%d 10진 정수
%o 8진 정수
%x 16진 정수

%f 부동 소수점
%e 지수 (exponent) 표현식

%c 문자
%s 문자열

2진수 찍기: System.out.print(“%s”, Integer.toBinaryString(15); // 1111 로 나옴
8진수와 16진수 앞에 접두사 붙이기 : …”%#x”, 15) // 0xf 로 나옴

ch2-14 화면에서 입력 받기 Scanner

1
2
3
4
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String input = scanner.nextLine();
int num = Integer.parseInt(input);

ch2-17 타입간의 변환방법

  1. 문자와 숫자간의 변환
  2. 문자열로의 변환
    “3” -> ‘3’ : str.charAt(0); // 인자는 str의 index
    “3” -> 3 : Integer.parseInt(“3”);
    “3.4” -> 3.4 : Double.parseDouble(“3.4”);

ch3-1,2 연산자와 피연산자

산술연산자 + - * / % << >>
비교연산자 > < >= <= == !=
논리연산자 && || ! & | ^ ~
대입연산자 =
기타 (type) ?: instanceof

ch3-3,4 연산자의 우선순위와 결합규칙

  1. 산술 > 비교 > 논리 > 대입 순서
  2. 단항 > 이항 > 삼항
  3. 방향 왼쪽 -> 오른쪽, 단항하고 대입만 오른쪽 -> 왼쪽

ch3-5,6 증감 연산자

증가 연산자 ++
감소 연산자 –
전위형: 값 참조 전에 증가 j = ++i; >> ++i; j=i;
후위형: 값 참조 후에 증가 j = i++; >> j=i; i++;

ch3-7 형변환 연산자

(타입) 피연산자

1
2
double d = 85.4;
int i = (int) d; // i 는 85가 됨

작은 범위 타입에서 큰 범위 타입은 자동 변환이 안되어 명시적으로 해주지 않으면 컴파일 에러 난다.

ch3-11,12 반올림

1
Math.round()

ch3-13 비교 연산자

문자열 비교에는 == 대신 equals() 를 사용

ch3-17 조건 연산자 ?

조건식에 결과에 따라 연산 결과를 달리 한다.

조건식 ? 식1: 식2
조건식 참이면 식1, 거짓이면 식2

result = (x > y) ? x : y;

ch4 조건문과 반복문

if문, if-else문

1
2
3
4
5
6
7
8
9
10
switch (조건식) {
case1:
break;

case2:
break;

default:
break; // 생략은 가능
}

switch문의 조건식 결과는 정수 또는 문자열

ch4-12 임의 정수 만들기

Math.random() - 0.0와 1.0 사이의 임의 double 값

1에서 X 사이의 랜던 정수 얻는 법

0.0 < Math.randome() * X < 1.0

  1. 각변에 원하는 숫자 곱한다.
  2. 각 변을 int 로 변환
  3. 각변에 1 더한다.
    1 < Math.random() * X < X+1

ch4-13 반복문

1
2
3
4
for (초기화;조건식;증감식)
{
수행 될 문장들 블럭
}

중첩 for 문

1
2
3
4
5
6
for (int i = 2; i < 10; i++)
{
for(int j = 1; j < 10; j++)
System.out.printf("%d * %d = %d\n", i, j, i*j);

}

ch4-16 while 문

while문의 loop 구문의 원조
이후 for loop 좀더 편하게 나옴

1
2
3
4
5
초기화;
while(조건식) {
수행될 문장
증감식;
}

ch4-19 do-while문

블럭 {}을 최소한 한번 실행

1
2
3
4
5
do {

실행할 문장들..

} while(조건식);

break; > 빠져 나올때는 사용
continue; > 반복문 실행 블락의 제일 밑으로 이동 , 다음 반복으로 갈때 사용

ch4-23 이름 붙은 반복문

label 을 붙여서 goto 하는 듯한 구문이
자바에도 있다.

1
2
3
4
5
6
7
8
9
10
11
Loop1 : for (int i = 2; i < 10; i++)
{
for(int j = 1; j < 10; j++)
{
if(j==5)
{
break Loop1;
System.out.printf("%d * %d = %d\n", i, j, i*j);
}
}
}

ch5 배열이란?, 선언 방법, 길이

  • 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것
1
2
3
4
5
6
7
8
9
10
11
12
int score1, score2, score3...
int[] score; // 배열의 선언, 참조 변수 score
score = new int[5]; // 실제 저장 공간 생성

score[0]; // index 0 부터 시작됨
score[1];
score[2];
score[3];
score[4];

int[] arr = new int[5];
int tmp = arr.length; // 길이 5, 리턴 됨
  • 자바는 2가지 선언 방식 전부 지원
    언어 | 선언방법 | 선언 예

——— | ———
Java | 타입[] 변수이름; | int[] score;
C | 타입 변수이름[]; | int score[];

ch5-5 배열의 초기화

  • 기본적으로 자동 초기화 된다.
1
2
3
4
int[] score = new int[5];
score[0] = 50;
...
int[] score = {50, 60, 70, 80, 90};

Arrays 의 toString 메서드

1
2
int[] iArr = { 100, 95, 80, 70, 65};
System.out.println(Arrays.toString(iArr));

System에 Copying Arrays 메서드 arraycopy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)

class ArrayCopyDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto", "Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato",
"Marocchino", "Ristretto" };

String[] copyTo = new String[7];

// copying
System.arraycopy(copyFrom, 2, copyTo, 0, 7);

// 결과 출력
for (String coffee : copyTo) {
System.out.print(coffee + " ");
}
}
}

The output from this program is: Cappuccino Corretto Cortado Doppio Espresso Frappucino Freddo

Arrays, array manipulations (common tasks) : copying, sorting, searching

For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class.

위에 예제는 copyOfRange 를 사용 하면 더 간편하다. (dest array 생성 불 필요)

1
2
3
4
5
6
7
8
9
10
11
12
13
class ArrayCopyOfDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto", "Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato",
"Marocchino", "Ristretto" };

String[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
for (String coffee : copyTo) {
System.out.print(coffee + " ");
}
}
}

결과: [Cappuccino, Corretto, Cortado, Doppio, Espresso, Frappucino, Freddo]

initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively. 예제 에서는 index 2 와 9 까지, 2는 포함, 9는 미포함

java.util.Arrays class의 다른 유용한 함수들

  1. Searching (binarySearch method).
  2. Comparing two arrays to determine if they are equal or not (the equals method).
  3. Filling an array to place a specific value at each index (the fill method).
  4. Sorting an array into ascending order. using sort method, or parallelSort method introduced in Java SE 8.
  5. Converting an array to a string. The toString method converts each element of the array to a string, separates them with commas, then surrounds them with brackets.
  6. Creating a stream that uses an array as its source (the stream method).
1
java.util.Arrays.stream(copyTo).map(coffee -> coffee + " ").forEach(System.out::print);  

See Aggregate Operations for more information about streams.

ch5-16 커맨드 라인을 통해 입력 받기

main(String[] args) 는 cmd 실행시 java example abc 123 “hello world” 하면 args[0]은 abc, [1]는 123, [2] hello world가 들어간다.

ch5-18~20 2차원 배열

1
2
3
4
5
6
int[][] score = {
{100, 100, 100},
{20, 20, 20},
{30, 30, 30},
{40, 40, 40}
};

ch5-14,15 String 클래스

ch5-24 Arrays 배열 다루기