[Java] java.lang패키지와 유용한 클래스

life_is_egg·2022년 7월 6일
0

Java

목록 보기
14/15

325p. 예제 9-1

//Object클래스의 메서드- equals()
class Ex_JS {
	public static void main(String args[]) {
		Value v1 = new Value(10);
		Value v2 = new Value(10);
		
		if (v1.equals(v2))
			System.out.println("v1과 v2는 같습니다.");
		else
			System.out.println("v1과 v2는 다릅니다.");
	}
}
	
class Value {
	int value;
	
	Value(int value) {
		this.value = value;
	}
}





326p. 예제 9-2

//equals()의 오버라이딩
class Person {
	long id;
	
	public boolean equals(Object obj) { //오버라이딩 이므로 선언부 일치
		if(obj instanceof Person)
			return id ==((Person)obj).id; //long타입과 Object타입의 형변환 가능여부 체크
		else
			return false;
	}
	
	Person(long id) {
		this.id = id;
	}
}

class Ex_JS {
	public static void main(String args[]) {
		Person p1 = new Person(8011081111222L);
		Person p2 = new Person(8011081111222L);
		
		if(p1.equals(p2))
			System.out.println("p1과 p2는 같은 사람입니다.");
		else
			System.out.println("p1과 p2는 다른 사람입니다.");
	}
}
출력값:
p1과 p2는 다른 사람입니다.





327p. 예제 9-3

//Object클래스의 메서드- hashCode()
class Ex_JS {
	public static void main(String[] args) {
		String str1 = new String("abc");
		String str2 = new String("abc");
		
		System.out.println(str1.equals(str2)); 
		System.out.println(str1.hashCode());
		System.out.println(str2.hashCode());
		System.out.println(System.identityHashCode(str1));
		System.out.println(System.identityHashCode(str2));
	}
}

출력값:
true
96354
96354
918221580
2055281021





328p. 예제 9-4

//Object클래스의 메서드- toString()
class Card {
	String kind;
	int number;
	
	Card() {
		this("SPADE", 1);
	}
	
	Card(String kind, int number) {
		this.kind = kind;
		this.number = number;
	}
}

class Ex_JS {
	public static void main(String[] args) {
		Card c1 = new Card();
		Card c2 = new Card();
		
		System.out.println(c1.toString());
		System.out.println(c2.toString());
	}
}
출력값:
Card@7a81197d
Card@5ca881b5 //오버라이딩을 하지 않았기 때문에 해시코드값이 반환, 서로 다른 인스턴스이므로 해시코드 값이 다름





329p. 예제 9-5

//toString()의 오버라이딩
class Card2 {
	String kind;
	int number;
	
	Card2() {
		this("SPADE", 1);
	}
	
	Card2(String kind, int number) {
		this.kind = kind;
		this.number = number;
	}
	
	public String toString() { //toString 오버라이딩
		return "kind : " + kind + ", number : " + number;//내가 원하는 형태로 오버라이딩 하기
	}
}

class Ex_JS {
	public static void main(String[] args) {
		Card2 c1 = new Card2();
		Card2 c2 = new Card2("HEART", 10);
		System.out.println(c1.toString());
		System.out.println(c2.toString());
	}
}
출력값:
kind : SPADE, number : 1
kind : HEART, number : 10





331p. 예제 9-6

//문자열(String)의 비교
class Ex_JS {
	public static void main(String[] args) {
		String str1= "abc";
		String str2= "abc"; //문자열 리터럴로 문자열 만들기, 값을 재사용 > 주소가 같음
		System.out.println("String str1 = \"abc\";");
		System.out.println("String str2 = \"abc\";"); 
		
		System.out.println("str1 == str2 ? " + (str1 == str2)); //등가비교연산자는 주소를 비교함
		System.out.println("str1.equals(str2) ? " + str1.equals(str2)); //equals()는 문자열을 비교함
		System.out.println();
		
		String str3 = new String("abc");
		String str4 = new String("abc"); //String클래스의 생성자로 문자열 만들기, 항상 새로운 객체 생성 > 주소가 다름
		
		System.out.println("String str3 = new String(\"abc\");");
		System.out.println("String str4 = new String(\"abc\");");
		
		System.out.println("str3 == str4 ? " + (str3 == str4)); 
		System.out.println("str3.equals(str4) ? " + str3.equals(str4)); 
	}
}
출력값:
String str1 = "abc";
String str2 = "abc";
str1 == str2 ? true
str1.equals(str2) ? true

String str3 = new String("abc");
String str4 = new String("abc");
str3 == str4 ? false
str3.equals(str4) ? true





332p. 예제 9-7

//문자열 리터럴(String리터럴)
class Ex_JS {
	public static void main(String[] args) {
		String s1 = "AAA";
		String s2 = "AAA";
		String s3 = "AAA"; //s1, s2, s3이 모두 같은 객체 AAA를 가르킨다. > 세 객체의 주소가 같다.
		String s4 = "BBB"; //String 객체, 내용변경 불가능
	}
}





333p. 예제 9-8

//빈 문자열(empty string)
class Ex_JS {
	public static void main(String[] args) {
		char[] cArr = new char[0]; //크기가 0인 배열 생성 > 빈 문자열
		String s = new String(cArr); // 빈 문자열로 초기화한 것과 같다.
		
		System.out.println("cArr.lenghth="+cArr.length);
		System.out.println("@@@"+s+"@@@");
	}
}
출력값:
cArr.lenghth=0
@@@@@@





337p. 예제 9-9

//join()과 StringJoiner
import java.util.StringJoiner;

class Ex_JS {
	public static void main(String[] args) {
		String animals = "dog,cat,bear";
		String[] arr   = animals.split(","); //해당 문자를 '기준'으로 자른다.
		
		System.out.println(String.join("-", arr)); //그 자른것을 구분하는 문자를 지정한다.
		
		StringJoiner sj = new StringJoiner("/", "[", "]"); //구분자, 시작, 끝을 지정할 수 있다.
		
		for(String s : arr)
			sj.add(s);
		
		System.out.println(sj.toString());
	}
}
출력값:
dog-cat-bear
[dog/cat/bear]





339p. 예제 9-10

//문자열과 기본형 간의 변환
class Ex_JS {
	public static void main(String[] args) {
		int iVal = 100;
		String strVal = String.valueOf(iVal); //int를 String으로 변환
		
		double dVal = 200.0;
		String strVal2 = dVal + ""; //int를 String으로 변환2
		
		double sum = Integer.parseInt("+"+strVal) + Double.parseDouble(strVal2);
		//문자열>기본형으로 형변환, +는 양수임을 나타낸다.
		double sum2 = Integer.valueOf(strVal) + Double.valueOf(strVal2);
		//문자열>기본형으로 형변환2(valueOf()를 더 자주 쓴다.)
		System.out.println(String.join("",strVal,"+",strVal2,"=")+sum);
		System.out.println(strVal+"+"+strVal2+"="+sum2);
	}
}
출력값:
100+200.0=300.0
100+200.0=300.0





343p. 예제 9-11

//StringBuffer의 비교
class Ex_JS {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("abc");
		StringBuffer sb2 = new StringBuffer("abc");
		
		System.out.println("sb == sb2 ? " + (sb == sb2)); //주소 비교>F
		System.out.println("sb.equals(sb2) ? " + sb.equals(sb2));
		//StringBuffer클래스는 String클래스와 달리 equals()의 오버라이딩이 되어있지 않음, 주소 비교>F
		
		//반면 toString()은 오버라이딩이 되어있음 >문자열을 String으로 반환
		String s = sb.toString();
		String s2 = sb2.toString();
		
		System.out.println("s.equals(s2) ? " + s.equals(s2));
		//String으로 변환 후 equals()로 비교하자.
	}
}
출력값:
sb == sb2 ? false
sb.equals(sb2) ? false
s.equals(s2) ? true





346p. 예제 9-12

//StringBuffer의 생성자와 메서드
class Ex_JS {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("01");
		StringBuffer sb2 = sb.append(23); //sb에 23추가 >0123
		sb.append('4').append(56); //sb에 456추가 >012345
		
		StringBuffer sb3 = sb.append(78);
		sb3.append(9.0);
		
		System.out.println("sb ="+sb);
		System.out.println("sb2="+sb2);
		System.out.println("sb3="+sb3); //sb,sb2,sb3 모두 같은 객체를 가리킴
		
		System.out.println("sb ="+sb.deleteCharAt(10)); //10번째 문자 삭제
		System.out.println("sb ="+sb.delete(3, 6)); //3부터 5번째 문자 삭제
		System.out.println("sb ="+sb.insert(3, "abc")); //3번째에 abc문자열을 삽입
		System.out.println("sb ="+sb.replace(6, sb.length(), "END")); 
		//6번째부터 문자열의 끝까지 문자를 "END"로 바꿈
		System.out.println("capacity="+sb.capacity()); //해당 배열의 버퍼 크기
		System.out.println("length="+sb.length()); //해당 배열의 문자열의 길이
	}
}
출력값:
sb =0123456789.0
sb2=0123456789.0
sb3=0123456789.0
sb =01234567890
sb =01267890
sb =012abc67890
sb =012abcEND
capacity=18
length=9





350p. 예제 9-13

//Math의 메서드
import static java.lang.Math.*;
import static java.lang.System.*;

class Ex_JS {
	public static void main(String args[]) {
		double val = 90.7552;
		out.println("round("+ val +")="+round(val));
		
		val *= 100;
		out.println("round("+ val +")="+round(val));
		
		out.println("round("+ val +")/100  =" + round(val)/100);
		out.println("round("+ val +")/100.0=" + round(val)/100.0);
		out.println();
		out.printf("ceil(%3.1f)=%3.1f%n", 1.1, ceil(1.1));
		out.printf("floor(%3.1f)=%3.1f%n", 1.5, floor(1.5));
		out.printf("round(%3.1f)=%d%n", 1.1, round(1.1));
		out.printf("round(%3.1f)=%d%n", 1.5, round(1.5));
		out.printf("rint(%3.1f)=%f%n", 1.5, rint(1.5));
		out.printf("round(%3.1f)=%d%n", -1.5, round(-1.5));
		out.printf("rint(%3.1f)=%f%n", -1.5, rint(-1.5));
		out.printf("ceil(%3.1f)=%f%n", -1.5, ceil(-1.5));
		out.printf("floor(%3.1f)=%f%n", -1.5, floor(-1.5));
	}
}
출력값:
round(90.7552)=91 //소숫점 첫째자리에서 반올림
round(9075.52)=9076
round(9075.52)/100  =90 //9076을 int 100으로 나눔 > int로 반환
round(9075.52)/100.0=90.76 //실수로 나눔 > 실수로 반환

ceil(1.1)=2.0 //올림
floor(1.5)=1.0 //버림
round(1.1)=1 //반올림
round(1.5)=2 //반올림, 5는 올림
rint(1.5)=2.000000 //가운데는 짝수를 반환
round(-1.5)=-1 //음수이므로 큰쪽으로 반올림
rint(-1.5)=-2.000000 //짝수를 반환하므로
ceil(-1.5)=-1.000000 //올림
floor(-1.5)=-2.000000 //버림





352p. 예제 9-15

//래퍼(wrapper) 클래스
class Ex_JS {
	public static void main(String args[]) {
		Integer i  = new Integer(100);
		Integer i2 = new Integer(100);
		
		System.out.println("i==i2 ? "+(i==i2)); //주소비교, F
		System.out.println("i.equals(i2) ? "+i.equals(i2)); //객체값 비교, T
		System.out.println("i.compareTo(i2)="+i.compareTo(i2)); //같으면 0을 반환, 값 비교
		System.out.println("i.toString()="+i.toString()); //int>문자열로 전환
		
		System.out.println("MAX_VALUE="+Integer.MAX_VALUE); //int와 범위가 같다.
		System.out.println("MIN_VALUE="+Integer.MIN_VALUE);
		System.out.println("SIZE="+Integer.SIZE+" bits"); //int는 32비트
		System.out.println("BYTES="+Integer.BYTES+" bytes"); //4byte
		System.out.println("TYPE="+Integer.TYPE); //int타입
	}
}
출력값:
i==i2 ? false
i.equals(i2) ? true
i.compareTo(i2)=0
i.toString()=100
MAX_VALUE=2147483647
MIN_VALUE=-2147483648
SIZE=32 bits
BYTES=4 bytes
TYPE=int

0개의 댓글

관련 채용 정보