예외 발생에 의해 프로그램이 종료되는걸 방지하고 예외 로그를 기록하는데 유용하게 사용할 수 있다.
finally를 사용하면 try-catch문의 예외 발생여부와 상관없이 내부의 코드를 실행할 수 있다.
Method뒤에 throws를 사용하여 메서드 내부에서 발생하는 예외를 자신을 호출 한 메서드에서 처리하도록 할 수 있다.
package study0307;
public class TryCatchEx {
public static void main(String[] args) {
int n = 100;
int r = 0;
for(int i=0; i<3; i++) {
try {
r = n / (int)(Math.random()*10);
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("오류 발생 이유 : "+e.getMessage());
r = 0;
} finally {
System.out.println(r);
}
}
try {
exceptionMethod();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("고장나지 않고 프로그램 종료");
}
//예외 처리를 자신을 호출한 메서드에서 처리
public static void exceptionMethod() throws Exception {
throw new Exception();
}
}
equals메서드의 용도는 변수가 할당받은 주소를 비교하는 것이다. 예외적으로 String은 주소 비교가 아닌 문자열의 값을 비교하도록 override되어 있다.
기본 메서드로 사용할 시 '클래스명@해쉬코드값'을 출력한다. 보통 메서드에서 출력해야 할 값이나 받아오는 값들이 제대로 들어있는지 확인하기 위해 override하여 사용한다.
String클래스는 생성되고 나면 그 값이 수정되지 않는다. 따라서 인스턴스에 새로운 문자열을 더할때마다 새로운 인스턴스가 다시 생성되며, JAVA에서는 이런 불필요한 메모리 낭비를 방지하기 위해 StringBuffer를 제공한다.
package study0307;
public class StringCalctimeEx {
public static void main(String[] args) {
//일반 String
long start = System.currentTimeMillis();
@SuppressWarnings("unused")
String s = "";
for(int i=0; i<100000; i++) {
s += i;
}
long end = System.currentTimeMillis();
System.out.println("Runtime : "+(double)(end - start)/1000);
//StringBuffer
long start2 = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for(int i=0; i<100000; i++) {
sb.append(i);
}
long end2 = System.currentTimeMillis();
System.out.println("Runtime : "+(double)(end2 - start2)/1000);
}
}
//출력
//String Runtime : 8.942초 (변동)
//StrungBuffer Runtime : 0.005초 (변동)
seed를 사용하면 seed가 바뀌지 않는 이상 절대 겹치지 않는 난수를 생성할 수 있다. 다만 각 시드마다 값이 고정되어 있기 때문에 주의해야 한다.
package study0307;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateEx {
public static void main(String[] args) {
Date now = new Date();
//System.out.println(now);
SimpleDateFormat now2 = new SimpleDateFormat("yyyy-MM-dd ");
System.out.print(now2.format(now));
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
String[] arr = {"일요일","월요일","화요일","수요일","목요일","금요일","토요일"};
System.out.print(arr[dayOfWeek-1]);
SimpleDateFormat now3 = new SimpleDateFormat(" HH:mm:ss");
System.out.println(now3.format(now));
}
}
// 출력 : 2022-03-07 월요일 17:10:07
InsatanceName.add(Object); - 배열 추가
InsatanceName.get(indexNum); - 가져오기
package study0307.Shape;
public abstract class Shape {
int x,y;
public Shape() {
this(0,0);
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public String getLocation() {
return "x:"+x+",y:"+y;
}
abstract double area();
abstract double length();
}
package study0307.Shape;
public class Rectangle extends Shape{
int w,h;
public Rectangle() {
this(1,1);
}
public Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
@Override
double area() {
return w*h;
}
@Override
double length() {
return (w+h)*2;
}
}
package study0307.Shape;
public class Circle extends Shape{
double r;
public Circle() {
this(10);
}
public Circle(double r) {
this.r = r;
}
@Override
double area() {
return (r*r)*Math.PI;
}
@Override
double length() {
return (r*2)*Math.PI;
}
}
package study0307.Shape;
import java.util.ArrayList;
import java.util.List;
public class ShapeEx {
public static void main(String[] args) {
List<Shape> l = new ArrayList<Shape>();
l.add(new Rectangle());
l.add(new Rectangle(10, 10));
l.add(new Circle());
l.add(new Circle(10));
sumArea(l);
sumLength(l);
}
static void sumArea(List<Shape> l) {
double sumArea = 0;
for(Shape s : l) {
sumArea += s.area();
}
System.out.printf("모든 도형의 면적합 : %s (%s)\n",Math.round(sumArea),sumArea);
}
static void sumLength(List<Shape> l) {
double sumLength = 0;
for(Shape s : l) {
sumLength += s.length();
}
System.out.printf("모든 도형의 둘레합 : %s (%s)",Math.round(sumLength),sumLength);
}
}
//출력
//모든 도형의 면적합 : 729 (729.3185307179587)
//모든 도형의 둘레합 : 170 (169.66370614359172)
중복을 허용하지 않기 때문에 겹치지 않는 난수를 생성할 때 유용하다. 난수를 따로 정렬하지 않는 HashSet과는 다르게 TreeSet은 크기를 기억하고 정렬하기 때문에 용도에 맞게 사용할 수 있다.
package study0307;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class LottoUseSet {
public static void main(String[] args) {
Random r = new Random();
//Set은 중복값이 발견되면 리스트에서 삭제하기 때문에
//for을 쓰면 출력 개수가 틀려질 수 있다.
//때문에 while문으로 size가 n개 될때 break;를 걸어주는 형식을 쓴다.
Set<Object> lottoHash = new HashSet<Object>();
while(true) {
int n = r.nextInt(45)+1;
lottoHash.add(n);
if(lottoHash.size() == 6) {
break;
}
}
System.out.println(lottoHash);
Set<Object> lottoTree = new TreeSet<Object>();
while(true) {
int n = r.nextInt(45)+1;
lottoTree.add(n);
if(lottoTree.size() == 6) {
break;
}
}
System.out.println(lottoTree);
}
}
컬렉션 프레임워크(List, Set 등)를 활용해 만들어진 인스턴스에 저장된 데이터에 접근하는데 사용된다.
package study0307;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class IteratorEx {
public static void main(String[] args) {
Iterator<Object> it = null;
List<Object> l = new ArrayList<Object>();
Set<Object> s = new HashSet<Object>();
for(int i=0; i<5; i++) {
l.add(i);
s.add(i+5);
}
System.out.println(l);
System.out.println(s);
it = l.iterator();
System.out.println("l Iterator 출력");
iteratorPrint(it);
it = s.iterator();
System.out.println("s Iterator 출력");
iteratorPrint(it);
System.out.println(l);
System.out.println(s);
}
private static void iteratorPrint(Iterator<Object> it) {
//hasNext() - 다음 요소를 가지고 있으면 true, 아니면 false
while(it.hasNext()) {
//next() - 다음 요소를 반환한다.
System.out.print(it.next()+" ");
//remove() - next()로 반환되는 마지막 요소를 현재 컬렉션에서 제거
it.remove();
}
System.out.println();
}
}