기록

20220727 수업기록 본문

수업기록(2022-07~2022-09) JAVA

20220727 수업기록

연삐 2022. 7. 27. 21:46
07-27(수) 수업진도

1.데이터타입
-실수리터럴
-정수리터럴

-boolean타입

2.타입변환
-promotion
-casting

3.변수 lifecycle

4.연산자와 연산식
-산술연산자
-할당연산자
-논리연산자
-비교연산자
-단항연산자
-3항연산자
-연산자우선순위

1.데이터타입

  • 실수리터럴
    • 실수를 표현할수있는 데이터타입은 float(4byte),double(8byte)가있다.
    • 실수의 데이터타입은 부호:sign(+,-), 가수:mantissa, 지수:exponent 
    • float은 
      sign1bit 
      exponent 8bit 
      mantissa 23bit  총 32bit로 4byte
    • double은 
      sign1bit 
      exponent 11bit 
      mantissa 52bit  총 64bit로 8byte
    • double의 소숫점bit수(mantissa)가 많기때문에 
      긴소숫점값을 표현할때는 double이 더 정밀하게 표현이 된다.
package p02.datatypes_basic;

// 실수값 literal의 기본type은 double임
// - 실수 literal은 float type에 넣을 경우에는 literal값 끝에 'f'를 붙임
//   예 : 3.14f 의미 : 3.14값을 float type인 4byte로 생성해달라는명령어
public class FloatDoubleEx {

	public static void main(String[] args) {
		 double var1 =3.14;
//		 float var2 = 3.14; //error
		 //flat은 4byte 3.14는 8byte
		 float var3 = 3.14f; // f(F): float 표시는 대/소문자 상관없음
		 double var4 = 0.1234567890123456789;
		 float var5 = 0.1234567890123456789f;
		 
		 System.out.println("var1 = "+ var1);
		 System.out.println("var3 = "+ var3);
		 System.out.println("var4 = "+ var4);
		 System.out.println("var5 = "+ var5);
		 
		 double var6 = 3e6;  // 3*10^6 , E : Exponential 
		 float var7 = 3e6F; 
		 double var8 = 2e-3; // 3*10^-3
		 
		 System.out.println("var6 = "+ var6);
		 System.out.println("var7 = "+ var7);
		 System.out.println("var8 = "+ var8);
		 

	}

}
  • 정수리터럴
    • 정수로 표현할수있는 데이터타입은 byte(1byte),char(2byte),short(2byte),int(4byte),long(8byte)가 있다.
package p02.datatypes_basic;

//int literal
// 1. 10진수, 8진수, 16진수 사용 가능
// 2. 16진수 (하드웨어와 연계된 프로그램, 통신프로그램)에서 많이 사용함
public class intEx {

	public static void main(String[] args) {
		int var1 = 10;
		int var2 = 012; //8진수 : 첫번쨰에 0을 넣으면 8진수
		int var3 = 0xA; //16진수 : 첫번째에 0x를 넣으면 16진수
		//실무에선 잘 사용하지않지만 통신프로그램에서 16진수를 사용함
		
		System.out.println("var1 = "+var1);
		System.out.println("var2 = "+var2);
		System.out.println("var3 = "+var3);
	}

}
package p02.datatypes_basic;


//정수 type literal : 기본은 4byte임
//long type literal로 만들고 싶으면 정수값 끝에 'L'또는'l'을 붙이면 되고, 이때 8byte로 메모리에 만듬

public class longEx {

	public static void main(String[] args) {
		//기계어로 변환
		// 1. 10을 4byte로 메모리에 생성
		// 2. long type인 var1에 넣기 위해 4byte로 된 것을 8byte로 확장하여 var1에 넣음
		long var1 = 10; //10 : 4 byte에 만듬 
		//작은값이 큰바이트방으로 넘어가기때문에 error가 발생안함.
		long var2 = 10L; // 10L : 8 byte에 만듬
//		long var3 = 10000000000000; //error. out of range
		long var3 = 10000000000000L;
		
		System.out.println("var1 = "+var1);
		System.out.println("var2 = "+var2);
		System.out.println("var3 = "+var3);
		

	}

}
package p02.datatypes_basic;

// char type : 문자 한글자를 관리하기 위한 타입(2byte)
// 문자 예 : 'A','1','가',...(정수와는 다름)
// -모든 문자를 unicode로 저장 
// 1.ASCII(American Standard Code Information Interchange) code table
//   -키보드의 숫자, 영문자 대문자/소문자, 특수기호 등에 대하여 2진수 코드로 매핑한 것
// 2.Unicode 코드 테이블 : 2bytes
// 	 -영어 ASCII코드 테이블 포함한 한국어, 중국어, 일어, 독일어, 기타 동남아, 아프리카 등 전세계 언어의 문자를 코드화한것
public class CharEx {

	public static void main(String[] args) {
		char c1 = 'A'; 
		char c2 = 65; 	//10진수 정수값 입력
		char c3 = '\u0041'; //16진수 정수값 입력 , \.u : Uni_code를 의미 ,유니코드로0041이라는뜻
							//16진수 한자리 bit값은 4bit
		
		char c4 = '가';
		char c5 =  44032; //10진수 정수값 입력
		char c6 = '\uac00';  //16진수 정수값 입력
		
		
		System.out.println("c1 = "+c1);
		System.out.println("c2 = "+c2);
		System.out.println("c3 = "+c3);
		System.out.println("c4 = "+c4);
		System.out.println("c5 = "+c5);
		System.out.println("c6 = "+c6);
		
		
	}

}
package p02.datatypes_basic;

// byte  : 1byte의 데이터값만 저장 가능 (-128~127)
// - byte type은 사용 권장 안함 (메모리절약을위해서 사용했던 데이터타입


public class ByteEx {

	public static void main(String[] args) {
		byte var1 = -128;
		byte var2 = -30;
		byte var3 = 0;
		byte var4 = 30;
		byte var5 = 127;
//		byte var6 = 128;
		
		System.out.println("var1 = "+ var1);
		System.out.println("var2 = "+ var2);
		System.out.println("var3 = "+ var3);
		System.out.println("var4 = "+ var4);
		System.out.println("var5 = "+ var5);

	}

}
  • boolean 타입
    • true와 false만 사용가능
    • 제어문과 반복문에서 사용한다.
    •  
package p02.datatypes_basic;

// boolean type:
// 1. literal 값이 true, false만 사용가능
// 2. 제어문(if, switch) 또는 반복문(while,for 등) 에서 사용한다.
// 3. 현실세계에서는 필요없는 데이터 type이지만, 프로그래밍할 떄는 핵심 타입

public class booleanEx {
	

	public static void main(String[] args) {
		boolean stop = true;
		boolean start = false;
		
		System.out.println("stop = "+stop);
		System.out.println("start = "+start);
	
		
	//stop이 참이면 중지합니다, 거짓이면 시작합니다를 display한다.
	if(stop) {
		System.out.println("중지합니다.");
	}else {
		System.out.println("시작합니다.");
	}
	}

}

2.타입변환

타입변화은 cpu때문에 발생하는 현상

  • 자동형변환 promotion (승진,승격)
    • 작은데이터 타입에서 큰 데이터타입으로 '자동'변환 시켜준다.
    • int -> long / int -> float   //정수값이 실수값으로 변환되는것도 프로모션이라한다.
    • byte(1) < short(2) < int(4) < long(8) < float(4) < double(8)
    • 서로 다른 타입의 피연산자는 같은 타입으로 변환
    • 두 피연산자 중 크기가 큰 타입으로 자동 변환
    • int 보다 작은 타입으로 산술연산할때 int로 자동변환
    • long과 그 밑에 작은 타입으로 연산할때 long으로 자동변환
    • double타입과 다른 타입으로 산술연산할때 모두 double타입으로 자동변환 ( 8 byte)
package p03.datatypes_promotion;

//1.정수형 산술연산 (+, -, *, / , 등)에서의 데이터타입 자동컨버전(promotion)
//  - int보다 작은 byte, short, char을 사용하여 산술연산을 수행하면 무조건 int타입으로 자동형변환 시킴
//2.long type이나, float,double등의 타입과 다른 타입의 산술연산을 수행하면 큰 데이터타입으로 자동형변환시킴

public class TypeConversionInExpressionEx {

	public static void main(String[] args) {
		byte b1 = 42;
		byte b2 = 10;
		byte sum;
		char c1 = 20;
		char c2 = 30;
		char csum;
		int isum;
		long l1 = 15;
		long result;
		double dresult; 
		
		//b1 + b2를 수행할 때 기게어로 표현
		//1.byte type인 b1을 int type으로 promotion시킴 (즉, 1byte->4byte 크기로 확장)
		//2.byte type인 b2를 int type으로 promotion시킴 
		//3.b1+b2를 수행
		//4.int type인 결과값을 byte type인 sum에 넣으려니까 error가 발생
//		sum = b1 + b2; //error발생
		sum = (byte) (b1 + b2); //(byte) : casting (강제형변환)
//		csum = c1 + c2; //error발생
		isum = b1+b2;
		
		//기계어로 표현
		//1. b1 + c1 연산하여 int type으로 변환하여 메모리에 4byte로 저장
		//2. b1 + c1의 결과값과  l1을 덧셈연산하기 위해서는 
		//   . 2.1 : b1+c1의 결과값을 8byte인 long type으로 변환(promotion 발생)
		//   . 2.2 l1가 덧셈 연산 수행
		//3. 최종값을 long type인 result에 넣음
		result = b1 + c1 + l1;

		//long type인 l1과 double type인 0.5를 더할 경우 기계어로는
		//1. l1을 double type으로 변환
		//2. 0.5을 더하여 연산결과가 double type으로 만듬
		
//		result = l1 + 0.5; //error double은 long으로 바꿀 수 없다.
		dresult = l1 + 0.5;

	}

}
package p03.datatypes_promotion;

public class PromotionEx {

	public static void main(String[] args) {
		byte byteValue =10;

		int intValue = byteValue; //1byte -> 4byte
		System.out.println("intValue = " + intValue);
		
		char charValue = '가';
		
		intValue = charValue; 
		System.out.println("intValue = " + intValue);
		
		intValue = 500;
		
		long longValue = intValue;
		System.out.println("longValue = " + longValue);
		
		float floatValue = longValue;
		System.out.println("floatValue = "+floatValue);
		
		double doubleValue = intValue;
		System.out.println("doubleValue = "+ doubleValue);
		
		

	}

}
(결과)
intValue = 10
intValue = 44032
longValue = 500
floatValue = 500.0
doubleValue = 500.0
  • 강제형변환 casting (던지는것, 작은곳으로 우겨서 집어 넣는다는 의미)
    • 큰데이터타입에서 작은 데이터 타입으로 '강제' 형변환 
    • (코딩할 때 강제 형변환 하겠다는 의사표현을 해줘야 함) 변수앞에 (데이터타입)입력
package p04.datatypes_casting;

//casting의 문제점
// - 큰 data type의 값이 작은 data type으로 변환되면서 데이터가 유실

public class CastingEx2 {
	
	public static void main(String[] args) {
		byte byteValue = 0;
		int intValue = 257;
		double doubleValue = 323.142;
		
//		byteValue = intValue; //error
		//4byte 데이터를 1byte만 남기고 전부 삭제
		byteValue = (byte)intValue; //data유실됨
		System.out.println("byteValue = " + byteValue);
		
//		intValue = doubleValue;//error
		intValue = (int) doubleValue;
		System.out.println("intValue = "+intValue);
		
	
		
	}

}
(결과)
byteValue = 1

int를 byte로 강제형변환할때 int의 10진수값이 2진수로 변환되어 byte가 저장할수있는 1byte(8bit)까지만 표현이가능하다
그래서 값이 1로 나온다.

intValue = 323

double을 int로 자동형변환할때 소숫점이 반올림이 되지않은상태로 소숫자리들은 데이터유실이된다.
package p04.datatypes_casting;

// 강제 형변환 할 때 사용하는 programming tip
// -casting가능한지 MIN_VALUE와 MAX_VALUE를 check하여 확인할 것
public class ByteTypeMunMaxCheckEx {
	
	public static void main(String[] args) {
		int num = 125;
		
		System.out.println("byte 최소값 : "+Byte.MIN_VALUE);
		System.out.println("byte 최대값 : "+Byte.MAX_VALUE);
		
		if((num<Byte.MIN_VALUE) || (num > Byte.MAX_VALUE)) {
			System.out.println("Byte타입으로 변환할 수 없습니다.");
		}else {
			byte bNum = (byte) num;
			System.out.println("bNum = "+bNum);
		}
	}

}
byte 최소값 : -128
byte 최대값 : 127
short 최소값 : -32768
short 최대값 : 32767
int 최소값 : -2147483648
int 최대값 : 2147483647
long 최소값 : -9223372036854775808
long 최대값 : 9223372036854775807
float 최소값 : 1.4E-45
float 최대값 : 3.4028235E38
double 최소값 : 4.9E-324
double 최대값 : 1.7976931348623157E308

3.변수 lifecycle

  • 변수가 생성되고 사용되고 소멸되는 과정
package p05.local_variable_scope;

//변수(variable)의 생명주기(life cycle) : 변수가 생성되고 사용되고 소멸되는 과정
//1.변수의 생명(존재) 유지하는 것은 메모리에 있을 경우에만 가능
//   - 변수가 메모리에 존재해야지만, 변수의 메모리값을 읽고, 메모리값을 수정할 수 있음
//2.java에서 변수의 생명 주기는 {}안에서만 살아 있음
//   - 예 : parentNum 변수는 main method안에서만 살아있음
//    		childNum 변수는 if문 안에서만 살아있음

public class LocalVariableScopeEx {
	
	public static void main(String[] args) {
		int parentNum = 20;
		
		if(parentNum > 10 ) {
			int childNum = parentNum -10;
			System.out.println("parentNum = "+parentNum);
			System.out.println("childNum = "+childNum);
			
		} //if문 안에 생성한 변수는 메모리에서 사라짐
		
		System.out.println("parentNum = "+parentNum);
		//childNum 변수가 if문안에서만 존재하여 if문 밖에서는 사용불가
//		System.out.println("childNum = "+childNum); //error
		
		
		{
			int a = 20;
			System.out.println("a = " + a);
		}
		
//		a = 30;  //error
		
	
	}
	
//	parentNum = 30; //error
	
}

4.연산자와 연산식

  • 산술연산자
    • +(덧셈),-(뺄셈),*(곱셈),/(나눗셈 (몫)),%(나눗셈 (나머지))
    • int / int = int
    • int / double = double
package p01.basic;

// +,=,*,/,% : 산술연산자 (arithmetic operator)
//
public class ArithmeticOperatorEx {

	public static void main(String[] args) {
		int a1 = 10;
		int a2 = 3;
		int result;
		double dresult;
		
		result = a1 + a2;
		System.out.println("result = " + result);
		
		result = a1 - a2;
		System.out.println("result = " + result);
		
		result = a1 * a2;
		System.out.println("result = " + result);
		
		result = a1 / a2; // /: 몫을 가져옴
		System.out.println("result = " + result);
		
		result = a1 % a2;// %: 나머지를 가져옴
		System.out.println("result = " + result);
		//산수의 결과값은 랭기지마다 다를 수 있다.
		
		//a2를 double로 자동 형변환시킴
		dresult = a1 / (double)a2; //int를 double로 나누면 double로 피연산자 모두 자동형변환된다 
		dresult = (double)a1 / a2;
		System.out.println("dresult = " + dresult);
	}

}
result = 13
result = 7
result = 30
result = 3
result = 1
dresult = 3.3333333333333335
  • 할당연산자
    • =,+= , -=, *=, /=, %=  
    • 연산이 간결해진다.
package p01.basic;

//Assignment Operator (할당 연산자)
//1. = 
//2. +=, -=, *=, /=, %=, ... => C language부터 사용된 표현방식


public class AssignmentOperatorEx {
	
	public static void main(String[] args) {
		int n1 =10;
		int n2 = n1;
		
		System.out.println("n1 = "+ n1);
		
//		n1 = n1 + 10;
		n1 += 10;
		System.out.println("n1 = "+n1);

//		n1 = n1 - 10;
		n1 -= 10;
		System.out.println("n1 = "+n1);

//		n1 = n1 * 3;
		n1 *= 2;
		System.out.println("n1 = "+n1);

//		n1 = n1 / 10;
		n1 /= 3;
		System.out.println("n1 = "+n1);

		
	}

}
  • 논리연산자
    • &&(AND연산자) , || (OR연산자), ! (NOT연산자)
package p01.basic;

// Logical Operator(논리연산자)
// 1. && (AND 연산자)
// 2. || (OR 연산자)
// 3. ! (NOT 연산자)

public class LogcalOperatorEx {

	public static void main(String[] args) {
		int a1 =10;
		int a2 = 20;
		int a3 = 20;
		int a4 = 0;
		boolean bResult;
		
		bResult = (a1 < a2 ) && (a2 == a3);
		System.out.println("bResult = "+ bResult);
		bResult = (a1 < a2 ) || (a2 == a3);
		System.out.println("bResult = "+ bResult);
		
		bResult = (a1 > a2 ) && (a2 == a3);
		System.out.println("bResult = "+ bResult);
		bResult = (a1 > a2 ) || (a2 == a3);
		System.out.println("bResult = "+ bResult);
		
		bResult = !(a1>a2);
		System.out.println("bResult = " + bResult);
		
		
	}

}
  • 비교연산자
    • ==(같다,true) , !=(틀리다,false) , >,<,>=,<=
package p01.basic;

// Relational Operator (비교 연산자)
// 1. == (예 : a == b : a와 b의 값이 같으면 true, 틀리면 false 가짐
// 2. != (예 : a != b : a와 b의 값이 틀리면 true, 같으면 false 가짐
// 3. >,>= 
//		(예 : a > b : a가 b보다 작으면 true, 같거나 크면 false 가짐)
//		(예 : a >= b : a가 b보다 작거나 같으면 true, 크면 false 가짐)
public class RelationalOperatorEx {

	public static void main(String[] args) {
		int a1 = 5;
		int a2 = 10;
		int a3 = 5;
		boolean bResult;
		
		System.out.println("a1 == a2 : " + (a1 ==a2));
		System.out.println("a1 == a3 : " + (a1 ==a3));
		
		bResult = (a1 == a2);
		System.out.println("bReasult = " + bResult);
		bResult = (a1 == a3);
		System.out.println("bReasult = " + bResult);
		
		System.out.println("a1 != a2 : " + (a1 !=a2));
		System.out.println("a1 != a3 : " + (a1 !=a3));
		
		System.out.println("a1 > a2 : " + (a1>a2));
		System.out.println("a1 < a3 : " + (a1<a3));
		
		System.out.println("a1 >= a2 : " + (a1>=a2));
		System.out.println("a1 <= a3 : " + (a1<=a3));
	}

}
  • 단항연산자
    • +,- 를 피연산자 앞에 붙여서 사용할경우
package p01.basic;

// Unary Operator(단항 연산자)
// +,- : 피연산자 앞에 붙여서 사용할 경우
// Binary Operator(이항 연산자) : operand가 2개인 경우 (산술연산자 : +,-,*,/)

public class UnaryOperatorEx {
	
	public static void main(String[] args) {
		int  n1 = 20;
		int result;
		
		
		result = +n1;
		System.out.println("result = "+result);
	
		result = -n1;
		System.out.println("result = "+result);
	}
	

}
(결과)
result = 20
result = -20

 

  • 3항연산자
    • 피연산자 갯수가 3개
package p01.basic;

// TernaryOperator (3항연산자) : 피연산자 갯수가 3개
// A ? B : C (연산자는 ?, : 2개이고 피연산자는 A,B,C 3개가 있는 경우)
// => 의미 : A가 true 이면 B를 실행하고, A가 false이면 C를 실행하라
//3항연산자는 그닥 사용하는편은 아니다.
public class TernaryOperatorEx {
	
	public static void main(String[] args) {
		
		int n1 = 15;
		int n2 = 10;
		int max;
		
		//n1이 n2보다 크면 n1을 출력하라 작으면 n2를 출력하라
		max =(n1>n2) ? n1 : n2;
		System.out.println("max = "+max);
		
		if(n1 > n2) {
			max =n1;
			System.out.println(n1);
		}else {
			max =n2;
			System.out.println(n2);
		}
		
		int result;
		
		result = (n1 > n2 )?(n1+n2):(n1-n2);
		System.out.println("result = "+result);
		
	}

}
  • 연산자우선순위
    • 연산자 ( + , - ,,,)의 우선순위
package p01.basic;

//Operator Precedence (연산자 우선순위)
//Assignment operator인 = 을 기준으로해서,
//1. 오른쪽에 있는 수식을 계산할 때 왼쪽부터 오른쪽으로 계산
//2. 왼쪽으로부터 오른쪽으로 계산할 때 연산순위가 높은 연산자가 먼저 연산 수행(*,/,%가 +,-보다 연산수위가 높아 먼저 수행한다.
//3. 단, ()가 모든 연산자보다 우선순위가 제일 높음
//*그렇지만 연산순위를 외울필요는없다.
//4. 프로그래밍할 때 사용할 tip:연산순위가 높은()를 적극활용하라
public class OperatorPrecedenceEx {

	public static void main(String[] args) {
		int result = 0;
		//이퀄 기준으로 왼쪽으로부터 연산
		//+,- 연산순위가 동일하므로 순서대로 연산진행
		//1)5-2 => 3  2)3+3=>6 3)6-6=>0
		result = 5 - 2 + 3 - 6;
		System.out.println("result = "+result);
		
		//1)4/2 =>2, 2)8*4=32, 3)(5+2)=>(7), 4)7%4=>1
		//5)3 - 2 + 32 - 1인 상태에서 왼쪽부터 오른쪽으로 계산
		result = 3 -4/2 + 8*4 - (5+2)%3;
		System.out.println("result = "+result);
		
		//개발자를 배려하는 연산식
		result = 3 - (4/2) + (8*4) - (5+2)%3;
		System.out.println("result = "+result);
		
	}

}

 

 

'수업기록(2022-07~2022-09) JAVA' 카테고리의 다른 글

20220801 수업기록  (0) 2022.08.02
20220729 수업기록  (0) 2022.07.29
20220728 수업기록  (0) 2022.07.28
20220726 수업기록  (0) 2022.07.27
20220725 수업기록  (0) 2022.07.26
Comments