티스토리 뷰

728x90

서문



자바의 정석 기초편 챕터 9편을 기재합니다.
목적은 공부한 내용을 기록하는 것에 있기 때문에 완전한 문장이 아닐 수도 있습니다.
또한 모든 내용을 적은 것은 아닙니다.









자바의 정석 ( ch.9 )



Object 클래스


  • 모든 클래스의 최고 조상으로 오직 11개의 메서드만 가지고 있음
  • protected가 있는 메서드는 오버라이딩을 통해 public으로 변경 후 사용
  • 사용자의 상황에 맞게 오버라이딩 후 사용

메서드 설명
protected Object clone() 객체 자신의 복사본을 반환
public boolean equals(Object obj) 객체 자신과 객체 obj가 같은 객체인지 알려줌 (같으면 true)
protected void finalize() 객체가 소멸될 때 가비지 컬렉터에 의해 자동적으로 호출, 이 때 수행되어야하는 코드가 있을 때 오버라이딩함(거의 사용안함)
public Class getClass() 객체 자신의 클래스 정보를 담고 있는 Class인스턴스를 반환, Class는 설계도 객체(객체생성, 객체정보-ReflectionAPI)
public int hashCode() 객체 자신의 해시코드를 반환
public String toString() 객체 자신의 정보를 문자열로 반환
public void notify() 객체 자신을 사용하려고 기다리는 쓰레드를 하나만 깨움
public void notifyAll() 객체 자신을 사용하려고 기다리는 쓰레드 모두를 깨움
public void wait()
public void wait(long timeout)
public void wait(long timeout, int nanos)
다른 쓰레드가 notiry()나 notifyAll()을 호출할 때까지 현재 쓰레드를 무한히 또는 지정한 시간(timeout, nanos)동안 기다리게 함. (timeout은 1초/1000분,nanos는 1초/10^9분 )


equals(Object obj)


  • 객체 자신(this)와 다른 객체를 비교, 같으면 true 다르면 false
  • Object클래스의 equals()는 객체의 주소를 비교(참조변수 값 비교)
public boolean equals(Object obj){
  return (this == obj); // 주소 비교
}

class Value{
  int value;

  Value(int value){
    this.value = value;
  }
}

class Ex1{
  public static void main(String[] args){
    Value v1 = new Value(10);
    Value v2 = new Value(10);

    System.out.println(v1);
    System.out.println(v2);
    System.out.println(v1.equals(v2)); // 서로 다른 객체이기 때문에 false
  }
}



> Value@58d25a40
> Value@15615099
> false

-------------------------------------

class Value{
  int value;

  Value(int value){
    this.value = value;
  }

  public boolean equals(Object obj){
    if (!(this instanceof Value)){
      return false;
    }
    Value v = (Value) obj;
    return this.value == v.value;
  }
}

class Ex2{
  public static void main(String[] args){
    Value v1 = new Value(10);
    Value v2 = new Value(10);

    System.out.println(v1.equals(v2)); // 서로 다른 객체이기 때문에 false
  }
}



> true


hashCode(), equals()


  • 객체의 해시코드를 반환하는 코드

  • Object클래스의 hashCode()는 객체의 주소를 int로 변환해서 반환

  • 객체마다 다른 값을 가지고 있음

  • equals()를 오버라이딩하면, hashCode()도 오버라이딩해주어야 함

  • equals()의 결과가 true인 두 객체의 해시코드는 같아야 하기 떄문에

    • equals()는 iv가지고 같은지 아닌지를 판단하는데 만약 equals()를 그러한 기준으로 사용했다면 hashCode()는 객체의 주소가 아니라 iv로 기준을 바꿔야 하기 때문에
  • System.identityHashCode()는 오버라이딩 한 hashCode()의 오리지널 버전과 동일

String str1 = new String("abc");
String str2 = new String("abc");

System.out.println(str1.equals(str2)) // true, iv로 기준잡아야함
System.out.println(str1.hashCode()) // 96354, 오버라이딩하면 이렇게 동일한 값으로 반환
System.out.println(str2.hashCode()) // 96354


toString(), toString()의 오버라이딩


  • toString() : 객체를 문자열(String)으로 변환하기 위한 메서드
public String toString(){
  return getClass().getName() + "@" + Integer.toHexString(hashCode()); 
}

class Card{
  String kind;
  int number;

  Card(){
    this("SPADE", 1);
  }

  Card(String kind, int number){
    this.kind = kind;
    this.number = number;
  }
}

class Ex1{
  public static void main(String[] args){
    System.out.println(new Card().toString());
    System.out.println(new Card().toString());
  }
}


> Card@58d25a40 // className + @ + hashCode값을 16진수로 변환한 값
> Card@15615099

-------------------------------------------------

class Card{
  String kind;
  int number;

  Card(){
    this("SPADE", 1);
  }

  Card(String kind, int number){
    this.kind = kind;
    this.number = number;
  }

  // 객체가 가진 iv로 오버라이딩
  public String toString(){
    return "kind:"+kind+", number:"+number;
  }
}

class Ex1{
  public static void main(String[] args){

    System.out.println(new Card().toString());
    System.out.println(new Card().toString());
  }
}


> kind:SPADE, number:1
> kind:SPADE, number:1


-------------------------------------------------

class Card{
  String kind;
  int number;

  Card(){
    this("SPADE", 1);
  }

  Card(String kind, int number){
    this.kind = kind;
    this.number = number;
  }

  // 객체가 가진 iv로 오버라이딩
  public String toString(){
    return "kind:"+kind+", number:"+number;
  }

  // equals() 오버라이딩
  public boolean equals(Object obj){
    if(!(obj instanceof Card))
      return false;

    Card c = (Card)obj;
    return this.kind.equals(c.kind) && this.number==c.number; 
  }

  // hashCode() 오버라이딩
  public int hashCode(){
    return Objects.hash(kind, number); // 가변인자라서 여러 개 넣어도 상관없음
  }
}

class Ex2{
  public static void main(String[] args){
    Card a = new Card();
    Card b = new Card();

    System.out.println(a.equals(b));
    System.out.println(a.hashCode());
    System.out.println(b.hashCode());

    System.out.println(a.toString());
    System.out.println(b.toString());
  }
}



> true
> -1842861219
> -1842861219
> kind:SPADE, number:1
> kind:SPADE, number:1


String 클래스


  • 데이터(char[]) + 메서드(문자열 관련)
  • 내용을 변경할 수 없음(불변)
  • 덧셈연산자(+)를 이용한 문자열 결합은 성능이 떨어짐 ( 새로운 객체가 계속 생기는 것이기 때문에)
  • 문자열을 많이 자주 수정해야 하는 경우 StringBuffer(변경가능)를 사용

문자열 비교


  • 문자열 리터럴 vs 새로운 객체 생성
String str1 = "abc"; // 문자열은 불변이기 때문에 다른 참조변수들이 하나의 주소의 값을 참조하는 것이 가능
String str2 = "abc";

String str3 = new String("abc"); // new를 사용하면 항상 새로운 객체 생성
String str4 = new String("abc"); // 굳이 이렇게 내용이 같은 문자열을 새로 객체 생성할 필요가 없음

System.out.println(str1==str2); // 참조변수 주소 비교
System.out.println(str3==str4);
System.out.println(str1.equals(str2)); // 내용 비교
System.out.println(str3.equals(str4));



> true
> false
> true
> true


문자열 리터럴


  • 문자열 리터럴은 프로그램 실행 시 자동으로 생성(constant pool에 저장)
  • 같은 내용의 리터럴은 하나만 만들어짐
class Ex1{
  public static void main(String[] args){
    String s1 = "AAA";
    String s2 = "AAA";
    String s3 = "AAA";
    String s4 = "BBB";

  }
}


빈 문자열 ("", empty string)


  • 내용이 없는 문자열, 크가기 0인 char형 배열을 저장하는 문자열

    • String str1 = "";
  • 크기가 0인 배열을 생성하는 것은 어느 타입이나 가능

    • char[] chArr = new char[0];
    • int[] iArr = {};
  • 문자(char)와 문자열(string) 초기화
    • String str = null; x
    • char c = '\u0000'; x
    • String str = "";
    • char c = ' ';


String 클래스의 생성자 및 메서드

메서드 설명 예제 결과
String(String s) 주어진 문자열(s)를 갖는 String인스턴스를 생성 String s = new String("Hello"); s = "Hello";
String(char[] value) 주어진 문자열(value)를 갖는 String인스턴스를 생성 char[] c = {'H','e','l','l','o'};
String s = new String(c);
s = "Hello";
String(StringBuffer buf) StringBuffer인스턴스가 가지고 있는 문자열과 같은 내용의 String인스턴스를 생성 StringBuffer sb = new StringBuffer("Hello");
String s = new String(sb);
s = "Hello";
char charAt(int index) 지정된 위치(index)에 있는 문자를 알려줌(index는 0부터 시작) String s = "Hello";
String n = "0123456";
char c = s.charAt(1);
char c2 = n.charAt(1);
s = 'e';
c2 = '1';
int compareTo(String str) 문자열(str)과 사전순서를 비교, 같으면 0을, 사전순으로 이전이면 음수, 이후면 양수를 반환 int i = "aaa".compareTo("aaa");
int i2 = "aaa".compareTo("bbb");
int i3 = "bbb".compareTo("aaa");
i = 0;
i2 = -1;
i3 = 1;
String concat(String str) 문자열(str)을 뒤에 덧붙임 String s = "Hello";
String s2 = s.concat(" World");
s2 = "Hello World";
boolean contains(CharSequence s) 지정된 문자열(s)가 포함되어 있는지 확인 String s = "abcdefg";
boolean b = s.contains("bc");
b = true
boolean endsWith(String suffix) 지정된 문자열(suffix)로 끝나는지 확인 String file = "Hello.txt";
boolean b = file.endsWith("txt");
b = true;
boolean equals(Object obj) 매개변수로 받은 문자열(obj)과 String인스턴스의 문자열을 비교, obj가 String이 아니거나 문자열이 다르면 false를 반환 String s = "Hello";
boolean b = s.equals("Hello");
boolean b2 = s.equals("hello");
b = true;
b2 = false
boolean equalsIgnoreCase(String str) 문자열과 String인스턴스의 문자열을 대소구분없이 비교 String s = "Hello";
boolean b = s.equalsIgnoreCase("Hello");
boolean b2 = s.equalsIgnoreCase("hellO");
b = true;
b2 = true;
int indexOf(int ch) 주어준 문자(ch)가 문자열에 존재함을 확인하여 위치(index)를 알려줌, 못 찾으면 -1를 반환(index는 0부터 시작) String s = "Hello";
int idx1 = s.indexOf('o');
int idx2 = s.indexOf('k');
idx1 = 4;
idx2 = -1;
int indexOf(int ch, int pos) 주어진 문자(ch)가 문자열에 존재하는지 확인하여 위치(index)를 알려줌, 못찾으면 -1를 반환 String s = "Hello";
int idx1 = s.indexOf('e', 0);
int idx2 = s.indexOf('e',2);
idx1 = true;
idx2 = -1
int indexOf(String str) 주어진 문자열이 존재하는지 확인 후 그 위치를 반환, 못 찾으면 -1를 반환 String s = "ABCDEFG";
int idx = s.indexOf("CD");
idx = 2;
int lastIndexOf(int ch) 지정된 문자 또는 문자코드를 문자열의 오른쪽 끝에서부터 찾아서 위치(index)를 반환, 못 찾으면 -1f를 반환 String s = "java.lang.java";
int idx1 = s.lastIndexOf('.');
int idx2 = s.indexOf('.');
idx1 = 9;
idx2 = 4
int lastIndexOf(String str) 지정된 문자열을 인스턴스의 문자열 끝에서부터 찾아서 위치(index)를 반환, 못 찾으면 -1 반환 String s = "java.lang.java";
int idx1 = s.lastIndexOf("java");
int idx2 = s.indexOf("java");
idx1 = 10;
idx2 = 0;
int length() 문자열의 길이를 반환 String s = "Hello";
int len = s.length()
len = 5;
String[] split(String regex) 문자열을 지정한 분리자(regex)로 나누어 문자열 배열을 담아 반환 String animals = "dog,cat,bear";
String[] arr = animals.split(",");
arr[0] = "dog";
arr[1] = "cat";
arr[2] = "bear";
String[] split(String regex, int limit) 문자열을 지정한 분리자로 나누어 문자열 배열을 담아 반환, 단 문자열 전체를 지정된 수(limit)로 자름 String animals = "dog,cat,bear";
String[] arr = animals.split(",",2);
arr[0] = "dog";
arr[1] = "cat,bear";
boolean startsWith(String prefix) 주어진 문자열(prefix)로 시작하는지 확인 String s = "java.lang.java";
boolean b = s.startsWith("java");
boolean b2 = s.startsWith("lang");
b = true;
b2 = false;
String substring(int begin)
String substring(int begin, int end)
주어진 시작위치(begin)부터 끝 위치(end)범위에 포함된 문자열을 얻음, 이 때 시작위치의 문자는 범위에 포함되지만 end 위치의 문자는 포함하지 않음 String s = "java.lang.Object";
String c = s.substring(10);
String p = s.substring(5, 9);
c = "Object";
p = "lang;
String toLowerCase() String 인스턴스에 저장되어 있는 모든 문자열을 소문자로 변환하여 반환 String s = "Hello";
String s1 = s.toLowerCase();
s1 = "hello";
String toUpperCase() String 인스턴스에 저장되어 있는 모든 문자열을 대문자로 변환하여 반환 String s = "Hello";
String s1 = s.toUpperCase();
s1 = "HELLO";
String trim() 문자열의 왼쪽 끝과 오른쪽 끝에 있는 공백을 없앤 결과를 반환, 이 떄 문자열 중간에 있는 공백은 제거하지 않음 String s = " Hello World ";
String s1 = s.trim();
s1 = "Hello World"
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(float f)
static String valueOf(double d)
static String valueOf(Object obj)
지정된 값을 문자열로 변환하여 반환, 참조변수의 경우 toString()을 호출한 결과를 반환 String b = String.valueOf(true);
String c = String.valueOf('a');
String i = String.valueOf(100);
String l = String.valueOf(100L);
String f = String.valueOf(10f);
String d = String.valueOf(10.0);
java.util.Date dd = new java.util.Date();
String date = String.valueOf(dd);
b = "true";
c = "a";
i ="100";
l = "100";
f = "10.0";
d = "10.0";
date = "Wed Jan 27 21:26:29 KST 2021"


join()과 StringJoiner


  • join()은 여러 문자열 사이에 구분자를 넣어서 결합
  • 성능상 StringBuffer를 사용하기 때문에 좀 더 좋음
String animals = "dog,cat,bear";
String[] arr = animals.split(",");
String str = String.join("-",arr);
System.out.println(str); 

> "dog-cat-bear"


문자열과 기본형 간의 변환


  • 숫자를 문자로 바꾸는 방법

    • 숫자 + ""; 편리함
    • String.valueOf(숫자); 성능상 더 빠름

  • 문자열을 숫자로 바꾸는 방법

    • Integer.parseInt(); // old 방법,
    • Integer.valueOf(); // new 방법
int i = 100;
String str1 = i + "";
String str2 = String.valueOf(i); // valueOf를 사용하는 것이 더 빠르다.

int i = Integer.parseInt("100");
int i2 = Integer.valueOf("100");
Integer i2 = Integer.valueOf("100");

기본형 -> 문자열 문자열 -> 기본형
String String.valueOf(boolean b)
String String.valueOf(char c)
String String.valueOf(int i)
String String.valueOf(long l)
String String.valueOf(float f)
String String.valueOf(double d)
boolean Boolean.parseBoolean(String s)
byte Byte.parseByte(String s)
short Short.parseShort(String s)
int Integer.parseInt(String s)
long Long.parseLong(String s)
float Float.parseFloat(String s)
double Double.parseDouble(String s)


StringBuffer 클래스


  • String처럼 문자형 배열(char[])을 내부적으로 가지고 있음
  • String은 불변, StringBuffer은 가변
  • 문자열을 조작하거나 수정 변경할 때에는 StringBuffer를 사용하자
  • 아무리 가변이라고 할지라도 배열의 크기를 수정할 때마다 리소스가 필요하므로 처음 생성할 때 배열의 크기를 고려하여 만들어주자.
  • equals()가 오버라이딩 x (주소비교함), String으로 변환 후에 equals()사용
public final class StringBuffer implements java.io.Serializable{
  ...
  private char[] value;
  ...
}

StringBuffer sb = new StringBuffer("abc"); // {'a','b','c'}
sb.append("123"); // {'a','b','c','1','2','3'}


public StringBuffer(int length){
  value = new char[length];
  shared = false;
}

public StringBuffer(){
  this(16)
}

public StringBuffer(String str){
  this(str.length() + 16);
  append(str);
}


StringBuffer의 생성자 및 메서드


메서드 설명 예제 / 결과
StringBuffer() 16문자를 담을 수 있는 StringBuffer인스턴스를 생성 StringBuffer sb = new StringBuffer();
StringBuffer(int length) 지정된 개수의 문자를 담을 수 있는 버퍼를 가진 StringBuffer인스턴스를 생성 StringBuffer sb = new StringBuffer(10);
StringBuffer(String str) 지정된 문자열(str)을 갖는 StringBuffer 인스턴스를 생성 StringBuffer sb = new StringBuffer("hi");
StringBuffer(boolean b)
StringBuffer(char c)
StringBuffer(char[] chArr)
StringBuffer(String str)
StringBuffer(int i)
StringBuffer(long l)
StringBuffer(float f)
StringBuffer(double d)
StringBuffer(Object o )
매개변수로 입력된 값을 문자열로 변환하여 StringBuffer인스턴스가 저장하고 있는 문자열의 뒤에 덧붙임 StringBuffer sb = new StringBuffer("abc");
StringBuffer sb2 = sb.append(true);
sb.append('d').append(10.0f);
StringBuffer sb3 = sb.append("ABC").append(123);
sb = "abctrued10.0ABC123";
sb2 = "abctrued10.0ABC123";
sb3 = "abctrued10.0ABC123";
int capacity() StringBuffer인스턴스의 버퍼크기를 알려줌, length()는 버퍼에 담긴 문자열의 길이를 알려줌 StringBuffer sb = new StringBuffer(100);
sb.append("abcd");
int bufferSize = sb.capacity();
int stringSize = sb.length();
char charAt(int index) 지정된 위치(index)에 있는 문자를 반환 StringBuffer sb = new StringBuffer("abc");
char c = sb.charAt(2);
c = 'c';
StringBuffer delete(int start, int end) 시작위치에서부터 끝위치사이에 있는 문자를 제거, 단 end는 미포함 StringBuffer sb = new StringBuffer("0123456");
sb.delete(3,6);
sb = "0126";
sb2 = "0126";
StringBuffer deleteCharAt(int index) 지정된 위치(index)의 문자를 제거 StringBuffer sb = new StringBuffer("0123456");
sb.deleteCharAt(3);
sb = "012456";
StringBuffer insert(int pos, boolean, char, char[], double, float, int, long, Object, String) 두 번째 매개변수로 받은 값을 문자열로 변환하고 지정된 위치(pos)에 추가함, pos는 0부터 시작 StringBuffer sb = new StringBuffer("0123456");
sb.inser(4,'.');
sb = "0123.456";
int length() StringBuffer인스턴스에 저장되어 있는 문자열의 길이를 반환 StringBuffer sb = new StringBuffer("0123456");
int len = sb.length();
len = 7;
StringBuffer replace(int start, int end, String str) 지정된 범위(start~end)의 문자들을 주어진 문자열로 바꿈, end위치의 문자는 범위에 포함 x StringBuffer sb = new StringBuffer("0123456");
sb.replace(3, 6,"AB");
sb = "012AB6";
StringBuffer reverse() StringBuffer인스턴스에 저장되어 있는 문자열의 순서를 바꿈 StringBuffer sb = new StringBuffer("0123456");
sb.reverse()
sb = "6543210";
void setCharAt(int index, char ch) 지정된 위치의 문자를 주어진 문자(ch)로 바꿈 StringBuffer sb = new StringBuffer("0123456");
sb.setCharAt(5,'o');
sb = "01234o6";
void setLength(int newLength) 지정된 길이로 문자열의 길이를 변경, 길이를 늘릴 경우 나머지 빈 공간을 널문자 '\u0000'로 채움 StringBuffer sb = new StringBuffer("0123456");
sb.setLength(5);
StringBuffer sb2 = new StringBuffer("0123456");
sb2.setLength(10);
String str = sb2.toString().trim();
sb = "01234";
sb2 = "0123456 ";
str = "0123456";
String toString() StringBuffer인스턴스의 문자열을 String으로 반환 StringBuffer sb = new StringBuffer("0123456");
String str = sb.toString();
str = "0123456";
String substring(int start, int end) 지정된 범위 내의 문자열을 String으로 반환, 시작위치만 넣으면 시작위치부터 문자열 끝까지를 범위로 함 StringBuffer sb = new StringBuffer("0123456");
String str1 = sb.substring(3);
String str2 = sb.substring(3,5);
str1 = "3456";
str2 = "34";


StringBuilder


  • StringBuffer는 동기화되어 있음, 멀티 쓰레드에 안전(thread-safe)

  • 멀티 쓰레드 프로그램이 아닌 경우, 동기화는 불필요한 성능저하를 가져옴

  • 이럴 떈 StringBuffer대신 StringBuilder를 사용하면 성능 향상


    결론 : 멀티쓰레드 (StringBuffer) 싱글쓰레드 (StringBuilder)

StringBuffer sb;
sb = new StringBuffer();
sb.append("abc");

StringBuilder sb;
sb = new StringBuilder();
sb.append("abc");


Math 클래스


  • 수학관련 static메서드의 집합
    • public static final double E = 2.7182 ... (자연로그의 밑)
    • public static final double PI = 3.1415 ... (원주율)

메서드 설명 예제 결과
static double abs(double d)
static float abs(float f)
static int abs(int i)
static long abs(long l)
주어진 값의 절대값을 반환 int i = Math.abs(-10);
double d = Math.abs(-10.0);
i = 10
d = 10.0
static double ceil(double d) 주어진 값을 올림하여 반환 double d = Math.ceil(10.1);
double d2 = Math.ceil(-10.1);
double d3 = Math.ceil(10.000015);
d = 11.0
d2 = -10.0
d3 = 11.0
static double floor(double d) 주어진 값을 버림하여 반환 double d = Math.floor(10.8);
double d2 = Math.floor(-10.8);
d = 10.0
d2 = -11.0
static double max(double a, double b)
static float max(float a, float b)
static int max(int a, int b)
static long max(long a, long b)
주어진 두 값을 비교하여 큰 값을 반환 double d = Math.max(9.5, 9.500001);
int i = Math.max(0, -1);
d = 9.500001
i = 0
static double min(double a, double b)
static float min(float a, float b)
static int min(int a, int b)
static long min(long a, long b)
주어진 두 값을 비교하여 더 작은 값을 반환 double d = Math.min(9.5, 9.500001);
int i = Math.min(0, -1);
d = 9.5
i = -1
static double random() 0.0~1.0범위의 임의의 double값을 반환(1.0은 포함 x) double d = Math.random();
int i =(int)(Math.random()*10)+1;
0.0<=d<1.0
1<=i<11
static double rint(double d) 주어진 double값과 가장 가까운 정수값을 double형으로 반환, 단 두 정수의 정 가운데 있는 값(1.5,2.5,3.5 등등 )은 짝수가 반환 double d = Math.rint(1.2);
double d2 = Math.rint(2.6);
double d3 = Math.rint(3.5);
double d4 = Math.rint(4.5);
d = 1.0
d = 3.0
d = 4.0
d = 4.0
static long round(double d)
static long round(float f)
소수점 첫째자리에서 반올림한 정수값(long)을 반환, 두 정수 가운데있는 값은 항상 큰 정수를 반환.(rint()의 결과와 비교) long l = Math.round(1.2);
long l2 = Math.round(2.6);
long l3 = Math.round(3.5);
long l4 = Math.round(4.5);
double d = 90.7552;
double d2 = Math.round(d*100)/100.0
l = 1
l2 = 3
l3 = 4
l4 = 5
d = 90.7552
d2 = 90.76


래퍼(wrapper) 클래스


  • 8개의 기본형을 객체로 다루어야할 때 사용하는 클래스
  • 자바에서 90%는 객체지향이지만 기본형은 객체지향이 아님(성능을 위해)
public final class Integer extends Number implements Comparable{ // 기본형을 감싸고 있는 래퍼클래스
  ...
  private int value; // 기본형
  ...
}

기본형 래퍼클래스 생성자 예시
boolean Boolean Boolean(boolean value)
Boolean(String s)
Boolean b = new Boolean(true);
Boolean b2 = new Boolean("true");
char Character Character(char value) Character c = new Character('a');
byte Byte Byte(byte value)
Byte(String s)
Byte b = new Byte(10);
Byte b2 = new Byte("10");
short Short Short(short value)
Short(String s)
Short s = new Short(10);
Short s2 = new Short("10");
int Integer Integer(int value)
Integer(String s)
Integer i = new Integer(100);
Integer i2 = new Integer("100");
long Long Long(long value)
Long(String s)
Long l = new Long(100);
Long l2 = Long("100");
float Float Float(double value)
Float(float value)
Float(String s)
Float f = new Float(1.0);
Float f2 = new Float(1.0f);
Float f3 = new Float("1.0f");
double Double Double(double value)
Double(String s)
Double d = new Double(100.0);
Double d2 = new Double("100.0");


Number 클래스


  • 모든 숫자 래퍼 클래스의 조상
  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • BigInteger(아주 큰 정수)
  • BigDecimal(아주 큰 실수)
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();
  }

}


문자열을 숫자로 변환하기

  • 문자열을 숫자로 변환하는 다양한 방법
    • int i = new Integer("100").intValue();
    • int i2 = Integer.parseInt("100");
    • Integer i3 = Integer.valueOf("100");
    • int i4 = Integer.valueOf("100");
    • parse...() = 기본형
    • valueOf() = 래퍼형 -> toString() = 문자형

  • n진법의 문자열을 숫자로 변환하는 방법
    • int i = Integer.parseInt("100",10) 10진수 (default)
    • int i = Integer.parseInt("100",2) 100(2) = 4
    • int i = Integer.parseInt("100",8) 100(8) = 64
    • int i = Integer.parseInt("100",16) 100(16) = 256
    • int i = Integer.parseInt("FF",16) 0~F = 255


오토박싱 & 언박싱

  • 기본형 -> 래퍼클래스(오토박싱)
  • 래퍼클래스 -> 기본형(언박싱)
  • JDK1.5이전에는 기본형과 참조형간의 연산이 불가능, 이후에는 가능(오토박싱)
1. JDK 1.5 이전 버전

int i = 5;
Integer iObj = new Integer(7);

int sum = i + iObj; // error

------------------------------

2. JDK 1.5 이후 버전

int i = 5;
Integer iObj = new Integer(7);

int sum = i + iObj.intValue(); // 덧셈 가능, (오토언박싱)

------------------------------

3. 오토박싱, 언박싱 예시

ArrayList<Integer> lst = new ArrayList<Integer>(); // ArrayList는 객체만 저장 가능
lst.add(10); // 오토박싱 10 -> new Integer(10);

int value = lst.get(0) // 언박싱 Integer(10) -> int 10

------------------------------

4. 오토박싱, 언박싱 예시 2

class Ex {
  public static void main(String[] args){
    int i = 10;

    // 기본형 -> 참조형
    Integer intg = (Integer)i; // Integer intg = Integer.valueOf(i);
    Object obj = (Object)i; // Object obj = (Object)Integer.valueOf(i);

    Long lng = 100L;

    int i2 = intg + 10; // 참조형과 기본형 연산 가능
    long l = intg + lng; // 

    Integer intg2 = new Integer(20);
    int i3 = (int)intg2; // 참조형 -> 기본형
  }
}





  • 자바의 정석 챕터 9에서는 Object, String, Number, wrapper, 오토박싱, 언박싱 등 클래스의 개념과 가진 중요 메서드 및 형변환에 대해서 배웠습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함