Day 36 (23.02.15)

Jane·2023년 2월 15일
0

IT 수업 정리

목록 보기
41/124

1. 예외처리 연습

throws

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

class JavaPractice {

	public static void main(String[] args) throws IOException {
		Path file = Paths.get("C:\\javastudy\\Simple.txt");
        BufferedWriter writer = null;
        writer = Files.newBufferedWriter(file);
        writer.write('A');    
        writer.write('Z'); 

        if(writer != null)
            writer.close();
		
	}

}

try ~ catch

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

class JavaPractice {

	public static void main(String[] args)  {
		Path file = Paths.get("C:\\javastudy\\Simple.txt");
        BufferedWriter writer = null;
       
		try {
			 writer = Files.newBufferedWriter(file);
		        writer.write('A');    
		        writer.write('Z'); 

		        if(writer != null)
		            writer.close();
		}
		catch(Exception e) {
			e.getMessage();
		}
	}

}

2. Object 클래스의 오버라이딩 활용

2-1. equals 오버라이딩

class INum {
	private int num;

	public INum(int num) {
		this.num = num;
	}

	@Override
	public boolean equals(Object obj) {
		if (this.num == (((INum) obj).num)) {
			return true;
		} else {
			return false;
		}
	}
}

class JavaPractice {

	public static void main(String[] args) {
		INum num1 = new INum(10);
		INum num2 = new INum(12);
		INum num3 = new INum(10);
		
		if(num1.equals(num2)) {
			System.out.println("num1 == num2");
		}else {
			System.out.println("num1 != num2");
		}
		
		if(num1.equals(num3)) {
			System.out.println("num1 == num3");
		}else {
			System.out.println("num1 != num3");
		}
	}

}

[Console]
num1 != num2
num1 == num3


2-2. 나의 클래스에서 @Override한 equals()를 지우고 돌렸을 때

Object 클래스 >> equals

public boolean equals(Object obj) {
	return (this == obj);
}

[Console]
num1 != num2
num1 != num3

  • @Override 하기 전의 Object의 equals(), 내가 만든 클래스의 equals()는 다른 함수이다.
  • 안에 저장되어 있는 값을 비교하는 것과, 참조하는 주소의 번지를 비교하는 것은 다른 개념이다.

INum의 주소 출력

System.out.println(num1);
System.out.println(num2);
System.out.println(num3);

[Console]
INum@4926097b
INum@762efe5d
INum@5d22bbb7

2-3. equals의 오버라이딩을 이용한 예시

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

if (str1 == str2) {
	System.out.println("true");
} else {
	System.out.println("false");
}

if (str1.equals(str2)) {
	System.out.println("true");
} else {
	System.out.println("false");
}

[Console]
false
true


String 클래스 >> equals()

public boolean equals(Object anObject) {
	if (this == anObject) {
		return true;
	}
	if (anObject instanceof String) {
		String aString = (String)anObject;
		if (coder() == aString.coder()) {
			return isLatin1() ? StringLatin1.equals(value, aString.value)
			: StringUTF16.equals(value, aString.value);
		}
	}
	return false;
}

StringLatin1 클래스 >> equals()

public static boolean equals(byte[] value, byte[] other) {
	if (value.length == other.length) {
		for (int i = 0; i < value.length; i++) {
			if (value[i] != other[i]) {
				return false;
 			}
		}
		return true;
	}
	return false;
}

StringUTF16 클래스 >> equals()

public static boolean equals(byte[] value, byte[] other) {
	if (value.length == other.length) {
		int len = value.length >> 1;
			for (int i = 0; i < len; i++) {
				if (getChar(value, i) != getChar(other, i)) {
					return false;
				}
			}
		return true;
	}
	return false;
}

3. 오버라이딩 예제 : 사람의 이름 비교

class Person extends Object{
	private String name;
	
	public Person(String name){
		this.name = name;
	}
	
	public boolean equals(Object obj) {
		if (this.name.equals(((Person) obj).name))
			return true;
		else
			return false;
	}
	
}

class JavaPractice {

	public static void main(String[] args) {
		Person p1 = new Person("홍길동");
	      System.out.println(p1.equals(new Person("홍길동")));
	      System.out.println(p1.equals(new Person("최명태")));
	}

}

[Console]
true
false

  • 문자열의 비교이므로, 다음 코드와 같이 주소 비교로는 X
public boolean equals(Object obj) {
	if (this.name == ((Person) obj).name)
		return true;
	else
		return false;
}
  • instanceof 연산자를 사용하는 방법 (Day 31 참고)
    객체가 클래스를 참조하고 있는지, 형 변환이 가능한지 물어본다.
public boolean equals(Object obj) {
		
	if(obj instanceof Person) {
		Person p = (Person) obj;
			if(this.name.equals(p.name))
				return true;
	}
	return false;
}

4. Wrapper 클래스

4-1. 종류

  • Boolean, Character, Byte, Short, Integer, Long, Float, Double

4-2. Boxing, Unboxing

class JavaPractice {

	public static void main(String[] args) {
    
    	/* Boxing */
		Integer iObj = 10;
	//	Integer iObj = new Integer(10);
		Double dObj = 3.14;
	//	Double dObj = new Double(3.14);
		
		System.out.println(iObj);
		System.out.println(dObj);
		System.out.println();
		
        
        /* Unboxing */
		int num1 = iObj;
		double num2 = dObj;
		
		System.out.println(num1);
		System.out.println(num2);
		
	}

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

0개의 댓글