210426_1~3(활용편 java.lang.*)
활용편
이미 개발되어있는 클래스 활용하기
1. java.lang.* ;
자바 기본 패키지이다.
자동 참조 되기때문에 import가 필요없다.
1) System : 주로 JVM 자바가상먼신 정보를 제공함
System.out.println() <---콘솔에 출력하고 줄바꿈
System.out.print() <---콘솔에 출력
System.in <---콘솔입력
2) Wrapperclass : 형변환 클래스 : 즉, 기본형 ===>객체형
boolean -> Boolean ,
byte -> Byte,
int -> Integer
... 8가지
래퍼클래스의 특징 : 변수->저장만, 객체형 ->저장+가공(메서드)
Integer it = new Integer("10") ; 기존의 방법
Integer it = 10 ; 최근에는 직접 대입이 가능함 : auto boxing(자동형변환) 기본형--->객체형
auto unboxing 객체형 ---> 기본형
형변환, 자동형변환 기본형<--->기본형 : 값을 변형 : 값을 줄인다
객체형변환 객체형<--->객체형 : 영역 변형 : 영역을 넓힌다 : 하위형으로
package chapter18;
import java.lang.*; //자동임포트이기떄문에 명기하지 않아도된다.
public class Test {
public static void main(String[] args) {
String bin = Integer.toBinaryString(100);// 2진수문자열로바꾸어라
System.out.println("100의 2진수는 : " + bin);
Integer it = new Integer("10");
// Integer it = 10 ; 최근에는 직접 대입이 가능함 : auto boxing(자동형변환) 기본형--->객체형
System.out.println("값 출력 :" + it.intValue());
System.out.println(it = it +10);
int kuk = Integer.parseInt("100"); // 문자열을 정수로바꾸어라
System.out.println("숫자 kuk 값 출력 : " + kuk);
}
}
//100의 2진수는 : 1100100
//값 출력 :10
//20
//숫자 kuk 값 출력 : 100
package chapter18;
class SystemExam {
public static void execTime() { // 스테틱메서드 new를 사용하지않고 사용
long start, end;
float time;
start = System.currentTimeMillis(); // 현재시간을 밀리세컨드로 변환
System.out.println("현재시간 : " + start);
SystemExam.testMethod(); // 20행 실행
end = System.currentTimeMillis(); // end에 끝난시간 대입
System.out.println("반복 종료 시간 : " + end);
time = (end - start) / 1000.0f;
System.out.println("end-start : " + (end - start));
System.out.println("반복에 소요된 시간 : " + time + "초");
}
public static void testMethod() { // 스테틱매서드 new를 사용하지않고 사용
System.out.println("100,000회의 Loop를 반복 시작");
for (int i = 0; i < 100000; i++) {
String str = new String("개구리 왕눈이");
System.out.println(str);
}
System.out.println("100,000회의 Loop를 반복 종료");
}
public static void main(String[] args) { // 메인함수
SystemExam.execTime();
}
}
//....
//개구리 왕눈이
//개구리 왕눈이
//개구리 왕눈이
//개구리 왕눈이
//개구리 왕눈이
//100,000회의 Loop를 반복 종료
//반복 종료 시간 : 1619518778725
//end-start : 977
//반복에 소요된 시간 : 0.977초
3)Math : 수학관련된 함수
Math.메서드() <--- 대부분 정적(static) 멤버로 구성되어 있다.
Math.ceil () 올림함수
Math.floor() 내림함수
Math.round () 반올림함수
*참고 Randum 클래스가 별도로 존재하고, 유용한 메서드가 잔뜩 들어있다.
Math.randum() 난수 발생함수 0~1사이에서 난수가 발생함
max min 사이 발생 : (int) ( d * ( (max-min) +1 ) )+ min
난수의 최근 용도 : 배송번호, 주문번호 등등으로 활용
package chapter18;
public class MathTest {
public static void main(String[] args) {
System.out.println("abs:" + Math.abs(-100)); //절대값 100
System.out.println("ceil:" + Math.ceil(1.1)); //올림 2
System.out.println("floor:" + Math.floor(1.9)); //내림 1.0
System.out.println("(int)(a+0.5f):" + (int) (10.5 + 0.5f)); //11 실수를 정수화(형변환)
System.out.println("round(10.4):" + Math.round(10.4)); //반올림 10
System.out.println("round(10.5):" + Math.round(10.5)); //11
System.out.println("round(10.6):" + Math.round(10.6));//11
System.out.println("----------------------------");
double d;
for (int i = 0; i <= 4; i++) {
d = Math.random(); // 0~1 사이 난수(임의의수)를 발생시킴
int min = 100;
int max = 105;
System.out.println(((int) (d * ((max - min) + 1)) + min));
//100와 105사이의 랜덤한숫자를 5개 출력
}
}
}
4) String : 1. 영역에 상관없이 같은 문자열을 가지면 해쉬코드 동일
2. 문자열을 비교할때 equals() 메서드 사용권장
== X영역비교 , equals () 눈 순순하게 문자열만 비교
3. 문자열이 자주 바뀌면 새로운 문자열 상수 계속 생성함
String사용금지. 대신에 StringBuffer , StringBuilder 사용 <==영역을 연장해서 사용
package chapter18;
class EqualsExam {
public static void main(String[] args) {
String a1 = "STUDY JAVA";
String a2 = "Apple";
String a3 = "APPLE";
System.out.println("A문자열 a1 : " + a1);
System.out.println("B문자열 a2 : " + a2);
System.out.println("C문자열 a3 : " + a3);
System.out.println("D.a2.equals(a3) : " + a2.equals(a3)); //false 대문자 소문자 차이
System.out.println("E.a2.equalsIgnoreCase(a3) : " + a2.equalsIgnoreCase(a3));
//대소문자무시equalsIgnoreCase(),true
if (a2 == "Apple") {
System.out.println("F.a2는 Apple입니다.");
}
String objs = new String("왕눈이");
if (objs == "왕눈이") { //false
System.out.println("G.objs는 왕눈이 입니다.");
} else {
System.out.println("G.objs는 왕눈이가 아닙니다.");
}
String objs2 = new String("왕눈이");
if (objs2.equals("왕눈이")) { //참// 순수문자열비교 equals
System.out.println("H.equals obj2는 왕눈이 입니다.");
}else {
System.out.println("H.objs2는 왕눈이가 아닙니다");
}
}
}
4. equals() : 같냐? 단순문자열비교T/F
compareTo() : 같냐? 크냐? 작냐? 0 음수 양수
'A' - 'B' ==> -1 앞쪽이 작다.
65 66
"가가가" - "가가나" = 음수 // 문자열도 가능하다.
// 기억 사전식 비교라 생각하자. 작은것이 먼저나온다. ABC, 가나다 순 뒤로갈수록크다
package chapter18;
public class CompareTo {
public static void main(String[] args) {
String s1 = "가길동";
String s2 = "가길동";
System.out.println(s1.compareTo(s2));
if (s1.compareTo(s2) < 0) {
System.out.println("s1이 작은 문자열 입니다.");
}
if (s1.compareTo(s2) == 0) {
System.out.println("두 문자열은 같은 문자열입니다.");
}
if (s1.compareTo(s2) > 0) {
System.out.println("s1이 큰 문자열 입니다.");
}
}
}
5) StringBuffer : 문자열이 자주바뀌면 StringBuffer를 사용하자.
메모리 연장해서 사용함 append("문자열") 특히 기억하자
Tread safe가 지원함
(자체가 스레드 안정성이 있다 즉 특정 처리를 하지 않아도 된다.)
자원을 더 많이 사용한다.
Thread Safe :
스레드 안전은 멀티 스레드 프로그래밍에서 일반적으로 어떤 함수나 변수, 혹은 객체가 여러 스레드로부터 동시에 접근이 이루어져도 프로그램의 실행에 문제가 없음을 뜻한다. 보다 엄밀하게는 하나의 함수가 한 스레드로부터 호출되어 실행 중일 때, 다른 스레드가 그 함수를 호출하여 동시에 함께 실행되더라도 각 스레드에서의 함수의 수행 결과가 올바로 나오는 것으로 정의한다. ===>자바에서는 synchronized로 해결한다.
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
package chapter18;
class StringBufferExam1 {
public static void main(String[] args) {
StringBuffer str1 = new StringBuffer("Hello JAVA");
StringBuffer str2 = new StringBuffer("안녕하세요 자바");
System.out.println("버퍼1 문자열 내용 ==>" + str1);
System.out.println("버퍼1 문자열 길이 ==>" + str1.length()); //내용물길이
System.out.println("버퍼1 할당된 용량 ==>" + str1.capacity()); // 할당된용량
System.out.println("버퍼2 문자열 내용 ==>" + str2);
System.out.println("버퍼2 문자열 길이 ==>" + str2.length());
System.out.println("버퍼2 할당된 용량 ==>" + str2.capacity());
}
}
package chapter18;
public class StringBufferExam2 {
public static void main(String[] args) {
StringBuffer str1 = new StringBuffer("☆☆자바");
System.out.println("버퍼에 들어있는 내용 ==>" + str1);
System.out.println("문자열 끼워넣기 ==>" +str1.insert(2, "GOOD"));//insert(번지,스트링)
System.out.println("버퍼의 5번째 문자 ==>" +str1.charAt(4));
str1.setCharAt(0, '★'); //0번째를 검은별로넣어라
System.out.println("0번째 값을 '★'로 변경 ==>"+ str1 );
str1.setLength(6); // 문자열의 길이를 6자로 맞춰라
System.out.println("str1.setLength(6) 지정 후" + str1);
System.out.println("버퍼의 새로운 값==>" + str1);
System.out.println("문자열의 역순출력하기 ==>" + str1.reverse()); //역순출력
System.out.println("내용의 길이 ==>"+str1.length());
System.out.println("할당된 용량 ==>" + str1.capacity());
}
}
6) StringBuilder : StringBuffer와 비슷함. 사용법도 비슷함.
차이는 Thread safe가 지원하지않음.
(자체가 스레드 안정성이 없다. 즉 스레드가 필요하면 특정 처리를 해서 사용해야 된다.
스레드가 안정성이 필요없는 곳에 사용)
package chapter18;
public class StringConvert1 {
public static void main(String[] args) {
String s1 = "새 천년";
String s2 = "대한 민국";
System.out.println("s1 Hash code : " + s1.hashCode());
System.out.println("s2 Hash code : " + s2.hashCode());
System.out.println(s1);
System.out.println(s2);
System.out.println("================================");
s1 += s2;
System.out.println(s1);
System.out.println(s2);
System.out.println("s1 Hash code : " + s1.hashCode());
System.out.println("s2 Hash code : " + s2.hashCode());
//s1의 해쉬코드만 바뀐다
}
}
package chapter18;
public class StringConvert2 {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("새 천년");
System.out.println("s1 Hash code :" + s1.hashCode());
System.out.println("------------------------------");
s1.append("대한 민국"); //append() a1의 해쉬코드가 변하지않는다.
//메모리를 연장해서 사용하기때문
System.out.println(s1);
System.out.println("s1 Hash code : " + s1.hashCode());
}
}