JAVA_19_자바 API

hyeong taek jo·2023년 7월 10일

JAVA

목록 보기
19/39

📌 자바 API

  • 자바 Application Programming Interface의 약어로서 자바 프로그램
    을 작성할 수 있도록 썬 마이크로시스템사에서 제공해주는 클래스

  • 외우지 말 것

  • 몇가지만 외우고 나머지는 그때그때 찾아서 사용할 것

📌1. Calendar 클래스

import java.util.Calendar;

public class Calendar1 {

	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance(); //캘린더 사용법
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+ 1; // 0월 부터
		int date = cal.get(Calendar.DATE);
		
		System.out.printf("오늘은 %d년 %d월 %d일 입니다. \n", year, month, date);
		
		int hour = cal.get(Calendar.HOUR);
		int min  = cal.get(Calendar.MINUTE);
		int sec  = cal.get(Calendar.SECOND);
		
		System.out.printf("지금은 %d : %d : %d 입니다. \n", hour, min, sec);
	}
}

📌2. LocalDateTime 클래스

public class DateTimeOperationExam {

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println(now);
		LocalDateTime targetDateTime = now.plusYears(1);
		System.out.println("연산후 : " + targetDateTime);
	}
}

📌3. GregorianCalendar 크래스

public class GreCal1 {

	public static void main(String[] args) {
		GregorianCalendar gc = new GregorianCalendar();
		
		int year  = gc.get(GregorianCalendar.YEAR);
		int month = gc.get(GregorianCalendar.MONTH)+ 1; // 0월부터
		int day   = gc.get(GregorianCalendar.DATE);
		
		System.out.printf("오늘은 %d년 %d월 %d일 입니다.\n", year, month, day);
		// (E) -> 요일    (a) -> 오전/오후
		//simpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd(E) (a)hh:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd(E) (a)hh:mm:ss"); 
		                                            // 대문자 M은 월, 소문자 m은 분
		Date date = gc.getTime();
		System.out.println(sdf.format(date));

📌4. Integer, valueOf 메서드

public class Integer1 {

	public static void main(String[] args) {
		String str  = "3";
		
		//원시 Date int 반환
		int    int1 = Integer.parseInt(str);
		// Integer 객체반환
		int    int2 = Integer.valueOf("5");
		System.out.println("int1-> "+ int1);
		System.out.println("int2-> "+ int2);
		System.out.println(int1+int2);
		System.out.println("int1 + int2---> " + (int1+int2));
		//"같은거다"라고만 우선 알고 있기
	}
}

📌5. Math 메서드

public class Math3 {

	public static void main(String[] args) {
		int[] i = new int[6];
		
		int count = 0;  // lotto Count
		while(count < 6) {
			int lotto = (int) (Math.random() * 45 ) + 1;
			for(int j = 0 ; j < 6 ; j++) {
				if(lotto == i[j]) {
					lotto = 0; // 중첩 발생
					break;
				}
			}
			if ( lotto > 0 ) {
				i[count] = lotto;
				count ++;
			}
		}
		System.out.println("-----Lotto 당첨번호 조회 -----");
		for(int j = 0; j < i.length ; j++) {
			System.out.println(j + "번째: " + i[j]);
		}
	}
}

📌6. equals 메서드, == 연산자, toString 메서드

toString 메소드를 오버라이딩 하는 경우

class StrPrint {
	String name;
	int    sNum = 7;
	StrPrint (String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "이름 : " + name + " , 번호: " + sNum;
		//return super.toString();
	}
}

public class ToStringEx {

	public static void main(String[] args) {
		StrPrint sp1 = new StrPrint("경찰회의");
		StrPrint sp2 = new StrPrint("간분회의");
		// hash code of the object
		System.out.println("sp1 -> "+ sp1);
		System.out.println("sp1 -> "+ sp2);
		
	}
}

sp1 -> 이름 : 경찰회의 , 번호: 7
sp2 -> 이름 : 간분회의 , 번호: 7

String을 equals할 경우

// equals 메소드는 비교하고자 하는 대상의 내용 자체를 비교하지만
//  ==    연산자는 비교하고자 하는 대상의 주소값을 비교     


public class String1 {

	public static void main(String[] args) {
		String a1 = "Java";
		String a2 = "Java";
		String a3 = new String ("Java"); // 문자열 상수를 생서자에 전달해서 String 객체를 생성한 예
		String a4 = new String ("java"); // j가 소문자임
		System.out.println(a1 + "," + a2 + " , " + a3);
		// == 연산자는 비교하고자 하는 대상의 주소값
		if ( a1 == a2 ) System.out.println("==a1과 a2는 같다");
		else            System.out.println("==a1과 a2는 다르다");
		if ( a1 == a3 ) System.out.println("==a1과 a3는 같다");
		else            System.out.println("==a1과 a3는 다르다");
		
		//equals 메소드는 배교하고자 하는 대상의 내용 자체를 비교
		if (a1.equals(a2)) System.out.println("equals  a1과 a2는 같다");
		else               System.out.println("equals  a1과 a2는 다르다");
		if (a1.equals(a3)) System.out.println("equals  a1과 a3는 같다");
		else               System.out.println("equals  a1과 a3는 다르다");
		
		if (a1.equals(a4)) System.out.println("a1과 a4는 같다");
		else               System.out.println("a1과 a4는 다르다");
		
		//대소문자 무시
		if (a1.equalsIgnoreCase(a4)) System.out.println("a1과 a4는 같다");
		else            System.out.println("a1과 a4는 다르다");
	}
}

객체를 equals할 경우

public class Person {
	int       id;   //key
	String    name;
	
	
	//equals, toString 모두  API다
	
	public Person (int id, String name) {
		this.id    = id;
		this.name  = name;
	}	
		public boolean equals(Object obj) {
			Person p = null;
			Boolean b = false;
			if(obj instanceof Person) p = (Person)obj;
			if(obj != null && this.id==p.id) b = true;
			
			 // return super.equals.(obj);
			return b;
		}
		
		public String toString() {
			String showText = "주민번호: " + this.id + "이름 : " + this.name;
			// return super.toString();
			return showText;
		}
}

public class PersonEx {

	public static void main(String[] args) {
		Person person1 = new Person(111, "김준수" );
		Person person2 = new Person(111, "김준타" );
		if (person1.equals(person2)) System.out.println("같다");
		else System.out.println("다르다");
		
		System.out.println("person1 -> " + person1);
		System.out.println("person1 -> " + person1.toString());
		                                       //toString()생략가능
	}
}

같다
person1 -> 주민번호: 111이름 : 김준수
person1 -> 주민번호: 111이름 : 김준수

📌7. StringTokenizer 클래스

public class StringTokenizer01 {

	public static void main(String[] args) {
		StringTokenizer st = new StringTokenizer("산딸기, 집딸기,판딸기.집딸기,알카리딸기",".,");
		                                                 // "." 과 ","을 기점으로 나눠서 출력
		//StringTokenizer st = new StringTokenizer("산딸기, 집딸기,판딸기.집딸기,알카리딸기",",");
		
		while (st.hasMoreElements()) {
			System.out.println(st.nextElement());
		}
	}
}

📌8. indexOf 메서드

public class String5 {
	
	//substring API
	
	public static void main(String[] args) {
		String fullName = "Hello.java";
		int    index    = fullName.indexOf('.');
		System.out.println("index-> "+index);
		
		String fileName = fullName.substring(0, index);
		String ext      = fullName.substring(index + 1);
		System.out.println(fullName+"의 확장자를 제외한 이름은 " + fileName);
		System.out.println(fullName+"의 확장자는 " + ext);
	}

}
profile
마포구 주민

0개의 댓글