eterno

JAVA 22일차. String 클래스, BigDecimal클래스, 오토박싱과 언박싱, Date 클래스 본문

JAVA/강의노트

JAVA 22일차. String 클래스, BigDecimal클래스, 오토박싱과 언박싱, Date 클래스

영원한별똥별 2022. 9. 21. 10:29
728x90
반응형

예제)

자바에서 데이터를 다루는 건  숫자와 문자(문자열)이다.

  • 정수 연산(int) 은 가능 범위가 2,147,483,648 ~ 0 ~ + 2,147,483,647여서 2,147,483,647를 넘을 수 없다.
  • 실수 연산(double)은 소수점 넷째 자리 이상부터는 오류가 날 확률이 크기 때문에 BigDecimal를 써아한다.

 

BigDecimal

 : 숫자의 오차범위를 허용하지 않는 자료형

 - java.math 클래스에 있다.
 - 함수 + 상수로 사용한다.
 - 초기화 할 때는 문자열(문자 숫자)로 초기화 한다.(자동 형변환되는 것을 방지하기 위함)
     ex) String x = "1.12345678922222";

 

BigDecimal 연산메서드

ADD(더하기)

public BigDecimal add(BigDecimal augend)

BigDecimal badd = b1.add(b2);
badd = badd.setScale(3, BigDecimal.ROUND_DOWN);

SUBTRACT(빼기)
public BigDecimal subtract(BigDecimal subtrahend)

BigDecimal bsub = b1.subtract(b2);		
bsub = bsub.setScale(3, BigDecimal.ROUND_HALF_EVEN);

MULTIPLY(곱하기)
public BigDecimal multiply(BigDecimal multiplicand)

BigDecimal bmul = b1.multiply(b2);
bmul = bmul.setScale(3, BigDecimal.ROUND_DOWN);

DIVIDE(나누기)
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

BigDecimal bdiv = b1.divide(b2, 3,  BigDecimal.ROUND_DOWN);

 * 나눗셈은 setScale 함수를 못쓰고 divide로만 쓴다.

 

setScale

 :  소수점 자리수를 지정하는 메서드

public BigDecimal setScale(int newScale, int roundingMode)

 - int roundingMode 종류
   ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP,

   ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_UNNECESSARY

 

예제)

 * 더하기, 빼기, 곱하기 는 연산 후에 소수점을 정리하는데

   나눗셈은 생성자에서 초기화할 때 소수점 자리수를 표기한다.

   (이유: 연산 과정에서 소수점이 무한대로 넘어가서 연산 범위를 넘어갈 수 있기 때문)

 

 

오토박싱과 언박싱

byte, char, short, int, long, float, double을 기초 자료형이라고 하는데 기초 자료형은 객체가 아니다.

→ 자바는 객체지향언어여서 기초 자료형에 대응하는 Wrapper Class를 사용한다.

→ Wrapper Class 상수로 존재한다. (Short, Integer, Long, Float, Double, Character, String)

 

 - 오토박싱(Autoboxing) : 기본형(기초자료형)을 객체(Wrapper)로 바꾸는 것

 - 언박싱(Unboxing) : 객체(Wrapper)를 기본형(기초자료형)으로 꺼내는 것

   * JDK 1.5부터는 자바 컴파일러가 박싱과 언박싱이 필요한 상황에 자동으로 처리를 해준다.

 

예제)

Integer 클래스에서 생성자 초기화 할 때 초기화 데이터 타입을 문자열(문자숫자) (≠ 기초자료형) 로 한다.

  → 형변환 못하게 하기 위해서

 * intValue(); : Integer 형을 int형으로 변환

 * valueOf(); : int형을 Integer형으로 변환


날짜함수

 - 컴퓨터에서 시간은 초로 계산한다

  • 1 day = 24 * 60 * 60 = 86400
  • 1 year = 365 * 24 * 60 * 60 = 31536000
  • The leap second : 윤초

 - 컴퓨터 시간 : 클라이언트 시간과 서버 시간이 있다.

    참고) 타임서버 : https://retilog.tistory.com/76

    컴퓨터에 저장되어있는 시간은 클라이언트 시간이다.

Date 클래스

 - java.util에 있다

 

Greenwich mean time (GMT)

: 그리니치 표준시는 런던을 기점으로 하고, 웰링턴에 종점으로 설정되는 협정 세계시의 기준시간대이다. UTC라고도 하며 전 세계 표준시간의 기준으로 사용된다 GMT는 컴퓨터, 인공위성 및 GPS와 같은 항법장치를 위한 표준시간으로도 사용

 

global positioning system (GPS) GPS는 UTC/GMT와 동기되어 있으며, 1980년 1월 5일 子正을 GPS 0시로 하여 시간을 측정한다.

 

A year y is represented by the integer y - 1900.
A month is represented by an integer from 0 to 11;
0 is January, 1 is February, and so forth; thus 11 is December.
A date (day of month) is represented by an integer from 1 to 31 in the usual manner.

=>년도는 -1900d으로 나타낸다.

월은 0 ~ 11의 정수로 표현된다.(0 = 1월)

시간은 0 ~23의 정수로 표현된다.(0 = 00시 ~01시)

 

 - Date 클래스는 epoch시간(이포크시간)을 리턴한다.

   1970년 1월 1일 00:00:00 시간을 기준으로 지나간 시간을 millisecond로 반환한다.

 - 윤년을 다루는 클래스는 Date클래스에만 있다. (The leap second)

 

시간 표현하는 형식

 - java.text.SimpleDateFormat에 있음

예제)

 

getYear() 메서드

→ getYear에는 static이 없으니까 클래스(date)의 참조 변수를 써서 사용하면 된다.

 함수 중에 Deprecated 라고 적혀있는 함수는 사용하지 말라는 뜻이다. (현재꺼 보다 더 향상된 버전이 있으니 이것을 사용하지 마시오)

 getYear함수 를 대신해서 Calendar.get(Calendar.YEAR) - 1900 를 사용할 수 있다.

 

java.lang.Calendar에 사용되는 변수는 상수이다.
     : public final static int YEAR = 1;

     : public final static int MONTH = 2;

     : public final static int DATE = 5;

     : public final static int DAY_OF_MONTH = 5;

     : public final static int DAY_OF_WEEK = 7;

     : public final static int HOUR_OF_DAY = 11;

     : public final static int MINUTE = 12;

    : public final static int SECOND = 13;

 

ex) Calendar cd = Calendar.getInstance();

int y= cd.get(Calendar.YEAR) - 1900;

* Calender 는 추상클래스(public abstract class Calendar)여서 객체를 생성할 수 없기 때문에 getInstance() 메소드를 통해 객체를 얻는다.

예제)

package a.b.c.ch8;

import java.util.Calendar;
import java.util.Date;

public class Test_Date_1 {

	public static void main(String[] args) {
	
		/*
		 Date 클래스는 epoch시간(이포크시간)을 리턴한다.
		 1970년 1월 1일 00:00:00 시간을 기준으로 지나간 시간을 millisecond로 반환한다.
		 */
		
		Date d = new Date();
		Calendar cd = Calendar.getInstance();
		System.out.println("cd >>> :" + System.identityHashCode(cd));
		
		//년
		// public int getYear()
		int year = d.getYear();
		// A year y is represented by the integer y - 1900.
		// the year represented by this date, minus 1900.
		System.out.println("year >>> : " + year);
		
		year = year + 1900;
		System.out.println("year >>> : " + year);
		
		//replaced by Calendar.get(Calendar.YEAR) - 1900.
		int y= cd.get(Calendar.YEAR) - 1900;
		System.out.println("y >>> :" + y);
		
		//월
		int month = d.getMonth();
		System.out.println("month >>> : " + month);
		month = month + 1;
		System.out.println("month >>> : " + month);
		// replaced by Calendar.get(Calendar.MONTH).
		int m = cd.get(Calendar.MONTH);
		m = m+1;
		System.out.println("m >>> : " + m);
				
		//일
		int date =  d.getDate();
		System.out.println("date >>> : " + date);
		
		// replaced by Calendar.get(Calendar.DAY_OF_MONTH)
			int date1 = cd.get(Calendar.DAY_OF_MONTH);
			System.out.println("date1 >>> : " + date1);
		
		int day =d.getDay();
		System.out.println("day >>> : " + day);
		
		int day1 = cd.get(Calendar.DAY_OF_WEEK);
		System.out.println("day1 >>> : " + day1);
		
		String time = "";
		
		// year은 숫자인데 "-"랑 더해서 문자열로 자동 형변환 되었다.
		time = year + "-" + month + "-" + date;
		System.out.println("time >>> : " + time);
	}
}

예제)Calendar 변수들은 상수이기 때문에 값이 정해져있어서 get()으로 호출한다.

package a.b.c.ch8;

import java.util.Calendar;

public class Test_Calendar {

	public static void main(String[] args) {
		Calendar cd = Calendar.getInstance();
		System.out.println("cd >>> : " + System.identityHashCode(cd));
		System.out.println("cd >>> : \n" + cd);
		
		//년
		int y = cd.get(Calendar.YEAR);
		System.out.println("y >>> : " + y);
		System.out.println("cd.get(1) >>> : " + cd.get(1));
		
		//월
		int m = cd.get(Calendar.MONTH);
		System.out.println("m >>> : " + m);
		System.out.println("(cd.get(2)+1) >>> : " + (cd.get(2)+1));
		
		//일
		int d = cd.get(Calendar.DATE);
		System.out.println("d >>> : " + d);
		System.out.println("cd.get(5) >>> : " + cd.get(5));
		
		int d1 = cd.get(Calendar.DAY_OF_MONTH);
		System.out.println("d1 >>> :" + d1);
		
		//시
		int t = cd.get(Calendar.HOUR_OF_DAY);
		System.out.println("t >>> : " + t);
		System.out.println("cd.get(11) >>> : " + cd.get(11));
		int t1 = cd.get(Calendar.HOUR);
		System.out.println("t1 >>> : " + t1);
		
		//분
		int mm = cd.get(Calendar.MINUTE);
		System.out.println("mm >>> : " + mm);
		System.out.println("cd.get(12) >>> : " + cd.get(12));
		
		//초
		int s = cd.get(Calendar.SECOND);
		System.out.println("s >>> : " + s);
		System.out.println("cd.get(13)" + cd.get(13));
		
		String time = "현재 시간은 : "
				+ y + "년"
				+ m + "월"
				+ d + "일"
				+ t + "시"
				+ mm + "분"
				+ s + "초 입니다!!";

				System.out.println("time >>>  \n " + time);
	}
}

예제) 상수를 배열 인덱스 값으로 사용할 수도 있다.

package a.b.c.test;

public class Test_4 {

	public static final int NUM_0 = 0;
	public static final int NUM_1 = 1;
	
	public static String[] sV = {"a", "b", "c"};
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println(Test_4.NUM_0);
		System.out.println(Test_4.sV[0]);
		System.out.println(Test_4.sV[Test_4.NUM_0]);
		
		System.out.println(Test_4.NUM_1);
		System.out.println(Test_4.sV[1]);
		System.out.println(Test_4.sV[Test_4.NUM_1]);
	}

}

세계시간 구하기

TimeZone 클래스

getAvailableIDs() :

예제)

package a.b.c.ch8;

import java.util.Calendar;
import java.util.TimeZone;

public class Test_Calendar_1 {

	public static void timeZone() {
		String cityID[] = TimeZone.getAvailableIDs();
		System.out.println("전세계 도시 수 >>> : " + cityID.length);
		
		for (int i=0; i<cityID.length; i++) {
			System.out.println("cityID["+ i +"] >>> : " + cityID[i]);
		}
	}
	
	public static String cityTime(Calendar cd) {
		String time = "현재시간 : " 
					+ cd.get(Calendar.YEAR) + "년"
					+ cd.get((Calendar.MONTH) +1 ) + "월"
					+ cd.get(Calendar.DATE) + "일"
					+ cd.get(Calendar.HOUR_OF_DAY) + "시"
					+ cd.get(Calendar.MINUTE) + "분"
					+ cd.get(Calendar.SECOND) + "초";					
		return time;					
	}	
	
	public static void main(String[] args) {
//		전 세계 도시명 가져오기 
//		Test_Calendar_1.timeZone();
		String strID[] = {"Europe/London"
				           ,"Europe/Paris"
				           ,"Asia/Seoul"
				           ,"Asia/Tokyo"
				           ,"Australia/Sydney"	
				           ,"America/Los_Angeles"				         
				           ,"America/New_York"};	
		
		String strName[] = {"런던", "파리", "서울", "도쿄", "시드니", "LA", "뉴욕"};
		
		//도시시간 가져오기
	for (int i=0; i < strID.length; i++) {
			
			TimeZone tz = TimeZone.getTimeZone(strID[i]);	
			System.out.println("tz >>> : " + tz);
			Calendar cd = Calendar.getInstance(tz);			
			String t = Test_Calendar_1.cityTime(cd);			
			System.out.println(strName[i] + " " + t);
		}
	}
}

자바에서 Resource를 사용하는 방법

  1. static 키워드 : 클래스로 사용
  2. new 연산자(키워드) : 참조변수 사용
  3. 상속(inheritance) : 클래스, 참조변수 없이 사용 extends 키워드 : class 클래스 상속시 사용
    단일상속(simple inheritance) impolement 키워드 : interface클래스 상속 시 사용
    다중상속(multiful inheritance)
  4. public abstract class : 추상클래스 new 연산자를 사용하지 못함 getInstance() 함수사용 ex)java.util.Calendar 사용방법 : Calendar rightNow = Calendar.getInstance();

Class.forName(String className) Class ca= Class.forName("a.b.c.ch8.Test_Class"); 클래스이름 참조변수 = (클래스이름).ca.newInsstance();
= Class.forName("패키지명.클래스이름") 클래스이름 참조변수 = (클래스이름).참조변수.

 

예제) Test_Class 를 호출하여 Test_ClassTest 에 출력한다.

package a.b.c.ch8;

public class Test_ClassTest {

	public static void main(String[] args) {
		//방법1

		Test_Class tc = new Test_Class();
		System.out.println("tc >>> : " + tc);
		tc.aM();
		
		
		//방법2
		try {
			Class ca = Class.forName("a.b.c.ch8.Test_Class");	
			System.out.println("ca >>> : " + ca);
			Test_Class tc_1 = (Test_Class)ca.newInstance();
			System.out.println("tc_1 >>> : " + tc_1);
			tc_1.aM();
			
			
		}catch(Exception ex) {
//			catch(ClassNotFoundException cx) {}
//			catch(InstantiationException inx) {}
//			catch(IllegalAccessException ilx) {}
			
		}
	}
}

 

package a.b.c.ch8;

public class Test_Class {

	public void aM() {	
		System.out.println("Test_Class.aM() 함수 >>> : ");
	}
}
728x90
반응형