일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 프로그래밍
- 데이터베이스
- squery
- Project
- 오라클
- html
- DB
- 주말이다..
- 자바
- 공부를열심히
- 객제지향
- 웹프로그래밍
- 객제지향프로그래밍
- 코딩
- 프로젝트
- jsp
- sql
- Java
- 객체지향
- orcle
- CSS
- Oracle
- web
- 테이블
- 공부
- ERWin
- 객체지향프로그래밍
- UI
- 웹
- javascript
- Today
- Total
햄찌개
Java 16일차 자바 주요 클래스 본문
1. java.lang 패키지
- java프로그램에서 기본적으로 필요한 클래스를 모아놓은 패키지이다.
- String, Objects, System, .....
2. objects
- Objects 클래스는 멤버변수 없이 11개의 메서드로 되어있다.
- equals()
: 두 객체의 내용이 같은지 확인하는 Method이다.
: 참조변수가 가르키는 주소를 비교한다.
: 주소가 아닌 변수의 해당 인스턴스가 가지고 있는 값을 비교하게 하려면
equals()를 오버라이드 해야한다.
: equals()가 오버라이드 되어있는 클래스
-> String, File, Date,......
public class EqualsTest01 {
public static void main(String[] args) {
Value v1 = new Value(10);
Value v2 = new Value(10);
System.out.println(v1 == v2);//false
System.out.println(v1.equals(v2));//false
}
}
class Value{
int value;
public Value(int value) {
this.value = value;
}
}
import java.io.Serializable;
public class EqualsTest02 {
public static void main(String[] args) {
Person p1 = new Person(960707L);
Person p2 = new Person(960707L);
System.out.println(p1 == p2); //주소비교해서 false
System.out.println(p1.equals(p2)); //오버라이드 해서 비교 해야 값을 비교
// String a = null;
// System.out.println(a.equals(null)); // 앞에가 null이 오면 안된다.
System.out.println(p1);
System.out.println(p1.hashCode());
}
}
class Person implements Serializable{
long regNo;
public Person(long regNo) {
this.regNo = regNo;
}
@Override
public boolean equals(Object obj) {
Boolean result = false;
if(obj instanceof Person && obj != null){
result = this.regNo == ((Person)obj).regNo;
}
return result;
}
@Override//단축키 : 알트 + 쉬프트 + s => s => 엔터
public String toString() {
return "Person [regNo=" + regNo + "]";
}
}
- hashCode() - 10진수로 이루어져 있다.
: 두 객체가 같은 객체인지 확인하는 Method이다.
: 객체의 주소에서 해시코드를 만들어 반환한다.
: String클래스는 같은 문자열을 가지고 있다면 동일한
해시코드를 반환하게 만들어져 있다.
- toString()
: 인스턴스에 대한 정보를 문자열로 제공할 목적으로 정의한 Method이다.
: Object의 toString()
-> return getClass().gerName()+"@"+Integer.toHexString(hashCode());
: toString()가 오버라이딩 되어있는 클래스
-> String,.....
- getClass()
: 클래스의 정보를 얻어올때 사용한다.
(1)생성된 객체로 부터 얻는 방법
Class obj = new Person().getClass();
(2)클래스 리터럴로부터 얻는 방법
Class obj = Person.class;
(3)클래스의 이름으로 부터 얻는 방법
Class obj = Class.forName("Person");
-> ClassNotFoundException이 발생할 수 있다.
import java.util.Arrays;
public class GetClassTest {
public static void main(String[] args) throws ClassNotFoundException {
//1. 클래스의 정보를 객체로 부터 얻는 방법
Class re1 = new Person(23123123L).getClass();
System.out.println(re1.getName());
System.out.println(Arrays.toString(re1.getInterfaces()));
//2. 클래스의 정보를 리터럴로 부터 얻는 방법
Class re2 = Person.class;
System.out.println(re2.getName());
System.out.println(Arrays.toString(re2.getInterfaces()));
//3. 클래스의 정보를 클래스명으로 부터 얻는 방법
Class re3 = Class.forName("h_javaLang.Person");//페키지명.클래스명 써야 에러가 나지 않는다.
System.out.println(re3.getName());
System.out.println(Arrays.toString(re3.getInterfaces()));
}
}
3. String
- 다른 언어에서는 문자열을 char형 배열로 다룬다.
하지만 java에서는 문자열을 다룰 수 있는 String 클래스를 제공한다.
- 문자열을 합칠때는 합쳐진 문자열을 저장할 인스턴스 새로 생성된다.
- 문자열 비교
: 문자열 리터럴을 만드는 방법과, 객체의 생성자를 이용할수 있다.
public class StringText01 {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2); //true
System.out.println(str1.equals(str2)); //true
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str3 == str4); //false
System.out.println(str3.equals(str4)); //true //equals()가 오버라이드 되어 있어 true
System.out.println(str2.equals(str3));//true
}
}
- 인코딩 변환
: 이클립스의 기본 인코딩 방식은 "MS949"
: 한글 윈도우의 기본 인코딩 방식은 "CP949"
: 우리가 사용하는 인코딩 방식은 "UTF-8"
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class FileEncodingTest {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "가";
byte[] cpStr = str.getBytes("CP949");
byte[] msStr = str.getBytes("MS949");
byte[] utfStr = str.getBytes("UTF-8");
System.out.println(Arrays.toString(cpStr));
System.out.println(Arrays.toString(msStr));
System.out.println(Arrays.toString(utfStr));
}
}
- 문자열 format
:기본형 타입을 String타입으로 변환
1)빈 문자열을 더하는 방식
int a = 10;
String b = a+"";
2)valueOf메서드
String b = String.valueOf(a);
: String 타입을 기본형으로 변환
1)wrapper클래스를 이용하는 방식
String b = "123";
int c = Integer.parseInt(b);
int c = Integer.valueOf(b); //모든 wrapper공통으로 사용
2)wrapper클래스의 진수
String b ="234";
int c = Integer.parseInt(b,8); //b가 8진수로 써있다는 것
4. StringBuffer, StringBuilder
- 문자열을 합치기 위해서 사용한다.
public class StringBufferTest {
public static void main(String[] args) {
/*
String str = "a";
str +="a";
str +="a";
str +="a";
str +="a";
str +="a";
String str = "a";
str = new StringBuffer(str).append("a").toString();
str = new StringBuffer(str).append("a").toString();
*/
String str = "a";
long start = System.currentTimeMillis();
for (int i = 0; i < 30000; i++) {
str+="a";
}
long end = System.currentTimeMillis();
System.out.println(end-start);
long start2 = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("a");
for (int i = 0; i < 30000; i++) {
sb.append("a");
}
long end2 = System.currentTimeMillis();
System.out.println(end2-start2);
long start3 = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("a"); //StringBuilder은 동기화를 보장하지 않아서 더 빠르다.
for (int i = 0; i < 30000; i++) {
sb.append("a");
}
long end3 = System.currentTimeMillis();
System.out.println(end3-start3);
}
}
5. wrapper클래스
- 자바는 모든 것을 객체로 다루어야 한다.
기본형 │ wrapper클래스
boolean │ boolean
char │ Character
byte │ Byte
short │ Short
int │ Integer
long │ Long
float │ Float
double │ Double
- 기본형 타입 -> wrapper클래스 : auto-Boxing
- wrapper클래스 -> 기본형 타입 : unBoxing
public class WrapperTest {
public static void main(String[] args) {
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
System.out.println(i1);//주소가 아니라 값이 나온게 toString()이 오버라이딩 되어있음
System.out.println(i2);//wrapper클래스 모두 toString()오버라이딩
System.out.println(i1 == i2);//false
System.out.println(i1.equals(i2));//true ,wrapper클래스 모두 equals()오버라이딩
Integer[] intArr = new Integer[3];
intArr[0] = new Integer(5);
intArr[1] = new Integer(10);
intArr[2] = new Integer(40);
intArr[0] = 5; //Auto Boxing 자동으로 포장
intArr[1] = 10;
intArr[2] = 40;
int b = intArr[0]; //unBoxing 자동으로 열어준다.
}
}
6. 정규식(Regular Expression)
- 텍스트 데이터에서 원하는 형태의 문장을 찾기 위해 만들어 졌다.
- 정규식 순서
: 패턴정의
-> Pattern클래스를 이용하여 패턴을 정의한다.
Pattern p = Pattern.compile("[a-z]*");
: 텍스트와 비교
-> Matcher클래스를 이용하여 패턴과 텍스트를 비교한다.
Matcher m = p.matcher("text");
m.matcher(); //boolean타임
- 정규식 문법
^ : 문자열 시작
& : 문자열 종료
. : 임의의 한 문자, 역슬러시는 포함되지 않는다.
* : 앞 문자가 없을 수도 무한정 많을 수도 있음
+ : 앞문자가 하나 이상
? : 앞문자가 거나없 하나 있음
() : 문자열을 하나의 문자로 인지한다.
{} : 반복횟수를 지정한다. {3,5} 3번 4번 5번 중에 반복
[] : 범위를 지정할때 사용한다. [abc] abc중에 하나, or은 생략된다.
| : OR연산을 수행할때 사용
\s : 공백문자
\S : 공백을 제외한 모든 문자
\w : 알파벳이나 숫자 [A-Za-z0-9]와 같은 의미
\W : 알파벳 숫자를 제외한 나머지 문자
\d : 숫자를 의미 [0-9]와 같은 의미
\D : 숫자를 제외한 모든 문자
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Qu5_2 {
public static void main(String[] args) {
//1. 텍스트가 영문자가 3회 반복되고 이후에 숫자가 하나 이상으로 구성
//Pattern p1 = Pattern.compile("[A-Za-z]{3}[0-9]+");
Pattern p1 = Pattern.compile("^[A-Za-z]{3}\\d+$");
Matcher m1 = p1.matcher("dfd6666");
System.out.println(m1.matches());
String str ="[A-Za-z]{3}\\d+";
System.out.println(Pattern.matches(str, "dfd666"));
//2. 텍스트가 핸드폰 번호 형태인 '숫자3개-숫자4개-숫자4개'로 구성
Pattern p2 = Pattern.compile("^\\d{3}(-)\\d{4}(-)\\d{4}$");
Matcher m2 = p2.matcher("010-5014-0707");
System.out.println(m2.matches());
//3. 텍스트가 핸드폰 번호로 구성
// 01 다음 0,1,7,8,9 – 0을 제외한 숫자, 숫자3개 – 숫자4개
Pattern p3 = Pattern.compile("^01[0-17-9](-)[1-9][0-9]{3}(-)[0-9]{4}$");
Matcher m3 = p3.matcher("010-5014-0707");
System.out.println(m3.matches());
//4. 텍스트가 주민등록번호로 구성
// 년도 월 일 – 1~4 숫자6개
Pattern p4 = Pattern.compile("^\\d{2}([0][1-9]|[1][0-2])([0][1-9]|[1-2][0-9]|[3][0-1])(-)([1-4][0-9]{6})$");
Matcher m4 = p4.matcher("960707-1012514");
System.out.println(m4.matches());
//5. 텍스트가 이메일로 구성
// 시작은 영문자 이어야 하고 특수기호는 - ,_ , \, . 4가지가 포함될 수 있다.
// @ 이후 영문자가 1개~7개가 포함될 수 있다.
// . 이후 영문자가 2~3개가 포함되어야 한다.
// .kr이 없을 수도 하나 존재 할 수도 있다.
Pattern p5 = Pattern.compile("([a-zA-Z][a-zA-Z0-9-_.\\\\]+)(@)([a-zA-Z]{1,7})(.)([a-zA-Z]{2,3}(.kr)?)");
Matcher m5 = p5.matcher("wlsdnj\\s40.-_5@naver.com.kr");
System.out.println(m5.matches());
}
}
'초급 JAVA' 카테고리의 다른 글
Java 17일차 자바 컬렉션 프레임워크 (0) | 2020.09.03 |
---|---|
Java 15일차 예외 처리 (0) | 2020.09.01 |
Java 14일차 추상클래스, 인터페이스 (0) | 2020.08.31 |
Java 13일차 객체지향의 다형성 (0) | 2020.08.28 |
Java 12일차 객체지향의 제어자 (0) | 2020.08.27 |