public static void main(String[] args) {
String[] strNum = {"23", "17", "3.141592"};
int i = 0;
try {
for(i=0; i<strNum.length; i++) {
//위에 i값 초기화해줬기 때문에 int 안 붙이고 i=o부터 시작하라고 함.
int x = Integer.parseInt(strNum[i]);
//(int)strNum 안됨. 객체타입을 기본타입으로 바꾸는 것이기 때문에. 기본-기본끼리는 됨.
System.out.println(x);
}
} catch(Exception e) {
System.out.println(strNum[i] + "는 실수이기에 정수로 변환할 수 없습니다.");
}
}
package exception01;
class Animal{};
class Dog extends Animal{};
class Cat extends Animal{};
public class _05_ClassCastException {
public static void main(String[] args) {
try {
Dog dog = new Dog();
Animal ani = dog; //자식을 부모타입으로 변환
Dog dog1 = (Dog)ani; //부모타입을 자식타입으로 강제 변환
System.out.println("Dog 타입으로 변경");
Animal ani2 = new Animal();
Cat cat = (Cat)ani2; //부모타입을 바로 자식타입으로 강제 변환해서 오류.
System.out.println("Cat 타입으로 변경");
}catch(ClassCastException e) {
System.out.println("클래스 타입 변경 불가");
}
}
}
package exception01;
import java.util.InputMismatchException;
import java.util.Scanner;
public class _06_InputMismatchException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("정수 3개 입력: ");
int sum=0;
for(int i=1; i<=3; i++) {
System.out.println(i + "번째 정수 입력");
try { //try를 밖으로 하면 오류났을 때 for문이 안 돌기 때문에 안에
int num = scan.nextInt();
sum += num;
}catch(InputMismatchException e) {
System.out.println("정수가 아닙니다.");
scan.next(); //토큰(줄줄이 이어짐)에 Exception난 것을 버리고 다음 토큰을 가리키도록 함
i--; //오류가 났으면 다시 전으로 돌아가서 새로 입력받을 수 있도록 함
}
}
System.out.println("합 = " + sum);
}
}
-public static void main(String[] args)에 값을 넣어주고 싶다면
Run - Run configurations... - Arguments - Program arguments - 넣을 값 쓰기
System.out.println(Arrays.toString(args));하면 배열값 볼 수 있음
-오류가 났던 내역을 보고싶다면?
e.printStakTrace();
-예외 메세지 보고 싶다면?
System.out.println("예외 메세지: " + e.getMessage());
throw e;
public class _07_Throw {
public static void main(String[] args) { //throws Exception { 너가 알아서 try~catch문 해줘라
try {
Exception e = new Exception("고의로 예외 발생");
throw e;
} catch(Exception e) {
//e.printStackTrace(); =>오류났던 거 나옴
System.out.println("예외 메세지: " + e.getMessage());
}
System.out.println("프로그램 정상 종료");
}
}
public class _09_Throws {
public static void main(String[] args) {
try {
findClass();
System.out.println("클래스 있음");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage() + " 클래스 없음");
}
}
static void findClass() throws ClassNotFoundException { //객체 생성 안 하고 쓰려고 static
Class class2 = Class.forName("java.lang.String2"); //그냥 class만 쓰면 java의 클래스라서 오류남
}
}
사용자 정의 예외:
자바 API에서 제공하지 않는 예외라서 나만의 예외 처리임
예를 들어, 잔고가 출금 금액보다 적으면 예외 처리 구문으로 실행 가능
반드시 상속해야 함
extends [Exception | RuntimeException] {
둘 중 하나는 무조건 상속!
package userException;
public class NotSufficientException extends Exception {
NotSufficientException() { } //사용자가 아무것도 안 넣어도 객체 생성해야되니까
NotSufficientException(String msg) {
super(msg);
}
}
package userException;
public class Account {
private int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public void deposit(int money) {
balance += money;
System.out.println("입금액 " + money +"원이 입금됨");
}
public void withdraw(int money) throws NotSufficientException { //여기서 오류가 날 거 같으니 처리해라
if(balance < money) {
throw new NotSufficientException("잔고 " + (money-balance) + "원 부족"); //고의 오류 호출
}
balance -= money;
}
/*
public void withdraw(int money) {
if(balance < money) {
System.out.println("잔고 " + (money-balance) + "원 부족");
return; //break는 반복문을 빠져나올 때 사용하는 거니까.
}
balance -= money;
}
*/
}
package userException;
public class AccountTest {
public static void main(String[] args) {
Account account = new Account();
account.deposit(100000);
System.out.println("잔액: " + account.getBalance());
try {
account.withdraw(150000);
} catch (NotSufficientException e) {
System.out.println(e.getMessage());
}
System.out.println("잔액: " + account.getBalance());
}
}
=>입금액 100000원이 입금됨
잔액: 100000
잔고 50000원 부족
잔액: 100000
* get,set 메서드는 Source -> Generate getters and setters... -> 넣어줄 메서드 고르고 실행
-다중 try~catch 블럭
public static void main(String[] args) {
String[] str = {"a", "b", "c"};
String[] strNum = {"23", "17", "3.141592"};
int i = 0;
try {
str[1] = "d";
str[2] = "e";
for(i=0; i<strNum.length; i++) {
int x = Integer.parseInt(strNum[i]);
System.out.println(x);
}
int num = 9/0;
} catch(ArrayIndexOutOfBoundsException e) {
//ArrayIndexOutOfBoundsException이기 때문에 해당하는 오류일 때만 출력문 나옴
System.out.println("배열의 크기를 넘어섰습니다.");
}
}
다른 버전
public static void main(String[] args) {
String[] str = {"a", "b", "c"};
String[] strNum = {"23", "17", "3"};
int i = 0;
try {
str[1] = "d";
str[2] = "e";
for(i=0; i<strNum.length; i++) {
int x = Integer.parseInt(strNum[i]);
System.out.println(x);
}
int num = 9/0;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 크기를 넘어섰습니다.");
} catch(NumberFormatException e) {
System.out.println(strNum[i] + "는 실수이기에 정수로 변환할 수 없습니다.");
} catch(ArithmeticException e) {
System.out.println(e.getMessage());
}catch(Exception e) { //Exception은 모든 에러를 가지기 때문에 맨 위에 적으면 밑에 다른 catch문은 오류남
System.out.println(e.getMessage());
} finally { //try~catch 다 끝나고 나서 무조건 실행문, 어차피 println 따로 쓰면 돼서 잘 안 쓰긴 함
System.out.println("프로그램 종료");
}
}
=> 23
17
3
/by zero
프로그램 종료
최상위 클래스. notify(), wait()등은 쓰레드와 관련된 메서드
-★equals(Object a):
==와 같음.
객체 자신과 객체 a가 같은 객체인지 참/거짓을 보려면 오버라이딩을 해줘야함.
public class Value {
int value;
Value(int value) {
this.value = value;
}
@Override //무조건 자식 것이 호출
public boolean equals(Object o) {
//사용자가 어떤 클래스로 객체 생성할지 모르기 때문에 equals의 원형인 최상위 Object클래스 로 써줘야함
return value == ((Value)o).value;
//Object 타입의 o를 자식 타입으로 변환시켜 Value타입의 객체 o가 가지고있는 변수 value값과 int value값과 같은가?
/*
if(o instanceof Value) //부모에서 자식으로 강제형변환했기 때문에 instanceof를 써준 것임
return value == ((Value)o).value;
else
return false;
*/
}
}
public class _01_Equals {
public static void main(String[] args) {
//String에서의 객체 생성
String str = "a";
String str2 = "a"; //new를 따로 안 쓰고 값이 같으면 같은 객체를 가리킴
System.out.println("주소가 같은가? " + (str == str2));
String str3 = new String("a");
String str4 = new String("a"); //얘넨 주소 다른 객체들이 따로 생성
System.out.println("주소가 같은가? " + (str3 == str4));
//Class에서의 객체 생성
Value v1 = new Value(5);
Value v2 = new Value(5); //무조건 new써야 객체 생성됨
System.out.println("v1과 v2 주소가 같은가? " + (v1 == v2));
// String에서는 equals를 오버라이딩 했기 때문에 값 비교가 가능
if(str3.equals(str4))
System.out.println("str3과 str4 값이 같습니다.");
else
System.out.println("str3과 str4 값이 다릅니다.");
//java.lang에 있는 equals()메소드는 주소가 같은가를 비교함
if(v1.equals(v2))
System.out.println("v1과 v2 값이 같습니다.");
else
System.out.println("v1과 v2 값이 다릅니다.");
}
}
-hashCode(): 오버라이딩을 해야 두 객체가 동등한 객체인지 판단함.
잘 안 씀.
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 == str2); //주소가 같은가? ㄴㄴ
System.out.println(str1.hashCode()); //해시코드는 같은가? ㅇㅇ
System.out.println(str2.hashCode());
System.out.println(System.identityHashCode(str1)); //고유로 가지고 있는 해시코드
System.out.println(System.identityHashCode(str2));
//값이 다 다르기 때문에 오버라이딩을 해줌으로써 모두 동일한 결과가 나오도록 함. 고유 해시코드는 고유라서 안 바뀜
}
-★toString(): 객체의 정보를 문자열(16진수 해시코드)로 제공하는 메서드
public class Card {
String kind;
int number;
Card() {
this("SPADE", 7);
}
Card(String kind, int number) {
this.kind = kind;
this.number = number;
}
@Override
public String toString() {
return "종류: " + kind + " 숫자: " + number;
}
}
public class _03_ToString {
public static void main(String[] args) {
Value v1 = new Value(5);
Value v2 = new Value(5);
System.out.println(v1); //객체를 그냥 호출하면 langPackage03.Value@6f2b958e 이렇게 나옴
System.out.println(v1.toString());
//toSting() 메서드 써도 langPackage03.Value@4e718207 이렇게 나와서 굳이 메서드 안 써도 됨
Card card1 = new Card();
Card card2 = new Card("HEART", 10);
System.out.println(card1); //toString 오버라이딩 했기 때문에 주소값이 아닌 설정해준 출력문이 나옴
System.out.println(card2);
}
}
=>langPackage03.Value@6f2b958e
langPackage03.Value@6f2b958e
종류: SPADE 숫자: 7
종류: HEART 숫자: 10
-getClass(): 객체 생성시 뒤에 getClass()를 호출하면 클래스 이름을 호출
public static void main(String[] args) {
Card card3 = new Card("DIA", 8);
Class cObj = new Card().getClass();
System.out.println(cObj);
//해시코드 빼고 이름만 나옴 =>class langPackage03.Card
System.out.println(cObj.getName()); //이것도 가능 =>langPackage03.Card
System.out.println(cObj.toString());
}
-clone(): 객체 자신을 복사하여 새로운 객체 생성
Cloneable을 implements로 반드시 상속 받아야함.
많이 쓰진 않음. 아예 안 쓰는 경향이 있다네요ㄷㄷ
public class Card implements Cloneable {
public Object clone() {
Object obj = null;
try {
obj = super.clone(); //clone 원형이 throws로 되어있기 때문에 try블럭으로 감싸줘야함
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return obj;
}
}
import java.util.Arrays;
public class _04_Clone {
public static void main(String[] args) {
Card card1 = new Card("CLOVER", 3);
Card card2 = (Card)card1.clone(); //card1.clone()이 object 타입이기 때문에 강제변환
System.out.println(card1);
System.out.println(card2);
//배열을 이용해 복제
int[] arr = {1,2,3,4,5};
int[] arrClone = arr.clone(); //object 타입이기 때문에 그냥 이렇게 씀
arrClone[0] =6;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arrClone));
}
}
-문자형 배열(char[])과 그에 관련된 메서드들이 정의되어 있다.
뭔 말이냐면 글자들이 들어오면 배열로 반환해준다는 말
public final class String implements 인스턴스명 {
private char[] value;
.
.
.
class 앞에 final 붙으면 상속해줄 수 없다는 뜻
-String 인스턴스의 내용은 바꿀 수 없다.
다시말해 덮어쓰기라는게 없음.
-★char charAt(int index): 인덱스 번호에 있는 문자를 알려줌
-★int indexOf(char(자.정 책이 잘못썼대) ch):
문자가 문자열에 존재하는지 확인하여 인덱스번호를 알려줌.
-★String[] split(String regex):
문자열을 지정된 분리자로 나누어 문자열 배열에 담아 반환한다
String animals = "dog,cat,bear");
String[] arr = animals.split(",");
=>arr[0] = "dog"
arr[1] = "cat"
arr[2] = "bear"
-★String substring(int begin)
String substring(int begin, int end)
String substring(10);이면 인덱스번호 9번부터 끝까지 가져오는 거임
String substring(5,9);면 인덱스번호 5번부터 8까지 가져오는 거임