Day 37 (23.02.16)

Jane·2023년 2월 16일
0

IT 수업 정리

목록 보기
43/124

1. Wrapper 클래스와 오버라이딩

1-1. Boxing을 통한 int, double의 출력

class JavaTest {

	public static void main(String[] args) {

		Integer iObj = 10; // new Integer(10);
		Double dObj = 3.14; // new Double(3.14);

		System.out.println(iObj);
        System.out.println(dObj);

	}

}

[Console]
10
3.14


  • 함수 오버라이딩이 적용된 클래스

Integer 클래스 >> toString(int i)

	public static String toString(int i) {
        int size = stringSize(i);
        if (COMPACT_STRINGS) {
            byte[] buf = new byte[size];
            getChars(i, size, buf);
            return new String(buf, LATIN1);
        } else {
            byte[] buf = new byte[size * 2];
            StringUTF16.getChars(i, size, buf);
            return new String(buf, UTF16);
        }
    }

Double 클래스 >> toString(double d)

public static String toString(double d) {
	return FloatingDecimal.toJavaFormatString(d);
}

1-2. Unboxing을 통한 int, double의 출력

  • 주소값을 치환하는 기능은 컴파일러가 넣어주며, Wrapper 클래스에서만 가능하다.
  • 컴파일러가 자동으로 넣어주므로, '오토' 박싱, '오토' 언박싱이라고 한다.

class JavaTest {

	public static void main(String[] args) {

		Integer iObj = 10; // new Integer(10);
		Double dObj = 3.14; // new Double(3.14);

		System.out.println(iObj + ", " + dObj);

		int numi = iObj; // iObj.intValue();
		double numd = dObj; // dObj.doubleValue();
		
		System.out.println(numi + ", " + numd);
	}

}

2. Number 클래스

  • 숫자를 관리하는 클래스

    java.lang.Number


package java.lang;

public abstract class Number implements java.io.Serializable {

	public abstract int intValue();

	public abstract long longValue();

	public abstract float floatValue();

	public abstract double doubleValue();

	public byte byteValue() {
		return (byte) intValue();
	}

	public short shortValue() {
		return (short) intValue();
	}

}

class JavaTest {

	public static void main(String[] args) {

		Integer num1 = new Integer(29);
		System.out.println(num1.intValue());
		System.out.println(num1.doubleValue());
		
		Double num2 = new Double(3.14);
		System.out.println(num2.intValue());
		System.out.println(num2.doubleValue());
	}

}

[Console]
29
29.0
3
3.14

3. static을 적용한 Wrapper 클래스의 함수들


class JavaTest {

	public static void main(String[] args) {

		Integer n1 = Integer.valueOf(5);
		Integer n2 = Integer.valueOf("1024");
		
		System.out.println("큰 수 : " + Integer.max(n1, n2));
		System.out.println("작은 수 : " + Integer.min(n1, n2));
		System.out.println("합 : " + Integer.sum(n1, n2));
		System.out.println();
		
		System.out.println("12를 2진수로 : " + Integer.toBinaryString(12));
		System.out.println("12를 8진수로 : " + Integer.toOctalString(12));
		System.out.println("12를 16진수로 : " + Integer.toHexString(12));
	}

}

[Console]
큰 수 : 1024
작은 수 : 5
합 : 1029


12를 2진수로 : 1100
12를 8진수로 : 14
12를 16진수로 : c

3-1. valueOf()

  • 오버로딩을 적용했다.
  • 다양한 자료형(int, double, String ...)을 int 형으로 바꿔준다.
 public static Integer valueOf(int i) {
   if (i >= IntegerCache.low && i <= IntegerCache.high)
       return IntegerCache.cache[i + (-IntegerCache.low)];
   return new Integer(i);
}
    
    
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i + (-IntegerCache.low)];
   return new Integer(i);
}    

3-2. min, max, sum

public static int max(int a, int b) {
	return Math.max(a, b);
}

public static int min(int a, int b) {
	return Math.min(a, b);
}

public static int sum(int a, int b) {
	return a + b;
}

3-3. toBinaryString, toOctalString, toHexString

  • Binary : 2
  • Octal : 2의 3제곱
  • Hex : 2의 4제곱
public static String toBinaryString(int i) {
	return toUnsignedString0(i, 1);
}
    
public static String toOctalString(int i) {
	return toUnsignedString0(i, 3);
}

public static String toHexString(int i) {
	return toUnsignedString0(i, 4);
}

4. 큰 숫자 다루기

4-1. BigInteger

  • 매우 큰 정수를 계산할 용도로 쓴다.
import java.math.BigInteger;

class JavaPractice {

	public static void main(String[] args) {
		System.out.println("최대 정수 : " + Long.MAX_VALUE);
        // public static final long MAX_VALUE = 0x7fffffffffffffffL;
		System.out.println("최대 정수 : " + Long.MIN_VALUE);
        // public static final long MIN_VALUE = 0x8000000000000000L;
        
		System.out.println();
		
		BigInteger big1 = new BigInteger("100000000000000000000");
		BigInteger big2 = new BigInteger("-99999999999999999999");
		
		BigInteger r1 = big1.add(big2);
		System.out.println("덧셈 결과 : " + r1);
		
		BigInteger r2 = big1.multiply(big2);
		System.out.println("곱셈 결과 : " + r2);
		System.out.println();
		
		int num = r1.intValueExact();
		System.out.println("From BigInteger : " + num);
	}

}

[Console]
최대 정수 : 9223372036854775807
최대 정수 : -9223372036854775808


덧셈 결과 : 1
곱셈 결과 : -9999999999999999999900000000000000000000


From BigInteger : 1

4-2. BigDecimal

  • 실수를 계산할 때는 오차가 발생할 수 있다. 오차 없는 실수 표현을 위해 BigDecimal을 사용한다.
import java.math.BigDecimal;

class JavaPractice {

	public static void main(String[] args) {
		BigDecimal d1 = new BigDecimal("1.6");
		BigDecimal d2 = new BigDecimal("0.1");
		
		System.out.println("덧셈 : " + d1.add(d2));
		System.out.println("곱셈 : " + d1.multiply(d2));
	}

}

[Console]
덧셈 : 1.7
곱셈 : 0.16

5. Math 클래스의 활용

5-1. 자주 쓰이는 함수들

class JavaPractice {

	public static void main(String[] args) {
		System.out.println("원주율 : " + Math.PI);
		System.out.println("제곱근 : " + Math.sqrt(2));
		System.out.println();
		System.out.println("원주율의 Degree(도) : " + Math.toDegrees(Math.PI));
		System.out.println("원주율 * 2의 Degree(도) : " + Math.toDegrees(Math.PI * 2));
		System.out.println();
		double radian45 = Math.toRadians(45);
		System.out.println("sin 45도 : " + Math.sin(radian45));
		System.out.println("cos 45도 : " + Math.cos(radian45));
		System.out.println("tan 45도 : " + Math.tan(radian45));
		System.out.println();
		System.out.println("log 25 : " + Math.log(25));
		System.out.println("2 ^ 16 : " + Math.pow(2, 16));
	}

}

[Console]
원주율 : 3.141592653589793
제곱근 : 1.4142135623730951


원주율의 Degree(도) : 180.0
원주율 * 2의 Degree(도) : 360.0


sin 45도 : 0.7071067811865475
cos 45도 : 0.7071067811865476
tan 45도 : 0.9999999999999999


log 25 : 3.2188758248682006
2 ^ 16 : 65536.0

5-2. Random

import java.util.Random;

class JavaPractice {

	public static void main(String[] args) {
		
		Random r1 = new Random();
		for(int i=0; i<7; i++) {
			System.out.println(r1.nextInt(1000));
		}
		
		Random r2 = new Random(12);
		// 안에 특정한 seed를 넣어주면 계속 같은 값이 출력된다.
		for(int i=0; i<7; i++) {
			System.out.println(r2.nextInt(1000));
		}
		
	}

}

6. 토큰 구분하기

6-1. 토큰을 구분하는 방법

  • 구분자가 ":", 구분하고자 하는 문자열 "PM:08:45"
    토큰 >> "PM", "08", "45"
  • 토큰 나누는 방법
    • 객체를 생성한다. 여기서 매개변수는 문자열과 토큰으로 받는다.
      StringTokenizer st = new StringTokenizer("문자열", "토큰");
    • public boolean hasMoreTokens()
      : 토큰이 있는지 확인 (있으면 true, 없으면 false)
    • public String nextToken() : 다음 토큰을 변수에 담는다

6-2. 예시

import java.util.StringTokenizer;

class JavaTest {

	public static void main(String[] args) {
		StringTokenizer st1 = new StringTokenizer("PM:08:45", ":");
		
		while(st1.hasMoreTokens()) {
			System.out.print(st1.nextToken() + ' ');
		}
		System.out.println();
		
		StringTokenizer st2 = new StringTokenizer("12 + 36 - 8 / 2 = 44", "+-/=");
		// 둘 이상의 구분자를 쓸 수 있으며, 공백도 포함 가능하다
		
		while(st2.hasMoreTokens()) {
			System.out.print(st2.nextToken() + ' ');
		}
	}

}

[Console]
PM 08 45
12 36 8 2 44

profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글