1. Java Primitive Type 8가지
: byte 1바이트, short 2 바이트, int 4바이트, long 8바이트,
float 4바이트, double 8바이트, char 2바이트, boolean
2. 기본 타입간의 자동 형변환(implicit casting)
: byte > short > int > long > float > double
: char > int
기본적으로 작은 크기에서 큰 크기로, 정수타입에서 실수타입으로 자동형변환
3. 연산자(Operator)
: 연산, 연산자, 피연산자
연산(Operation) : 4 + 2
연산자(Operator) : 4, 2
피연산자(Operand) : +
: 단항연산자(unary operator), 이항연산자(binary operator), 삼항연산자(ternary operator)
4. 한 번에 변수명 변경하기
: [변경하고자 하는 이름에 커서를 두기] 우클릭 > Refactor > Rename 클릭, 혹은 Alt + Shift + R 단축키 사용
> 키보드를 이용하여 변경할 이름 입력
> Continue 클릭
> 한 번에 변경 완!!
5. 프로젝트 압축하기
: 해당 프로젝트 선택 > 우클릭 > Export 클릭
> General > Archive File > Next 클릭
> 압축할 프로젝트가 잘 선택되었는지, 경로와 파일명은 제대로 설정됬는지 확인하고 Finish 클릭
6. 압축된 프로젝트 불러오기
: 우클릭 > import
> General > Existing Projects into Workspace
> Select archive file 선택 > Brower를 통해 불러오기할 압축된 프로젝트 선택
> 프로젝트가 잘 선택되었는지 확인 후 Finish 클릭
7. 물리적으로 다른 곳에 있는 압축된 프로젝트 불러오기(물리적으로 다른 곳에 있을 때, copy 필요)
: 우클릭 > import > General > Existing Projects into Workspace 까지는 동일
> Select root directory 선택 > 불러오고자 하는 압축된 프로젝트 선택
> [중요!] Copy projects into workspace 체크 > Finish 클릭
8. 이클립스 세팅 초기화
[실습 코드]
1. Lec03_Variables
1) com.lec.java.variable02 패키지, Input01Main 클래스
package com.lec.java.variable02;
//자바의 기본 자료형(primitive data type)
//정수 타입: byte(1바이트), short(2바이트), int(4바이트), long(8바이트)
//실수 타입: float(4바이트), double(8바이트)
//문자 타입: char(2바이트)
//논리 타입: boolean
public class Variable02Main {
public static void main(String[] args) {
System.out.println("정수타입 변수들");
// 정수표기법, 아래에 저장된 값은 전부 11임
int number1 = 11; // 10진수(Decimal)
int number2 = 0xB; // 16진수(Hexadecimal), 0x로 시작
int number3 = 013; // 8진수(Octal) : 0으로 시작
int number4 = 0b1011; // 2진수(Binary) : 0b로 시작
System.out.println("number1 = " + number1);
System.out.println("number2 = " + number2);
System.out.println("number3 = " + number3);
System.out.println("number4 = " + number4);
// String.format()을 사용하여 원하는 포맷(진법)으로 출력 가능
// String.format("%x", number1) -> number1을 16진수로 출력하라는 뜻
System.out.println("number1 = " + String.format("%x", number1));
// String.format("%o", number1) -> number1을 8진수로 출력하라는 뜻
System.out.println("number1 = " + String.format("%o", number1));
// Integer.toXxx(n)를 사용하여 원하는 포맷의 문자열로 변환 가능
System.out.println("number1 = " + Integer.toHexString(number1));
System.out.println("number1 = " + Integer.toOctalString(number1));
System.out.println("number1 = " + Integer.toBinaryString(number1));
} // end main()
} // end class
2) com.lec.java.variable03 패키지, Variable03Main 클래스
package com.lec.java.variable03;
//실수형 자료 타입: float(4바이트), double(8바이트)
//정수형 자료 타입의 기본형은 int
//실수형 자료 타입의 기본형은 double
public class Variable03Main {
public static void main(String[] args) {
System.out.println("변수 - 실수타입");
double number1 = 3.141592;
//float number2 = 3.14; // 기본적으로 실수 리터럴은 double로 인식
// Type mismatch: cannot convert from double to float
// float <- double 대입 불가
// float 리터럴
float number3 = 3.14f;
// 실수 타입 최소값, 최대값
// 실수 타입의 최소값의 개념은? 1보다 작고 0보다 큰(즉, 얼마나 많이 표현할 수 있느냐가 중요)
System.out.println("float : " + Float.MIN_VALUE + " ~ " + Float.MAX_VALUE);
System.out.println("double : " + Double.MIN_VALUE + " ~ " + Double.MAX_VALUE);
// 실수는 정확한 값을 기대하면 안된다
// float와 double은 저장할 수 있는 값의 크기만이 아니라
// 소숫점 이하 정밀도(precision)의 차이가 있다.
float number4 = 1.23456789f;
double number5 = 1.23456789;
System.out.println("number4 = " + number4);
System.out.println("number5 = " + number5);
// 실수 표기법
double number6 = 123; // 123은 int가 double로 자동형변환 된다!
double number7 = 1.23e2; // 지수표기법(exponential notation)
System.out.println("number6 : " + number6);
System.out.println("number7 : " + number7);
double number8 = 0.0001213;
double number9 = 1.213E-4;
System.out.println("number8 : " + number8);
System.out.println("number9 : " + number9);
} // end main()
} // end class
3) com.lec.java.variable04 패키지, Variable04Main 클래스
package com.lec.java.variable04;
public class Variable04Main {
public static void main(String[] args) {
System.out.println("변수 - char, boolean, String");
// char : 문자 하나를 저장하기 위한 데이터 타입(2 바이트)
char ch1 = 'A';
// char 리터럴은 홑따옴표('')로 묶어줌
// 문자열(String) 리터럴은 쌍따옴표(" ~ ")로 묶어줌
System.out.println("ch1 : " + ch1);
char ch2 = '한';
char ch3 = '글';
System.out.println("ch2 : "+ ch2);
System.out.println("ch3 : "+ ch3);
char ch4 = 0xAE01;
System.out.println("ch4 : " + ch4);
char ch5 = 1234;
System.out.println("ch5 : " + ch5);
// println()은 char를 문자로 출력함
// 그러나, 다른 정수형으로 변환되면 해당 코드값을 정수로 출력
char ch6 = '!';
System.out.println("ch6 : " + ch6);
char ch7 = 33;
System.out.println("ch7 : " + ch7);
System.out.println("ch7 + 1 : " + (ch7 + 1));
System.out.println("ch7 + 1 : " + (char)(ch7 + 1));
char ch8 = 'A';
char ch9 = 'a';
System.out.println("'A' : " + ch8 + " - " + (int)ch8);
System.out.println("'a' : " + ch9 + " - " + (int)ch9);
// 1. 까마귀
// 2. 가마우지
// 3. 직박구리
// 2 - 1 - 3
// 1. cable
// 2. bible
// 3. able
// 3 - 2 - 1
// 1. aaAa
// 2. AaAa
// 3. AAaa
// 4. aAaA
// 3 - 2 - 4 - 1
// boolean(논리형) : 참(true), 거짓(false) -> 1 바이트
boolean b1 = true;
boolean b2 = false;
System.out.println("b1 : " + b1);
System.out.println("b2 : " + b2);
System.out.println(10 < 20);
System.out.println(10 > 20);
boolean b3 = 10 < 20;
System.out.println("b3 : " + b3);
// String 타입
// primitive 타입 아닙니다!!
String name = "Hong"; //String literal은 " ~ "
String nick = "Thunder";
System.out.println("이름은 : " + name + "\n별명은 : " + nick);
} // end main()
} // end class
4) com.lec.java.casting 패키지, CastingMain 클래스
package com.lec.java.casting;
/*
* 암묵적 형변환(Implicit casting): 자바 언어가 자동으로 해주는 형변환
*
* primitive type 에서 implicit casting 방향
*
* byte → short → int → long → float → long
* ↑
* char
*
* 명시적 형변환(Explicit casting): 프로그래머가 직접 타입을 변환하는 것
*
* (변환하고자 하는 타입명)변수/값
*
*
*
*/
public class CastingMain {
public static void main(String[] args) {
System.out.println("형변환(Type Casting/ Type Converting)");
byte num1 = 123;
int num2 = 123;
//byte num3 = num2; // 자동형변환 불가
// Type Mismatch: cannot convert from int to byte
byte num3 = (byte) num2; // 명시적형변환!
System.out.println("num3 : " + num3);
// 명시적 형변환시 주의점!! --> 데이터 손실 발생 주의!
byte num5 = (byte)513;
System.out.println("num5 : " + num5); // 1
double avg1 = (99 + 88 + 78) / 3;
System.out.println("avg1 : " + avg1);
double avg2 = (double)(99 + 88 + 78) / 3;
System.out.println("avg2 : " + avg2);
double avg3 = (99 + 88 + 78) / 3.0;
System.out.println("avg3 : " + avg3);
} // end main()
} // end class
5) com.lec.java.constant 패키지, ConstantMain 클래스
package com.lec.java.constant;
/*
* 상수 : final
* 변수 선언 앞에 final 키워드를 사용하면
* '상수 (constant)' 가 되어.
* 한번 값을 대입하면 변경할수 없게 된다.
*
* 관례적으로 상수값을 담는 상수명은 대문자로 작성
*/
public class ConstantMain {
public static void main(String[] args) {
int myage= 35;
myage = 40;
myage = 23;
final int MYAGE = 35;
//MYAGE = 21; // 에러, 상수임, 한 번 값을 대입하면 수정 불가능
// The final local MYAGE cannot be assigned.
// It must be black and not using a compound assignment
final short MYAGE2;
MYAGE2 = 100; // 초기화
//MYAGE2 = 200; // 에러, 상수임, 한 번 값을 대입하면 수정 불가능
// The final local variable MYAGE2 may already have been assigned
} // end main()
} // end class
6) com.lec.java.printf 패키지, PrintFormatMain 클래스
package com.lec.java.printf;
/* 서식화된 문자열 (formatted string)
* ● 화면에 출력할때는 -> printf()
*
* printf("서식문자열", 값1, 값2....)
*
* ● 문자열(String)으로 만들때는 -> String.format()
*
* String.format("서식문자열", 값1, 값2....)
*
* ● format specifier (서식 지정자)
* %d : 십진수 정수로 출력
* %f : 실수 출력
* %s : 문자열 출력
* %c : '문자하나' 출력
* %x : 16진수 정수로 출력
* %% : % 출력
*/
public class PrintFormatMain {
public static void main(String[] args) {
System.out.println("서식화된 출력 : printf(), String.format()");
double pi = Math.PI; // 원주율 값
System.out.println(pi);
// printf : print with format
// printf("서식문자열", 값1, 값2, ...)
// '서식문자열' 안에는 %로 시작하는 '서식지정자'들
System.out.printf("원주율");
System.out.printf("원주율");
System.out.printf("원주율\n");
System.out.printf("원주율 %f\n", pi);
System.out.printf("원주율 %.2f\n", pi);
int age = 10;
short grade = 3;
System.out.printf("제 나이는 %d살입니다. 학년은 %d학년입니다.\n", age, grade);
// 소숫점 이하 제한
double height = 182.3;
System.out.printf("저는 %d살입니다. 키는 %fcm입니다.\n", age, height);
System.out.printf("저는 %d살입니다. 키는 %.1fcm입니다.\n", age, height);
// 출력폭 지정, 좌우 정렬
System.out.printf("|%d|%d|%d|\n", 100, 200, 300);
System.out.printf("|%5d|%5d|%5d|\n", 100, 200, 300); // 출력폭 5칸, 우측 정렬(기본)
System.out.printf("|%-5d|%-5d|%-5d|\n", 100, 200, 300); // 출력폭 5칸, 좌측 정렬
System.out.printf("제 이름은 [%10s] 입니다. 혈액형은 %c 형입니다.\n", "봉준호", 'B');
// % 출력
double rate = 134423.0 / 345678.0;
System.out.printf("합격률은 %.1f%%입니다.\n", rate);
// 숫자에 패딩
System.out.printf("|%05d|%05d|%05d|\n", 100, 200, 300);
// format 문자열을 따로 설정해서 운영, printf를 이용해 화면 출력용으로 사용
String fmt = "주소 : %s, 우편번호[%05d]";
System.out.printf(fmt + "\n", "서울", 12345);
System.out.printf(fmt + "\n", "광주", 44);
System.out.printf(fmt + "\n", "대구", 776);
System.out.println();
// String.format(), 화면 출력용이 아님 -> 문자열 만드는 용이다!
String.format("합격률은 %.1f%% 입니다.", rate);
String result = String.format("합격률은 %.1f%% 입니다.", rate);
System.out.println(result);
} // end main()
} // end class
2. Lec04_input
1) com.lec.java.input01 패키지, Input01Main 클래스
package com.lec.java.input01;
import java.util.Scanner;
/*
* 표준 입력(Standard Input) : 키보드로부터 입력
* Scanner 객체 사용
*
* 표준 출력(Standard Output) : 모니터로 출력
*/
public class Input01Main {
public static void main(String[] args) {
System.out.println("표준 입력 : Scanner 사용");
Scanner sc = new Scanner(System.in); // import 필요, Scanner 객체 생성
// Scanner 사용한 입력 작업
int num1, num2;
System.out.print("숫자1을 입력하세요 : ");
num1 = sc.nextInt(); // 키보드로부터 int 입력
System.out.print("숫자2을 입력하세요 : ");
num2 = sc.nextInt();
System.out.println(num1 + " + " + num2 + " = " + (num1+num2));
System.out.printf("%d + %d = %d\n", num1, num2, num1 + num2);
// nextInt()에서 문자나 다른 것을 입력하면 InputMismatchException 발생
// 각 primitive 타입에 대해 nextXXX() 메소드 제공
// 주의!! sc.nextChar()는 없다!! -> sc.next().charAt(0)
// sc.nextByte();
// sc.nextShort();
// sc.nextLong();
// sc.nextFloat();
// sc.nextDouble();
// sc.nextBoolean();
sc.close(); // Scanner 객체를 사용한 뒤에는 반드시 close()를 해주자.
} // end main
} // end class
2) com.lec.java.input02 패키지, Input02Main 클래스
package com.lec.java.input02;
import java.util.Scanner;
// Ctrl + Shift + O : 자동 import
// 문자열(String) 입력
// char 입력
public class Input02Main {
public static void main(String[] args) {
System.out.println("표준입력 : String, char");
Scanner sc = new Scanner(System.in);
// // String 입력
// System.out.print("이름을 입력하세요 : ");
// String name = sc.nextLine(); // 엔터를 입력할때까지의 모~든 문자들을 문자열로 리턴
//
// System.out.print("별명을 입력하세요 : ");
// String nick = sc.nextLine();
//
// //System.out.println("이름: " + name + "\n별명: " + nick);
//
// // char 입력
// // .nextChar()이라는 명령 없다!
// System.out.print("성별을 입력하세요 M/F : ");
// char gender = sc.next().charAt(0);
// System.out.println("이름: " + name + "\n별명: " + nick + "\n성별: " + gender);
//
// System.out.println();
// 주소를 입력받지 않고 곧바로 출력이 되는 문제가 발생
// 할 일이 많은 CPU는 실시간 처리하지 않는다.
// [그렇기 때문에] 사용자에게 입력받은 데이터를 키보드 버퍼에 저장해서 한 번에 처리를 한다
// [ex] 8 8 공백
// nextInt는 숫자만 빼감, 88
// nextLine는 남아 있는 공백을 가져감과 동시에 비어있는 문자열을 갖게 됨
// 그런 이유로 주소를 입력받지 않은 상태에서 바로 출력이 됨
System.out.println("나이를 입력하세요 : ");
int age = sc.nextInt();
// 숫자 입력 받은 뒤에 문자열 입력시에는 반드시 '\n'을 consume(버퍼에서 제거) 해야 한다.
// 어떻게? sc.nextLine();를 이용
sc.nextLine();
System.out.println("주소를 입력하세요 : ");
String addr = sc.nextLine();
System.out.println("나이: " + age + "\n주소: " + addr);
sc.close();
} //end main()
} // end class
** 주소를 입력받지 않고 곧바로 출력이 되는 문제가 발생
** 할 일이 많은 CPU는 실시간 처리하지 않는다.
[그렇기 때문에] 사용자에게 입력받은 데이터를 키보드 버퍼에 저장해서 한 번에 처리를 한다
** 둘 다 가능
** 둘 다 가능
3) com.lec.java.input03 패키지, Input03Main 클래스
package com.lec.java.input03;
import java.util.Scanner;
public class Input03Main {
public static void main(String[] args) {
System.out.println("nextLine() vs next()");
Scanner sc = new Scanner(System.in);
// nextLine()
// '\n' 까지 한 라인 전체를 입력 받음
System.out.print("여러 단어의 문장을 입력>");
String line = sc.nextLine();
System.out.println("line : " + line);
// next()
// 다음 단어(token)을 받아서 String으로 결과 리턴
System.out.print("여러 단어의 문장을 입력>");
String token1 = sc.next();
System.out.println("token1 : " + token1);
// next()를 또 실행시키면
// 기존의 버퍼에 담겨 있는 내용들이 담긴다.
String token2 = sc.next();
System.out.println("token2 : " + token2);
String token3 = sc.next();
System.out.println("token3 : " + token3);
// nextInt(), nextDouble(), ... <-- next()처럼 단어 단위로 동작 함.
// 따라서 숫자 타입도 여러 개를 '한 줄'로 입력 받을 수 있다.
System.out.println("숫자 3개(int, double, int)를 입력하세요>");
int i1 = sc.nextInt();
double d1 = sc.nextDouble();
int i2 = sc.nextInt();
System.out.println("i1, d1, i2 : " + i1 + ", " + d1 + ", " + i2);
sc.close();
} // end main()
} // end class
4) com.lec.java.input04 패키지, Input04Main 클래스
package com.lec.java.input04;
//일반적으로 프로그램에서 숫자입력하는 것이 처음에는 '문자열(String)' 형태다
//ex) 웹, 모바일앱..
//
//이를 숫자 타입으로 변환해야 산술 연산등이 가능해진다
//
//Integer.parseInt(문자열) --> int 로 변환
//Double.parseDouble(문자열) --> double 로 변환
import java.util.Scanner;
//Byte.parseByte(문자열)
//Short.parseShort(문자열)
//Long.parseLong(문자열)
//Float.parseFloat(문자열)
//Boolean.parseBoolean(문자열)
//문자열이 해당 타입으로 변환할수 없는 문자열이면 NumberFormatException 예외 발생 (에러)
public class Input04Main {
public static void main(String[] args) {
System.out.println("입력 : 문자열 -> 숫자 변환");
Scanner sc = new Scanner(System.in);
System.out.print("숫자 3개(int, int, int)를 입력하세요>");
//int i1 = sc.next(); // 에러, 문자열을 int에 담을라고 해서
// 해당 에러를 해결하기 위해서는 문자열을 int로 바꿔해야 해!
String in1 = sc.next();
int i1 = Integer.parseInt(in1);
int i2 = Integer.parseInt(sc.next());
int i3 = Integer.parseInt(sc.next());
System.out.println("합 : " + (i1 + i2 + i3));
// Q. 실수 3개를 문자열로 입력받아서(next())
// 3개의 실수의 곱을 계산하여 출력하세요
System.out.println("숫자 3개(double, double, double)를 입력하세요>");
double d1 = Double.parseDouble(sc.next()); //입력받은 문자열을 double로 변환
double d2 = Double.parseDouble(sc.next());
double d3 = Double.parseDouble(sc.next());
System.out.println("곱 : " + (d1 * d2 * d3));
sc.close();
} // end main()
} // end class
3. Lec05_Operator
1) com.lec.java.operator01 패키지, Operator01Main 클래스
package com.lec.java.operator01;
/*
* 연산자 관련 일반사항
*
* 연산 Operation
* 연산자 Operator
* 피연산자 Operand
*
* ■ 피연산자의 개수에 따라
* 이항연산자(binary operator) : 피연산자가 2개인 연산자
* 단항연산자(unary operator) : 피연산자가 1개인 연산자
* 삼항연산자(ternary operator) : 피연산자가 3개인 연산자
*
* ■ 연산자는 연산을 수행하기 전에 피연산자의 타입을 일치시키려 한다.
*
* ■ 피연산자의 타입에 따라 수행하는 연산이 달라지는 연산자들도 있다 (ex: + )
*
* ■ 모든 연산은 연산의 결과값을 리턴한다 (어떠한 '값'인지?, 어떤 '타입'인지? 주목)
*
* ■ 관례적으로 이항연산자는 피연산자와 연산자 간에 한칸씩(space) 띄어주는게 좋다
* 단항연산자는 피연산자와 연산자를 붙여주는게 일반.
*/
/*
대입 연산자 assignment operator : =
등호(=) 오른쪽의 값을 왼쪽에 대입(저장)
산술 연산자 arithmetic operator : +, -, *, /, %
*/
public class Operator01Main {
public static void main(String[] args) {
System.out.println("연산자(Operator) 01");
System.out.println("\n====================");
System.out.println("[1] 대입 연산자 : = (assignment operator)");
// 등호(=) 오른쪽의 값을 왼쪽에 대입(저장)
int num = 123;
System.out.println("num = " + num);
System.out.println("\n====================");
System.out.println("[2] 산술 연산자: +, -, *, /, % (arithmetic operator)");
int num1 = 7;
int num2 = 3;
int result;
result = num1 + num2;
System.out.println("덧셈 결과 : " + result);
result = num1 - num2;
System.out.println("뺄셈 결과 : " + result);
result = num1 * num2;
System.out.println("곱하기 결과 : " + result);
result = num1 / num2;
System.out.println("나눈 몫 : " + result);
result = num1 % num2; // 나머지 연산
System.out.println("나머지 : " + result);
// 나눗셈 연산자(/)가 실수에 사용됐을 경우에는
// 계산 결과를 실수로 돌려 줌.
// 실수 / 정수, 정수 / 실수, 실수 /실수 경우에는 결과가 항상 실수형이 됨
double result2 = 12.0 / 3;
System.out.println("실수 나누기 결과 : " + result2);
// 나머지 연산자(%)
// 정수 % 정수 = 정수로 값을 돌려 줌.
// 실수 % 정수, 정수 % 실수, 실수 % 실수 = 몫을 제외한 실수형 나머지를 돌려줌.
double result3 = 12.1 % 3.0;
System.out.println("나머지 연산 결과 : " + result3);
// 두 변수 값 바꾸는 방법
int num3 = 100;
int num4 = 200;
int temp; //임시 변수
System.out.println("바꾸기 전 num3 = " + num3 + " num4 = " + num4);
temp = num3;
num3 = num4;
num4 = temp;
System.out.println("바꾼 후 num3 = " + num3 + " num4 = " + num4);
// 대입연산자도 연산자다! 따라서
// 연산의 결과값이 있다. 대입된 값을 결과값으로 리턴함
int num5;
int num6;
System.out.println("num5 : " + (num5 = 100));
//우에서 좌로 실행, num5에 300 대입된 다음 num6에 300이 대입됨
num6 = num5 = 300;
System.out.println("num5 : " + num5);
System.out.println("num6 : " + num6);
System.out.println("\n프로그램 종료");
} // end main()
} // end class
2) com.lec.java.operator02 패키지, Operator02Main 클래스
package com.lec.java.operator02;
/* 복합 대입 연산자 compound assignment operators
*
* +=, -=, *=, /=, %=, ...
*/
public class Operator02Main {
public static void main(String[] args) {
System.out.println("연산자(Operator) 2 - 복합 대입 연산자 compound assignment operators");
System.out.println("+=, -=, *=, /=, %=, ...");
int num1 = 10;
System.out.println("num1 = " + num1);
num1 = num1 + 1; // 기존의 num1 값에 1증가
System.out.println("num1 = " + num1);
num1 += 1; // 복합 대입연산자
System.out.println("num1 = " + num1);
int num3 = 123;
num3 -= 23;
System.out.println("num3 = " + num3);
double num4 = 3.14;
num4 *= 2;
System.out.println("num4 = " + num4);
double num5 = 3.14;
num5 /= 2;
System.out.println("num5 = " + num5);
System.out.println("\n프로그램 종료");
} // end main()
} // end class
3) com.lec.java.operator03 패키지, Operator03Main 클래스
package com.lec.java.operator03;
/*
* 부호연산자(+, -) sign operator '대표적인 단항 연산자'
* +: 부호 연산자(수의 부호(양,음)가 바뀌지 않음)
* -: 부호 연산자(수의 부호(양,음)가 바뀜)
*/
// Ctrl + Shift + f : 자동으로 들여쓰기, 띄어쓰기 규칙에 맞게 정리해줌
public class Operator03Main {
public static void main(String[] args) {
System.out.println("연산자 3 - 부호연산자(+, -) sign operator");
int num1 = -10;
int num2 = +num1;
int num3 = -num1;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("num3 = " + num3);
int num4 = 11;
int num5 = -22;
int num6 = num4 + -num5;
System.out.println("num6 = " + num6);
int num7 = num4 - -num5;
System.out.println("num7 = " + num7);
System.out.println("\n프로그램 종료");
} // end main
} // end class
4) com.lec.java.operator04 패키지, Operator04Main 클래스
package com.lec.java.operator04;
/* 증감 연산자(++, --) Increment / Decrement Operator
* ++변수: 변수의 값을 1 증가시켜서 저장
* --변수: 변수의 값을 1 감소시켜서 저장
*
* 증감연산자: prefix(접두사), postfix(접미사)
* 접두사(prefix)인 경우에는, 증감(++, --)이 먼저 된 후 다른 연산자가 동작
* 접미사(postfix)인 경우에는, 다른 연산자 먼저 실행된 후 증감(++, --)가 동작
*/
public class Operator04Main {
public static void main(String[] args) {
System.out.println("연산자 4 - 증감 연산자(++, --) Increment / Decrement Operator");
int num1 = 100;
System.out.println("num1 = " + num1);
// ++ : 변수값 1증가
++num1;
// num1 = num1 + 1와 동일한 결과
// num1 += 1와 동일한 결과
System.out.println("num1 = " + num1);
// -- : 변수값 1감소
int num2 = 100;
--num2;
// num2 = num2 - 1와 동일한 결과
// num2 -= num2와 동일한 결과
System.out.println("num2 = " + num2);
num2--;
num2--;
System.out.println("num2 = " + num2);
System.out.println("\n\n======================");
System.out.println("증감연산자: prefix(접두사), postfix(접미사)");
int num4 = 100;
int num5 = ++num4; // prefix, 대입연산자= 보다 ++가 먼저 수행된다.
System.out.println("num4 = " + num4);
System.out.println("num5 = " + num5);
int num6 = 100;
int num7 = num6++; // postfix
System.out.println("num6 = " + num6);
System.out.println("num7 = " + num7);
System.out.println();
int num8 = 10;
int num9 = --num8 + 5;
System.out.println("num8 = " + num8);
System.out.println("num9 = " + num9);
int num10 = 10;
int num11 = num10-- + 5;
System.out.println("num10 = " + num10);
System.out.println("num11 = " + num11);
//---------------------------------------
int number1 = 10;
int number2 = number1-- + 5 + --number1;
// number1 ? 8
// number2 ? 23
// (1) number1에 저장된 값(10) + 5 -> 15
// (2) number1의 값이 1 감소 -> 9
// (3) 15 + --number1: number1의 값을 먼저 감소 -> 8
// (4) 15 + 8 -> 23
// (5) number2에 23이 저장
// ★ 그러나, 실무에서는 절대로 이런 코드는 작성하지 마십시오.
System.out.println("\nnumber1? " + number1);
System.out.println("number2? " + number2);
System.out.println("\n프로그램 종료");
} // end main
} // end class
5) com.lec.java.operator05 패키지, Operator05Main 클래스
package com.lec.java.operator05;
/*
관계(비교) 연산자 Equality and Relational Operators
비교 연산의 결과를 참(true) 또는 거짓(false)으로 리턴하는 연산자
A < B: A는 B보다 작다
A > B: A는 B보다 크다
A >= B: A는 B보다 크거나 같다
A <= B: A는 B보다 작거나 같다
A == B: A와 B가 같다. (대입연산자=와 헷갈리지 말자)
A != B: A와 B는 다르다.
*/
public class Operator05Main {
public static void main(String[] args) {
System.out.println("연산자 5 - 관계(비교) 연산자 Equality and Relational Operators");
System.out.println("<, >, <=, >=, ==, !=");
System.out.println(10 < 20);
System.out.println(10 > 20);
int n1 = 11;
int n2 = 12;
boolean b2 = n1 != n2;
System.out.println("b2 = " + b2);
// 실수타입은 연산 결과값을 비교연산자로 같은지 비교하면 안된다.
double d1 = 3.2;
double d2 = 12.3 / 4.1 + 0.2;
System.out.println(d1 == d2);
System.out.println(d1);
System.out.println(d2);
System.out.println("\n프로그램 종료");
} // end main()
} // end class
6) com.lec.java.operator06 패키지, Operator06Main 클래스
package com.lec.java.operator06;
/* 논리 연산자: &&, ||, !, ^
* A && B: (AND 연산) A와 B가 모두 참일 때만 결과가 true, 나머지는 결과가 false
* A || B: (OR 연산) A나 B 둘 중 하나가 참이면 결과가 true, 둘 다 거짓이면 결과가 false
* !A : (NOT 연산) A가 참이면 결과가 false, 거짓이면 결과가 true
* A ^ B : (XOR 연산, 배타적 논리합) A, B 둘의 논리값이 같으면 false, 다르면 true
*/
public class Operator06Main {
public static void main(String[] args) {
System.out.println("연산자 6 - 논리 연산자: &&, ||, !, ^");
int num1 = 10;
boolean result;
result = num1 > 0 && num1 < 100;
System.out.println(result);
result = num1 > 0 && num1 < 10;
System.out.println(result);
result = num1 > 0 || num1 < 10;
System.out.println(result);
result = num1 < 0 || num1 < 10;
System.out.println(result);
result = !(num1 > 0);
System.out.println(result);
result = num1 < 0 ^ num1 > 100;
System.out.println(result);
System.out.println("\n 프로그램 종료");
} // end main ()
} // end class
7) com.lec.java.operator07 패키지, Operator07Main 클래스
package com.lec.java.operator07;
/* 게으른 계산(Lazy Evaluation)
* SCE: Short-Circuit Evaluation
*
* A && B를 계산할 때
* A가 거짓이면, B의 결과에 상관 없이 결과가 항상 거짓이 되기 때문에
* B는 연산이 이루어지지 않는다.
*
* A || B를 계산할 때
* A가 참이면, B의 결과에 상관 없이 결과가 항상 참이 되기 때문에
* B는 연산이 이루어지지 않는다.
*/
public class Operator07Main {
public static void main(String[] args) {
System.out.println("게으른 계산(Lazy Evaluation)");
System.out.println("SCE: Short-Circuit Evaluation");
int num1 = 0, num2 = 0;
boolean b;
b = (num1 += 10) < 0 && (num2 += 10) > 10;
System.out.println("b = " + b);
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// ↑ 실무에서는 위와 같은 코드 작성하지 말자!!
num1 += 10;
num2 += 10;
b = (num1 < 0) && (num2 > 10);
System.out.println("\nb = " + b);
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("\n 프로그램 종료");
} // end main ()
} // end class
8) com.lec.java.operator08 패키지, Operator08Main 클래스
package com.lec.java.operator08;
/* 비트 연산자 (bit-wise operator)
* a & b: (and) a,b가 모두 1 이면 결과도 1, 그 외에는 0
* a | b: (or) a가 1이거나 또는 b가 1이면 결과는 1, a,b 모두 0일 때만 0
* a ^ b: (xor) a와 b 둘 중 하나만 1이 있는 경우는 1, 그 외에는 0
* 결국 둘이 같으면 0, 다르면 1
* ~a : (not) a가 1이면 0, a가 0이면 1로 바꿔줌
*/
public class Operator08Main {
public static void main(String[] args) {
System.out.println("연산자 8 - 비트 연산자");
System.out.println("[1] &(and), |(or), ^(exclusive or), ~(not)");
byte n1 = 10; // 0000 1010
byte n2 = 7; // 0000 0111
// &---------------
// 0000 0010
int result = n1 & n2; //AND
System.out.println("&결과 = " + result);
System.out.println("&결과 = " + Integer.toBinaryString(result));
result = n1 | n2; //OR
System.out.println("|결과 = " + result);
System.out.println("|결과 = " + Integer.toBinaryString(result));
result = n1 ^ n2; //XOR
System.out.println("^결과 = " + result);
System.out.println("^결과 = " + Integer.toBinaryString(result));
result = ~n1; // 0000 1010
// ~-----------
// 1111 0101
System.out.println("~결과 = " + result);
System.out.println("~결과 = " + Integer.toBinaryString(result));
// 음수 정수 표현 참조 : http://tcpschool.com/c/c_refer_negativeNumber
System.out.println("\n\n================");
System.out.println("비트 이동(shift) 연산자: >>, <<");
int n3 = 10; // 0000 1010
// 0000 0101
int result2 = n3 >> 1; // 비트를 오른쪽으로 1bit 이동
System.out.println(">> 결과 = " + result2);
System.out.println(">> 결과 = " + Integer.toBinaryString(result2));
result2 = n3 << 1; // 비트를 왼쪽으로 1bit 이동
System.out.println("<< 결과 = " + result2);
System.out.println("<< 결과 = " + Integer.toBinaryString(result2));
// 같은 결과값을 도출하지만 비트 연산자가 훨씬 더 빠름
System.out.println(n3 << 1);
System.out.println(n3 * 2);
System.out.println(n3 >> 1);
System.out.println(n3 / 2);
System.out.println("\n 프로그램 종료");
} // end main ()
} // end class
9) com.lec.java.operator09 패키지, Operator09Main 클래스
package com.lec.java.operator09;
/* 산술 연산의 결과 타입
*
* 일단 피연산자가 reference type 이면, unbox 후 형변환 수행됨. 그리고 나서
* 피연산자중 하나라도 double 이면 다른쪽이 double 이 된다.
* 그렇지 않으면 피연산자중 하나라도 float 이면 다른 쪽이 float 가 된다.
* 그도 아니면 피연산자중 하나라도 long 이면 다른 쪽을 long 으로 바꾼다.
* 그도 아니면 양쪽 피연산자 모~ 두 int 로 바꾼다.
*
* https://docs.oracle.com/javase/specs/#5.6.2
* When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
* If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
* If either operand is of type double, the other is converted to double.
* Otherwise, if either operand is of type float, the other is converted to float.
* Otherwise, if either operand is of type long, the other is converted to long.
* Otherwise, both operands are converted to type int.
*/
public class Operator09Main {
public static void main(String[] args) {
System.out.println("산술연산의 결과 타입");
int n1 = 10, n2 = 20;
int n3 = n1 + n2;
System.out.println("n3: " + n3);
byte b1 = 10, b2 = 20;
// byte b3 = b1 + b2; // byte + byte -> int
// byte b3 = b1 + 20;
short s1 = 10, s2 = 20;
//short s3 = s1 + s2; // short + short -> int
// short s3 = b1 + s1; // byte + short -> int
char ch1 = 10, ch2 = 20;
//char ch3 = ch1 + ch2; // char + char -> int
char ch3 = (char)(ch1 + ch2); // 따라서 명시적 형변환
long l1 = 10L;
//int n4 = n1 + l1; // int + long -> long
float f1 = 1.0f, f2 = 2.0f;
float f3 = f1 + f2; // OK
f3 = f1 + n1;
f3 = f1 + b1;
double d1 = 1.0, d2 = 2.0;
double d3 = d1 + d2;
d3 = d1 + f1;
//f3 = f1 + d1; // float + double --> double
// int 이하 끼리 연산결과 무조건 int 이기 때문에 주의!
long l2 = 27000000000L;
System.out.println("l2 : " + l2);
l2 = 3000 * 3000 * 3000;
System.out.println("l2 : " + l2);
// 자바 의 연산결과 타입규칙과
// 기본데이터 타입의 한계값 인지하고 있어야 함.
// 복합대입연산자
int sum = 0;
double d4 = 1.2;
//sum = sum + d4;
sum += d4; // 에러 안난다??
System.out.println(sum);
// sum += d4 복합대입연산자는
// sum = sum + d4 가 아니라...
// sum = (int)(sum + d4) 으로 동작함
System.out.println("\n 프로그램 종료");
} // end main ()
} // end class
'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글
2020.03.20 (0) | 2020.03.20 |
---|---|
2020.03.19 (0) | 2020.03.19 |
2020.03.18 (0) | 2020.03.18 |
2020.03.16 (0) | 2020.03.16 |
학습목표 및 일정(3월 16일 ~ 8월 06일) (0) | 2020.03.16 |