'Java 설치 및 이론 정리'에 해당되는 글 1건

  1. 2012.06.20 Java 설치 및 이론 정리

* 2012.2.20 1일차
1.JAVA의 역사(Sum microSystems에서 만듬)

96년도 1.0 버전
------------------1.2버전(이 시기에 엄청나게 많이 바뀌었음, 새로운 개념들이 많이 들어감, 자바의 틀을 잡음. JAVA2라고 부름

------------------1.5버전(이 시기에 엄청나게 많이 바뀌었음, 새로운 개념들이 많이 들어감, 프로그래머들의 요구사항이 많이 들어감.JAVA5라고 부름
현재 1.7버전까지 나옴

2.JAVA 기술군
applet-> 기본적인 움직임이 있는 웹문서

-JAVA ME(Micro Edition)-하드웨어를 기반으로 묵었음. 작은기계에 들어감(ex : 핸드폰)
-JAVA SE(Standard)-표준이 되는 것.PC(ex : 데스크톱(워드프로세서))
-JAVA EE(Enterprise Edition)-기업용 (웹과 프레임워크)

3. 자바 설치
JAVA를 실행하기 위한 프로그램(JRE)
JVM(JAVA VIRTUAL MACHINE) : 자바가상머신.하드웨어를 소프트웨어적으로 구현한것에 자바를 붙인것 (소프트웨어적으로 o/s와 h/w를 구현한것->JAVA program을 실행시켜주는 가상 플랫폼
API( Abstract Programming Interface) :  미리 만들어둔 코드.(라이브러리와 같다.) 자주사용되는 코드들을 미리 만들어 제공.

     O/S와 H/W를 합쳐서 플랫폼이라고 부르며 실행을 할수 있게 해주는 도구이다.
     -JRE(JAVA Runtime Enviornment) 실행환경은 JVM과 API를 합쳐서 말한다. == 자바플랫폼이라고도 부른다.
 JDK-|
     -개발 utility들
(JAVA Develoment kit(자바개발도구))

4.설치
JDK
http://www.oracle.com/index.html
여기서 Java SE 6 UPDATE 31을 받음
라이센스 access하고 windowsx86을 받는다 . 32비트일경우.

next로 설치

-jdk 설치후 환경설정 - name - value 쌍 형태(ex : 이름 =홍길동, 나이 = 20) key - value
시작-내컴퓨터-마우스오른쪽- 속성-고급시스템설정-고급-환경변수
새로만들기
1. 이름  :  JAVA_HOME
   값 :  JDK 설치 경로( C:\Program Files\Java\jdk1.6.0_31 )
2. 이름  :  path
   값 : JDK 설치경로/bin ( C:\Program Files\Java\jdk1.6.0_31\bin ) <-기존에 있는 것 그대로 두고 home키 눌러서 맨앞으로가서 붙여넣기 한 후 ;를 붙여준다.
새로만들기
3. 이름 :  classpath
   값 :  .;

* 2012.2.21 2일차
1. 컴파일드 방식은 빠르지만 interpred방식은 속도가 느리다.
-JAVA는 interpred방식의 프로그램이다.
-한번 만들면 어느곳에서든 그 소스가 돌아가야 한다.
src - 사람이이해하는 방식

 

|
| 컴파일
|
program - 기계가 이해하는(0,1)

2.자바 - 인터프리트방식(속도는 느리지만 플래폼이 독립적이다)
src - 사람(high level언어)
|-> file명.java(ex : HelloWorld.java)
|
|->컴파일 : javac file명.java
|
|->실행 : java class파일명

-실행시점(Runtime)->JVM이 이해하는 말로 만들어짐.
①class Loading - classfile을 메모리에 올리는 작업
②실행-> interpreted방식(실행,구문단위로 기계어로 변경 후 실행)

***컴파일-> class-> byte code-> JVM(byte code는 JVM이 이해하는 언어)

#자바의 특징
1.자바는 플랫폼만 만들어 두면 어느 O/s에서나 다 돌아간다.
2.자바는 객체지향 언어이다.

*객체란? 세상에 존재하는것 (ex : 눈에 보이는것 :  차, 사람, 책상.  관념적인것 : 사람, 계좌)

-객체-속성(attribute)
     |
     -동작(operation)

* 2012.2.22 3일차

1.키워드 - 예약어-> 언어차원에서 사용하기 위해 예약한 단어들.
(ex : class, public, int, double.......)

-자바에서는 참거짓을 true/false로만 표현한다. 0/1은 안된다.
-모든 키워드는 소문자다.

-식별자 이름규칙 : 1.알파벳,숫자(숫자는 두번째 글자부터 가능)
                   2.특수문자 중에는 _,$만 가능하다.
                   3.글자수는 무제한.
                   4.대소문자 구분
                   5.keyword는 식별자로 쓸수 없다.
                   6.class :  모두 소문자, 단어의 첫글자는 대문자
                   7.변수,메소드 :  모두 소문자, 두번째 단어부터 첫글자는 대문자
                   8.final 변수 - 한번 값이 할당되면 못바꿈, 모두 대문자, 단어_단어

2.주석
//한줄짜리 주석
/* */여러줄짜리 주석
/** */ JAVA doc주석

3. 공백 - space, tab, enter :  가독성을 높여준다. program에 영향을 미치지 않는다.
; -> 구문의 종료를 나타낸다.(마침표역할. 실행문의 종료)

4.www.editplus.co.kr
에디트 플러스 다운하기
에디트 플러스 설정'
도구-사용자기본설정(사용자 도구)-> 추가->new program-> 명령 :  javac-> 명령 : C:\Program Files\Java\jdk1.6.0_31\bin\javac.exe
디렉터리 : 현재디렉터리

5.class

한 파일(ABC.java)에
class A{
 }
class B{
 }
로 저장을 하면 class파일은 A.class B.class 두개가생긴다.

6. 생성자(Constructor) - 객체가 생성될 때 한번 호출되어 실행되는 동작.객체가 생성되서 소멸될 때까지 딱 1번만 실행됨
- 호출 : new 생성자()

- 구문 : [제한자] class이름([매개변수,...]){구현}
- 제한자 : public, protected, private : 접근제한자
- return 타입이 없다.
- 이름 :  class 이름과 반드시 같아야 한다.
- 매개변수(parameter)는 0~n개 가질 수 있다.

- default 생성자 : class에 생성자가 한개도 없으면 compiler가 생성해 주는 생성자
구문 : public Class이름(){}

- 생성자 역할 :  instance Member 변수의 값을 초기화(처음 값을 대입)
- 객체가 소멸될때까지 계속 사용할 자원들을 생성.

* 2012.2.23 4일차

1.오버로딩-생성자 -매개변수가 다르다면 같은 이름의 메소드/생성자를 한 class안에 여러개 만들 수 있는 것
          -메소드


- 오류나는 코드(같은 코드내에는 같은 이름의 변수를 쓸수 없다.
int a = 10;
String a = "ABC";
-----------------

-이건 안됨.
void go(){}
void go(){}
-------------

-이건 됨(메소드 오버로딩)
void go(){}
void go(int a){}
-----------------

- class overloading
Student(){}
Student(int a){}
--------------------------

- 메소드 오버로딩을 하는 경우 :  같은 일을 하는데 매개변수(인수)가 다를 경우(이럴 경우 장점은 호출하는 사람이 메소드 이름을 하나만 알면된다.)
(동일하게 덧셈을 하는 경우)
int add(int a,int b){}
double add(double a,double b){}

(ex: System.out.println("aa", System.out.println(10), System.out.println(10.2));
----------------------------------------------------------------------

* this([값,...]);
->생성자에서 overloading 된 다른 생성자 호출.
-생성자 구현부의 첫번째 실행문으로 들어와야 한다.
ex : 
-안되는 경우
Student(){
System.out.println("aaaa");
         this(10);
 }
-----------------------
-되는 경우
Student(){
this(10);
System.out.println("aaaa");
        
}
-----------------------

-this()의 사용
Student(String sid,String n,int a){
 studentId = sid;
 name = n;
 age = a;
}

Student(String sid,String n, int a, int g, int sy){
 /*
 studentId = sid;
 name = n;
 age = a;
 */
 this(sid,n,a);                    <----------------------this()는 이렇게 사용한다.(코드를 좀더 짧게 하는 거지 몰라도 된다).
//만약 new Student(sid,n,a);를 쓰게 되면 새로운 객체를 새로 하나 만든다는 것이고 this(sid,n,a);를 하게 되면 내부적으로 생성자를 불러만 오는 것이다.
 grade = g;
 schoolYear = sy;
}

2. UML
일반
 변수
 제한자 type 이름[=값]

UML에서는
이름 : type = 값
(ex: int age;
     age : int

     String name = "홍길동"
     name :  String ="홍길동"

일반코드  => void eat(String food){}
UML표기법 => eat(food : String) : void

3.메모리관리
Heap 메모리 영역(JVM이 시작시에 만들어 놓고 관리한다) :  객체를 저장하는 영역.

-기본값
숫자 : 0
char : 공백
논리 : false
String : null
숫자,char,논리를 제외한 값은 모두 기본값이 null이다

* 변수에 값은 처음 기본값이 설정이 되고, 다음에 명시적인 값이 설정이 되고, 그 다음에 생성자가 호출되어 값이 설정이 된다.
* 객체명은 객체가 가지는 위치 값(ex :  100번지) 만 갖는다.

*객체 생성시 instance 변수 초기화 3단계
1.묵시적인 초기화(default 초기화) : 변수 type의 기본 값 할당
-기본값
숫자 : 0
char : 공백
논리 : false
String : null
숫자,char,논리를 제외한 값은 모두 기본값이 null이다

2. 명시적 초기화 :  code상에서 대입한 값이 할당됨
3. 생성자 수행에 의한 초기화 :  생성자 실행.

* 객체지향(oop)이라면 알아야할 개념
1. 캡슐화 - 정보은닉
* 접근 제한자 (특정 데이터에 접근을 막아 버리는 것) : class, 메소드, 생성자, instance 변수, static 변수에 사용되는 제한자-> 호출의 범위를 제한하는 역할
-public(UML : +) : 접근에 제한이 없다. (공중화장실) :  UML에서는 +로 표현
-protected(UML : #)
-private(UML : -) : 객체 내에서만 접근 가능.(개인화장실 :  우리집 안에서만 쓸수 있음), 같은 클래스 내의 메소드에서만 접근이 가능하다
-package friendly : 제한자를 붙이지 않으면 package friendly이다.(default 접근제한자라고 부르기도 한다.)


2. 상속
3. 다형성

* 2012.2.27 5일차

1.제한자-①접근제한자(값을 변경, 조회)- 접근 범위를 정해줌.(ex :  public, protected, packagefriendly(아무것도 쓰지 않을경우), private)
         ②보통 제한자(final(한번 값을 넣으면 변경할 수 없음을 제한))


2.private에 접근하기 위해서 변경하는 메소드와 조회하는 메소드를 지원한다.(set(int a), get())

3. 캡슐화(은닉성, 정보 하이딩 기법)
- instance 변수의 접근제한자는 private로 하여 직접 접근하지말고 변수의 값을 변경하는 setter와 조회할수 있는
  getter메소드를 public으로 제공하라.
- setter구문 :  public void set변수명(매개변수 :  변수 type)  int age; public void setAget(int a){}
- getter구문 : public 변수 type get변수명(){}, public int getAget(){}
- boolean : 변수명을 is로 시작하라.

4. 변수

-Local variable : 메소드 안에 선언한 변수.(지역변수 Method variable)(매개변수도 local변수)
 ->사용범위 : 메소드 수행시. 선언부 실행~메소드 종료.
 ->외부에서 호출(접근)불가.
 ->실행 stack(excute stack) 메모리 영역에 저장.  stack 구조는 FILO구조를 가진다.( 먼저들어간게 나중에 나온다.)
 ->묵시적 초기화가 없다.
*객체는 heap영역에 저장.

*변수 = 값
① value(10,20,"ABC")
② 연산(10+20)
③ 변수 int i = 20;
        int j = i;
④ 메소드 호출문 int j = sum(10,20);//리턴값

*Local 변수는 자신이 선언되어 있는 블럭 내에서만 사용가능하다.
ex :

void go(){
 int i = 10;
 {
  System.out.println(i);(가능)
  int j = 20;
 }
 System.out.println(j);(에러)
}

 

5. 데이터 저장

- (실행)stack - 실행 중인 메소드의 local 변수(로컬변수에서 변수는 사용이 끝나면 없어 지므로 (실행) 스택이라는 말을 쓴다.)
- heap  - 객체가 저장.

6. this : 이것(①overloading constructor(생성자),
               ②현재 일하는 메소드, 생성자를 소유한 객체를 가리키는 Local 변수)
          -> 현재 일하고 있는 객체의 주소값을 가리킨다.
          -> instance 메소드나 생성자 호출 시 실행 stack 영역에 가장 먼저 올라간다.

* 2012.2.28 6일차

1. Data type : Data(값)의 구분(종류)
               -> 기준 :  형태, 크기

   -① Primitive Data type(기본 data type)-(ex :  숫자, 문자..(1개의 값 표현밖에 못함))
   -② Reference Data type(참조 data type)-(ex : class(class가 type, 객체(instance) 가 값이된다.)(여러개의 값이 합쳐져 하나의 값을 표현))
       ->Reference Data type의 기본 값은 NULL이다.
(null은 아무 객체도 참조하고 있지 않다는 뜻이다.)
* null값가진변수.xxx->실행시 오류 발생.(Null pointer exception발생)
 
2.타입

①실수 - double(8byte) - 실수형의 기본 type->소수점이하 16자리까지 표현(더 정밀하게 표현한다)
       float(4byte)  - 값F, 값f(ex :  50.2F, 50.2f)->소수점이하 7자리까지 표현

②정수형 - byte(1byte)
  short(2byte)
  int(4byte) - 기본형(20억을 기준으로 사용을 결정한다.)
  long(8byte)


* 10.5->1.05x10->0.105e2
* 1600000000000000 ->16*10^14->16E14

③ 논리형(Logical) - 참/거짓->type은 boolean

   값 : true,false

④ 문자 - char(2byte) : 1글자를 값으로 가진다.
                 값은 ''으로 감싼다.
                 2byte-unicode 한글자
  '\uAOSB(<-유니코드 한글자) -> unicode 1글자(16진수로 나타남)

*escape문자
'\t' - tab
'\n' - enter
'\\' - \문자(역슬러시)
'\'' - '
"\"" - "

3.String - 문자열(0~n글자)을 위한 Data type
         ->class -> Reference Data type
         - new 생성자() 하지 않고 객체 생성

* 사용:

1.변수 = "문자열";
  String s = "ABCDE";
2.변수=new String("문자열");
  String s = new String ("ABCDE");

* 두개의 문자열이 같은지 비교

boolean b = String객체.equals(비교String객체);
        b = "abs".equals("def");
 b = s1.equals(s2)l - s1,s2가 String type

* type이 다른 경우 작은 type 을 큰 type으로 바꾼후 계산한다.
* byte-short-int-long-float-double
      -char

*논리 연산자
- && ->and  true & true -> true 나머진 다 false   (&하나짜리는 뒤에도 검사, &&뒤에짜리는 하나가 참이면 바로 검사를 멈추고 나온다)
- || ->or   false | false ->false 나머진 다 true  (|하나짜리는 뒤에도 검사, ||뒤에짜리는 하나가 참이면 바로 검사를 멈추고 나온다)
- ^->xor  true ^ false -> true
        false ^ true -> true

        t^t->false
        f^f->false
- !->not

!true->false
!false->true

* 조건(삼항)연산자

조건 ? 피연산자1 :  피연산자2;
->boolean- true면 피연산자 1을 쓰고 false면 피연산자 2를쓴다.

int a = (x<5)? 20 :  50;
x가 5보다 작으면 20을 a에 넣고 아니면 50을 넣어라.

* cast 연산자(형변환) :  값의 type을 변환 시켜주는 연산자

- primitive Data type 간의 형변환 가능
- Reference Data type 간의 형변환 가능

사용법 :  (type)값; (int)10.5;

*자동형변환 : upcasting( 작은 type->큰 type)

*명시적코딩 : down casting(큰type->작은type)
 (변수보다 값이 더 큰경우 명시적 형변환이 필요하다)
* primitive Data type에서 형변환을 하면 Data가 깨질수도 있다.

ex :
class TypeCasting{
 public static void main(String[] args)
 {
  
  int var1=10+20; 
  System.out.println("10+20 = "+var1);//String +int->String+String
  
  double var2 = 20+30+25.7;
  System.out.println("20+30+25.7 = "+var2);//String +int->String+String
  
  long var3 = 365L*365*365*365*365*365*5;
 //  long var3 = (long)365*365*365*365*365*365*5;
  System.out.println("365*365*365*365*365*365*365*365*365*365*5 = "+var3);
                //캐스팅 연산 - 대입연산시에만 주의
         boolean b = 'a'<5;
  System.out.println(b); //false나옴
  long I = 10;//(O)
 // int k = 20L;//컴파일 에러
  int l = (int)30L;
  System.out.println(k);//30나옴
  int h = (int)300000000000000000L; //
  System.out.println(h);//이러면 300000000000000000L이 값이 나오지 않음 따라서. 작은 값안으로 강제형변환 하는 것은 좋지 않음.
 }
}


*2012.2.29 7일차

* JAVA datatype - 객체 클래스 - 값을 표현(저장)하는 객체 class :  type역할 Value Object Data Transfer Object
                - 일하는 객체 Business Service


*class를 만드냐 마냐 하는 문제는 무언가를 만들때 데이터를 조합해서 표현해야 하느냐의 문제다.(ex :  나이를 만들때 여러개의 데이터의 조합이 필요한가? 하나의 int값이면 표현할 수 있기에 primitive Data type을 쓴다.

* double이나 float은 계산할때보다 고정된 값을 표현할때 쓴다. 계산시에는 Bigdecimel()을 사용한다. (ex : 키(178.8))(double로 계산하면 컴퓨터가 계산시 계산이 복잡해지고, 잘못된 값이 나올수도 있다)

* 한글자를 표현할때는 unicode를 사용해서 2byte를 사용한다. 따라서 char에서는 ''사이에 한글자를 넣어서 표현한다.

*String type은 객체로써 Reference type으로 class로 만들어져 있지만 primitive type처럼 new를 생성하지 않고 사용한다. (ex :  String name="홍길동"; String name = new String ("홍길동");)

* 문자열 비교는 s1==s2가 아니라 boolean b = s1.equals(s2);로 비교한다.

*byte<short<int<long<float<double

 변수 = 값(변수보다 값의 타입이 더 클 때 강제 형변환의 문제가 생긴다.)

*ex :
class  TypeCasting2
{
 public static void main(String[] args)
 {
  byte b = 10;  //10 : int
  //byte : -128 ~ +127
  //byte b = (byte)10;  //10 : int
  //byte, short는 표시할수 없을 경우는 자동으로 downcasting을 해준다. (단, 값의 범위안에 들어갈 경우)

  //byte c = 200;
  byte c = 100;
  byte d = b+c;//(x) b와 c를 더하면 110으로 127미만이지만 변수를 더했을 경우 계산을 하지 못해 값이 깨질수 있다고 에러가 난다.int형으로 계산을 해서 강제로 casting 해줘야한다.
  byte d = (byte)(b+c);//(O)이렇게 해줘야 byte를 계산한다.
  System.out.println("byte b의 값 : "+b);
 }
}

//TypeCating2.java

* 실행 -> 흐름 : 순차구조
          -> 조건문(분기문) : if,switch case문
          -> 반복문(Loop) : while, for, do while.

* if문
//1.이렇게 하거나
class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
  if(100>=jumsu && jumsu>=90){
   return 'A';
  }else if(jumsu<=89 && jumsu>=80){
   return 'B';
  }else if(jumsu<=79 && jumsu>=70){
   return 'C';
  }else if(jumsu<=69 && jumsu>=60){
   return 'D';
  }else {
   return 'F';
  }

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}


2.
class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
  if(100>=jumsu && jumsu>=90){
   return 'A';
  }else if(jumsu>=80){
   return 'B';
  }else if(jumsu>=70){
   return 'C';
  }else ifjumsu>=60){
   return 'D';
  }else {
   return 'F';
  }

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}
3.

class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
   char grade = ' ';
  if(100>=jumsu && jumsu>=90){
   grade = 'A';
  }else if(jumsu>=80){
   grade = 'B';
  }else if(jumsu>=70){
   grade = 'C';
  }else ifjumsu>=60){
   grade  = 'D';
  }else {
   grade =  'F';
  }
  return grade;

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  if(


  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}

* if 예외처리

class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
 char grade = ' ';
  if(100>=jumsu && jumsu>=90){
   grade= 'A';
  }else if(jumsu<=89 && jumsu>=80){
   grade= 'B';
  }else if(jumsu<=79 && jumsu>=70){
   grade= 'C';
  }else if(jumsu<=69 && jumsu>=60){
   grade= 'D';
  }else if(jumsu<60){
   grade= 'F';
  }
     return grade;
 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  char c4 = grade.checkGrade(150);

  
  System.out.println(c1+","+c2+","+c3);//A,F,B
  if(c4==' '){
  System.out.println("잘못된 잢이 들어갔습니다.");
  }

 }
}

* switch

- switch(식){<- 변수 메소드 호출 type(식에 들어 갈수 있음) :  byte, short, char, int,Enum(jdk 1.5버전부터됨), String(1.7버전부터됨)
case 값1 :
실행구문 A
case 값2 :
실행구문 B
default:
실행구문 C
}
* default는 생략가능
식의 값이 값1이면 A를 실행 , 식의값이 값2이면 B실행 , 값1도 값2도 아니면 default 실행.


(ex :

int i = 2;
switch(i){
case 1:
s.o.p("일");
break;
case 2:
s.o.p("이");
break;
case 3:
s.o.p("삼");
break;
default : 
s.o.p("그밖에");

}


2.
class SwitchTest1{
 public static void main(String[] args)
 {
  //Math.random() : double -> 0<=x<1 실행시 마다 임의적으로 return
  int num = (int)(Math.random()*4)+1; //1~3까지의 수를 찍고 싶으면
  //int num = (int)(Math.random()*51);//0~50을 찍고 싶으면
  System.out.println("num : "+num);
  switch(num){
   case 1:
    System.out.println("스페이드");
   break;
   case 2:
    System.out.println("다이아몬드");
   break;
   case 3:
    System.out.println("클로버");
   break;
   case 4:
    System.out.println("하트");
   break;
  }
 }
}

* 2012.3.5 8일차

1. 메소드(메소드 타입과 명이 사용법을 알려준다.)
2. $와 _는 변수명 앞에 올수 있다.
3. 메소드와 변수명을 길게 정확하게 주는 이유는 이 메소드나 변수가 뭐하는 거구나 알기 위해서이다.
4.for(1(초기식) ; 2(조건식) ; 3(증감식) ){
    4(반복구문)
}

for문의 수행 순서는 1->2->4->3 이다

5. while문 예제

public class WhileTest{

 public static void main(String[] args)
 {
  //1~10출력

  int x = 1;
  while(x<=10){

  System.out.println(x);
  x++;
  }
  System.out.println("-----------------------------");
  printLoop(10,20);
  System.out.println("-----------------------------");
  printLoop(20,10);
 }
 public static void printLoop(int start, int end){
  if(start<=end){
  while(start<=end){
   
   System.out.println(start);
   start++;
  }
  }else if(start>=end){
  while(start>=end)
  {
   System.out.println(start);
   start--;
  }
  }
 }
}


* for문 예제

class forTest
{
 public static void main(String[] args)
 {
  //1~10 for문 이용 출력

  for(int i =1;i<=10;i++){

  System.out.println(i);
  }
  System.out.println("--------------------");
  printLoop(10,20);
  System.out.println("--------------------");
  printLoop(21,8);
 }
 public static void printLoop(int start, int end){
  if(start<=end){
  for(;start<=end;start++){
    System.out.println(start);
  }
  }else{
  for(;start>=end;start--){
    System.out.println(start);
  }
 }

 }
}

* 중접반복문 예제

//중첩 반복문
public class NestedLoop
{
 public static void main(String[] args)
 {
  for(int i = 1;i<=5;i++){
   for(int j=1;j<=5;j++){
    System.out.print(j+" ");
   }
   System.out.println();
  }
 }
}

* 구구단 예제

import java.io.*;
class gugudan
{
 public static void main(String[] args) throws IOException
 {

  int num = System.in.read()-'0';
  for(int i=1;i<=9;i++){
   for(int j = num;j<=9;j++){
    System.out.print(j+"*"+i+"="+i*j+"\t");
   }
   System.out.println();
  }
 }
}


* continue , break 예제

class BreakContinueTest
{
 public static void breakTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  System.out.println(i);
  if(i==5) break;
  }
  
 }
 public static void continueTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  
  if(i==5) continue;
   System.out.println(i);
  }
 
  
 }
 public static void main(String[] args){
  breakTest();
  System.out.println("----------------------");
  continueTest();
 }
}

*BreakContinueTest 2

class BreakContinueTest
{
 public static void breakTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  System.out.println(i);
  if(i==5) break;
  }
  
 }
 public static void continueTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  
  if(i==5) continue;
   System.out.println(i);
  }
 
  
 }
 public static void continueTest2()
 {
  int i=1;
  while(i<=10){
   if(i%2==0){
   i++;// 여기서도 증가를 시켜줘야함
    continue;
   }
   System.out.println(i);
   i++;    //여기서만 i++넣으면 무한 반복 하게 된다.
  }
 
  
 }
 public static void main(String[] args){
  breakTest();
  System.out.println("----------------------");
  continueTest();
  System.out.println("----------------------");
  continueTest2();
 }
}

 

* 반복문 완전 빠져나가기(label1으로 반복문 빠져 나가기)

label1 :  for( ; ; ){
  for( ; ; ){
   break label1;
  }
 }


ex :

a :  while(조건){
 b : while(조건){
  c : while(조건){
   break b;  //반복문 b를 빠져나가라,
   break a;  //반복문 a를 빠져나가라,
   break c;  //반복문 c를 빠져나가라,
  }
 }
}

* 배열 (Array) - 같은 type의 Data를 모아서 관리하는 객체 (상자안에 여러개의 물건을 넣는 방식)
->같은 의미를 가지는 Data들을 모을 때 사용.

배열 변수선언

Datatype[] 식별자
ex :  int[] arr;

- 배열 객체 생성 및 할당

식별자 = new Datatype[length];

length : 모을 수 있는 Data 수


ex :  arr = new int [10];->int data 10개를 모을 수 있는 배열 객체(한번 크기를 정하면 거기서 끝이다.)

- 배열에 값 대입.

변수명 [index]= 값;

대입된 값 사용 :  변수명[index];

* 2012-03-06

- 배열 생성시 값초기화
1.int i[] = {10,,20,30,40};
2.new int[]{10,20,30};


* 배열 ex :

public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }

 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();

 }
}


-배열 선언 ex:
public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }
 
 public void createArray2(){
  //배열 선언, 생성, 값할당(초기화)
  double doubleArray[] = {10.5,203.7,102.3,1.6,2E3};
  System.out.println(doubleArray[0]+"\n"+doubleArray[1]+"\n"+doubleArray[2]+"\n"+doubleArray[3]+"\n"+doubleArray[4]);//2E3 : 2*10.0의 세제곱
  System.out.println("doubleArray의 length : "+doubleArray.length);

//for문을 이용한 출력.
  for(int i = 0;i<doubleArray.length;i++){
   System.out.println("doubleArray["+i+"] = "+doubleArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.

 }
 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();
  at.createArray2();

 }
}

* 배열 예제2

public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }
 
 public void createArray3(){
  //배열 선언, 생성, 값할당(초기화)
  String stringArray[] = new String[]{"가","나","다"};

//for문을 이용한 출력.
  for(int i = 0;i<stringArray.length;i++){
   System.out.println("stringArray["+i+"] = "+stringArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.
  test(new boolean[]{true,false,false,false,true});
 }
 public void test(boolean[] boolArray){
  for(int idx = 0;idx<boolArray.length;idx++){
   System.out.println(boolArray[idx]);
  }
 }
  public void createArray2(){
  //배열 선언, 생성, 값할당(초기화)
  double doubleArray[] = {10.5,203.7,102.3,1.6,2E3};
  System.out.println(doubleArray[0]+"\n"+doubleArray[1]+"\n"+doubleArray[2]+"\n"+doubleArray[3]+"\n"+doubleArray[4]);//2E3 : 2*10.0의 세제곱
  System.out.println("doubleArray의 length : "+doubleArray.length);

//for문을 이용한 출력.
  for(int i = 0;i<doubleArray.length;i++){
   System.out.println("doubleArray["+i+"] = "+doubleArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.

 }
 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();
  at.createArray2();
  at.createArray3();

 }
}

* 향상된 for문(jdk1.5이상부터 가능) = 배열/collection의 값들을 조회할때 사용.

배열 : 0번 idx~마지막 idx의 값 조회.

구문 :  for(변수선언 :  배열객체){
 변수로 작업;
}

ex : int [] arr = {1,2,3,4,5};
for(int i :  arr){
System.out.println(i); //배열의 0~마지막 idx까지 조회할때만 사용한다. 값대입이 안된다.
}


* 배열안에 들어간 숫자 객수 찍어보기

public class ArrayCount
{
 public static void main(String[] args)
 {
  int[] arr = new int[10];
  int[] arrayCount=new int[10];
  //1. arr에 0~9의 숫자를 10개 넣으세요.
  //2. 배열에 들어간 숫자들이 각각 몇개가 들어갔는지 출력하세요.
  for(int i=0;i<arr.length;i++){
   arr[i]=(int)(Math.random()*10);
   System.out.print(arr[i]+" ");
   
   arrayCount[arr[i]]++;
  
  }
  System.out.println();
  for(int i=0;i<arrayCount.length;i++){
   System.out.println("arrayCount["+i+"] = "+arrayCount[i]);
  }
 }
}


*rateTest

public class RateTest
{

 public static void starPrint(int tot){
 for(int i=0;i<tot;i++){
 System.out.print("*");
 }
 }
 public static void main(String[] args)
 {
  int data[] = {10,30,20,80,50};
  double rate[] = new double[5];
  double tot=0;


  for(int i =0;i<data.length;i++){
   tot+=data[i];
  }
  System.out.println(""+tot);
  
  for(int i=0;i<rate.length;i++){
   rate[i]=Math.round(data[i]/tot*100);

   System.out.print(data[i]+" : ");
   starPrint((int)rate[i]);
   System.out.println("<"+rate[i]+"%>");
  }

 }
}


* 클래스 배열

선언 :  Student[] stuArr = new Student[30];
생성 :  stuArr[0] = new Student();
        stuArr[1] = new Student();
값   :  stuArr[0].name ="홍길동";
 stuArr[1].study();


* type
stuArr - Student[]
stuArr[0] - Student


ex :

public class ArrayTestRefType
{
 public void createArray1(){
  Human[] humArray = new Human[3];
  humArray[0] = new Human();
  humArray[1] = new Human("이순신",20,172.3);
  humArray[2] = new Human("홍길동",30,182.5);
  
  humArray[0].printInfo();
  System.out.println("-------------------------");
  humArray[1].printInfo();
  System.out.println("-------------------------");
  humArray[2].printInfo();

  System.out.println("----------for문이용---------------");
  for(int i =0;i<humArray.length;i++){
   humArray[i].printInfo();
   System.out.println("-------------------------");
  }
  System.out.println("----------향상된 for문이용---------------");
  for(Human h : humArray){
   h.printInfo();
   System.out.println("-------------------------");
  }
 }
 public static void main(String[] args)
 {
  ArrayTestRefType atrt = new ArrayTestRefType();
  atrt.createArray1();
 }
}

ex2 :


public class ArrayTestRefType
{
 public void createArray1(){
  Human[] humArray = new Human[3];
  humArray[0] = new Human();
  humArray[1] = new Human("이순신",20,172.3);
  humArray[2] = new Human("홍길동",30,182.5);
  
  humArray[0].printInfo();
  System.out.println("-------------------------");
  humArray[1].printInfo();
  System.out.println("-------------------------");
  humArray[2].printInfo();

  System.out.println("----------for문이용---------------");
  for(int i =0;i<humArray.length;i++){
   humArray[i].printInfo();
   System.out.println("-------------------------");
  }
  System.out.println("----------향상된 for문이용---------------");
  for(Human h : humArray){
   h.printInfo();
   System.out.println("-------------------------");
  }

 }
 public void createArray2(){
  //선언,생성,초기화 한번에 처리
 Human humArray[] = {new Human(), new Human("유재석",41,180.0), new Human("박명수",43,178.5)};
 
 for(int i =0;i<humArray.length;i++){
  humArray[i].printInfo();
  System.out.println("######");

 }
 }
 public static void main(String[] args)
 {
  ArrayTestRefType atrt = new ArrayTestRefType();
  atrt.createArray1();
  atrt.createArray2();
 }
}


* class는 type , 객체는 값 잘기억해라.

* 2012.3.7

1. 2차원배열

-선언 :  Datatype[][] 변수명;

int [][]i;
int[]i[];
inti[][];
다 가능

- 생성 및 변수에 대입

변수명 = new Datatype[length][length];
i = new int[3][2];

* 2차원 배열 ex :
public class TwoDimensionArrayTest
{
 public static void main(String[] args)
 {
  //2010,2011 년도 1월~6월(전반기)강수량을 이차원배열을 통해 넣으세요.


  //double[][] rainfall = {{10,20,30,40,50,60},{10,20,30,40,50,60}};
  double[][] rainfall = new double[2][6];
  for(int i=0;i<rainfall.length;i++){
   for(int j=0;j<rainfall[i].length;j++){

    rainfall[i][j]=Math.random()*100;

   }
  }


  for(int i=0;i<2;i++){
   for(int j=0;j<6;j++){

    System.out.printf("201%d년 %d월 강수량 : %.2f\n",i,(j+1),rainfall[i][j]);

   }
  }
  System.out.println("---------향상된 for문---------------");
  for(double[] firstArr :  rainfall){
   for(double rain : firstArr){
    System.out.print(rain+"\t");
   }
   System.out.println();
  }

 

 }
}


* UML

- DTO (Datatype)


          객체  - data(값)  - VO (value)
                |           - DTO(Data Transfer Object
type(class)     |           - DO(Domain Object)
                |
                |       ->속성 -  setter,getter
                -일하는 객체(Business Logic처리) ->동작
                 ->Business Service, Business Manager라고도 불린다.

*제품만들기 실습
*폴더 : /productManagerArray 만들기

1. ProductDTO클래스를 UML을 보고 작성하세요. 저장은 productManagerArray 폴더에 하세요.
   toString() - 객체의 모든 attribute의 값을 하나의 String으로 만들어 return 하도록 작성.


public class ProductManagerService 
{
 private ProductDTO[] productList;
 private int totalProductCount; //배열로 부터 현재 데이터가 몇개 들어가 있는지를 알게 해줄 변수

 public ProductManagerService(int length){
  productList = new ProductDTO[length];
 }
 public ProductManagerService(){
  productList = new ProductDTO[100];
 }
 //productList에 제품을 추가하는 메소드
 /*
  instance 변수 productList에 인수로 받은 제품 정보를 추가 하는 메소드
 */
 public void addProduct(ProductDTO productDTO){
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  //3. 배열에 제품정보 추가
  //4. totalProductCount의 값을 1 증가.
 
  /*
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  if(totalCount == productList.length){
   System.out.println("제품정보를 넣을 저장 장소가 없습니다.");
   return;
  }
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  for(int i = 0;i<totalProductCount;i++){
   if(productList[i].getProductId().equals(productDTO.getProductId())){
   System.out.println("같은 제품이 있습니다.");
   return;
  }
  
  //3. 배열에 제품정보 추가
  this.productList[totalProductCount]=productDTO;
  //4. totalProductCount의 값을 1 증가.
  totalProductCount++;
   
  }
  }

  */

  System.out.println("함수를 썼을경수");
  if(totalProductCount==productList.length){
   System.out.println("넣을 공간이 없습니다.");
  }
  else if(searchProductById(productDTO.getProductId())!=null){
   System.out.println("같은 제품이 있습니다.");
  }
  else{
   this.productList[totalProductCount]=productDTO;
   totalProductCount++;
  }
 }
 /*
  instance 변수 productList에 저장된 모든 상품의 정보(id~info)를 출력해 주는 메소드
 */
 public void printProductList(){
  for(int i =0;i<totalProductCount;i++){
  System.out.println(productList[i].toString());
  }
 }
 public ProductDTO searchProductById(String productId){
  ProductDTO pDTO = null;
  for(int i =0;i<totalProductCount;i++){
  if(productId.equals(productList[i].getProductId())){
   pDTO=productList[i];
  
   }
  }
  return pDTO;
  
 }
 public void modifyProductInfo(ProductDTO productDTO){
  for(int i=0;i<totalProductCount;i++){
  if(productDTO.getProductId().equals(productList[i].getProductId())){
  productList[i]=productDTO;
  }
  }
  
 }
 public void removeProductById(String productId){
  for(int i=0;i<totalProductCount;i++){
  if(productList[i].getProductId().equals(productId)){
   productList[totalProductCount]=null;
  }
  }
 }
}

* 2012.3.9

ex :


public class TestProductManager
{
 public static void main(String[] args)
 {
  ProductDTO pdto1 = new ProductDTO("p-111","이름",5000,"제조사","정보");
  ProductDTO pdto2 = new ProductDTO("p-222","마우스",12000,"삼성","휠");
  ProductDTO pdto3 = new ProductDTO("p-333","컴퓨터",43000,"LG","무선 마우스");
  ProductDTO pdto4 = new ProductDTO("3333333333","TV",43000,"LG","무선 마우스");
//  System.out.println(pdto1.getProductName());
//  System.out.println(pdto1.toString());

  ProductManagerService pms = new ProductManagerService(30);
  pms.addProduct(pdto1);
  pms.addProduct(pdto2);
  pms.addProduct(pdto3);

  pms.addProduct(null);

  //pms.addProduct(pdto3);

  pms.printProductList();

  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pms.searchProductById("p-111");
  System.out.println("p-111 제품정보 : "+p1.toString());
  ProductDTO p2 = pms.searchProductById("p-222");
  System.out.println("p-222 제품정보 : "+p1.toString());
  ProductDTO p3 = pms.searchProductById("p-333");
  System.out.println("p-333 제품정보 : "+p1.toString());

  //없는 Id로 조회
  ProductDTO p4 = pms.searchProductById("p-555");
  System.out.println("p-111 제품 정보 : "+p4);


  System.out.println("--------------정보수정--------------");
  pdto1 = new ProductDTO("p-111","노트북",15000000,"제조사","정보");
  pdto2 = new ProductDTO("p-222","마우스",1200000000,"삼성","휠");
  pms.modifyProductInfo(pdto1);
  pms.modifyProductInfo(pdto2);
  pms.printProductList();
 

  System.out.println("--------------정보삭제--------------");
  pms.removeProductById("p-222");
  pms.printProductList();
 // System.out.println("-------------------------------");
 // pms.printProductList();
 }
}


----------------------------

public class ProductManagerService 
{
 private ProductDTO[] productList;
 private int totalProductCount; //배열로 부터 현재 데이터가 몇개 들어가 있는지를 알게 해줄 변수

 public ProductManagerService(int length){
  productList = new ProductDTO[length];
 }
 public ProductManagerService(){
  productList = new ProductDTO[100];
 }
 //productList에 제품을 추가하는 메소드
 /*
  instance 변수 productList에 인수로 받은 제품 정보를 추가 하는 메소드
 */
 public void addProduct(ProductDTO productDTO){

  if(isNull(productDTO)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  //3. 배열에 제품정보 추가
  //4. totalProductCount의 값을 1 증가.
 
  
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  if(totalProductCount == productList.length){
   System.out.println("제품정보를 넣을 저장 장소가 없습니다.");
   return;
  }
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  /* for(int i = 0;i<totalProductCount;i++){
   if(productList[i].getProductId().equals(productDTO.getProductId())){
   System.out.println("같은 제품이 있습니다. 아이디를 바꾸세요.");
   return;
   }
  }
  */
  ProductDTO p = searchProductById(productDTO.getProductId());
  if(p!=null){
   System.out.println("같은 제품이 있습니다. 아이디를 바꾸세요.");
   return;
  }
  //3. 배열에 제품정보 추가
  this.productList[totalProductCount]=productDTO;
  //4. totalProductCount의 값을 1 증가.
  totalProductCount++;
   
  
  

  
  /*
  //System.out.println("함수를 썼을경우");
  if(totalProductCount==productList.length){
   System.out.println("넣을 공간이 없습니다.");
  }
  else if(searchProductById(productDTO.getProductId())!=null){
   System.out.println("같은 제품이 있습니다.");
  }
  else{
   this.productList[totalProductCount]=productDTO;
   totalProductCount++;
  }
  */
 }
 /*
  instance 변수 productList에 저장된 모든 상품의 정보(id~info)를 출력해 주는 메소드
 */
 public void printProductList(){
  for(int i =0;i<totalProductCount;i++){
  System.out.println(productList[i].toString());
  }
 }
 /*
  productId를 인수로 받아 productList에서 찾아 그 제품의 정보를 return하는 메소드
  없을 경우 -null을 return
 */
 public ProductDTO searchProductById(String productId){

  ProductDTO pDTO = null;
  if(isNull(productId)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return pDTO;
  }

  for(int i =0;i<totalProductCount;i++){
   if(productId.equals(productList[i].getProductId())){ //조회대상
   pDTO=productList[i];
   break;
   }

  }
//  if(pDTO==null){
//   System.out.println("동일한 ID가 없습니다.");
//  }
  return pDTO;
  /*
   for(int i =0;i<totalProductCount;i++){
   if(productId.equals(productList[i].getProductId())){ //조회대상
   return productList[i];
  
   }

  }
  if(pDTO==null){
   System.out.println("동일한 ID가 없습니다.");
  }
  return null;
  */
 }
 /*
  정보를 수정하는 메소드
  id,이름,가격, 제조사,정보
  수정할 내용을 ProductDTO 객체로 받아서 productList에서 id를 가지고 찾아
  id가 같은 제품의 정보를 인수로 받은 정보로 변경한다.

 */


 public void modifyProductInfo(ProductDTO productDTO){
 

  if(isNull(productDTO)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  for(int i=0;i<totalProductCount;i++){
  if(productDTO.getProductId().equals(productList[i].getProductId())){
   productList[i]=productDTO;
   break;
   }
  }

  
 }
 /*
 인수로 받은 productId를 가지고 productList에서 제품을 찾아 삭제(제거)
 */

 public void removeProductById(String productId){
  
  if(isNull(productId)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  for(int i=0;i<totalProductCount;i++){
  if(productList[i].getProductId().equals(productId)){
  
   for(int j=i;j<totalProductCount-1;j++){
   productList[j]=productList[j+1];
   
   }
//   for(int j=i+1;j<totalProductCount-1;j++){
//   productList[j-1]=productList[j];
//   }

   totalProductCount--;
   productList[totalProductCount]=null;
  
   break;
  }

  }
 }

 private boolean isNull(ProductDTO pdto){
  boolean flag = false;
  if(pdto == null){
   flag = true;
  }
  return flag;
 }
 private boolean isNull(String str){
  boolean flag = false;
  if(str == null){
   flag = true;
  }
  return flag;
 }
}

-------------------------------------

public class  ProductDTO
{
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;

 public ProductDTO(){}
 public ProductDTO(String productId, String productName, int productPrice, String productMaker, String productInfo){
  this.productId=productId;
  this.productName=productName;
  this.productPrice=productPrice;
  this.productMaker=productMaker;
  this.productInfo=productInfo;
 }
 public String getProductId(){
  return productId;
 }
 public void setProductId(String productId){
  this.productId = productId;
 }
 public String getProductName(){
  return productName;
 }
 public void setProductName(String productName){
  this.productName = productName;
 }
 public int getProductPrice(){
  return productPrice;
 }
 public void setProductName(int productPrice){
  this.productPrice = productPrice;
 }
 public String getProductMaker(){
  return productMaker;
 }
 public void setProductMaker(String productMaker){
  this.productMaker = productMaker;
 }
 public String getProductInfo(){
  return productInfo;
 }
 public void setProductInfo(String productInfo){
  this.productInfo = productInfo;
 }
 public String toString(){
  return productId+" "+productName+" "+productPrice+" "+productMaker+" "+productInfo;
 }

}

============================================================

ex :

public class CommandLineArgs 
{
 //JVM은 실행 시 (java class명) 입력한 값을 main()의 인자로 넘겨준다.
 //예 : java CommandLineArgs A ABC 안녕 -> length 가 3인 배열을 만들어 A, ABC, 안녕
 //값을 넣어 main메소드의 인자로 넘긴다.
 public static void main(String[] args)
 {
  System.out.println("args.length : "+ args.length);
  System.out.println("------command line argument로 넘어온 값들-------------");
  for(int i = 0;i<args.length;i++){
   System.out.println(args[i]);
  }

 }
}

//CommandLineArgs.java
//java CommandLineArgs 안녕 반갑습니다 abc
//java CommandLineArgs "안녕 반갑습니다 abc"


- package -  class파일을 모아 놓은 directory(folder).(class가 들어가 있는 패스주소.)->src 코드 작성시 class가 어느 package안에 들어갈 것인지 선언해야한다.

구문 :
package Root_package이름.sub_package명.;  <- sub경로가 없으면 .sub_package명.은 생략가능.(package는 같은 역할을 하는 여러개의 class가 모여진 folder이다.)
package 선언은 소스코드 file당 한번만 할 수 있다.

package 선언은 소스코드의 첫 실행(명령)문으로 와야만한다.
package 명은 식별자 규칙에 따라 준다.
-관례 :  소문자, domain명 꺼꾸로(ex : 도메인 주소가 kosta.or.kr이라면 kr.or.kosta

ex :
package value;

package ab.cd.ef; ->ab/cd/ef
- import = class에서 class를 부를때 파일이 어딨는지 알려준다.

*package, import 예제

//import kosta.dto.Human;
//import kosta.dto.CarDTO;

import kosta.dto.*;
public class TestImport
{
 public static void main(String[] args)
 {
  Human h = new Human("홍길동",23,170.4);
  h.printInfo();
  CarDTO c = new CarDTO();
  c.go();
  }
}

//package 디렉토리 아래 TestImport.java로 저장

//새이름으로 저장 : package 디렉토리 아래에 Human.java로 저장
package kosta.dto;
public class Human
{
 private String name ;
 public int age;
 public double tall;
 public Human(){}
 public Human(String name, int age, double tall){
  this.name=name;
  this.age=age;
  this.tall=tall;
 }

 public void setName(String name){
  this.name = name;
 }
 public String getName(){
  return name;
 }
 public void printInfo(){
  System.out.println(name);
  System.out.println(age);
  System.out.println(tall);
 }

}


//패키지 선언 :  이 클래스가 위치할 경로(디렉토리)를 선언하는 것
package kosta.dto; // /kosta/dto/CarDTO.class
public class CarDTO
{
 private String name;
 private String engine;
 
 public String toString(){
  return "이름 : " +name+",엔진 종류 : "+engine;
 }
 public void go(){
  System.out.println(name+"가 출발합니다.");
 }
}
// package/CarDTO.java

 


* java.lang 패키지의 class들은 import 없이 사용가능.

String,System, Math class등등..(사용을 하려면 API documentation을 확인하면됨. sun에서 제공해주는 설명서)

www.oracle.com(API 다큐멘테이션)

download-> java for develop -> Additional Resources-> Java SE6 Documentation 다운로드


* 2012.3.12


* http://www.eclipse.org/downloads/
들어가서

Eclipse IDE for Java EE Developers, 212 MB Windows 32 Bit 다운

* eclipse(개발시 개발에 필요한 tools을 모아둔 것(ex :  editor, 디버깅, 서버연결,  형상관리, 안드로이드)

- perspective(개발하고자 하는 환경적인 개념. (안드로이드를 개발할거냐, 웹을 개발할거냐, JAVA EE를 개발할거냐등으로 나뉜다.)
- view(Java의 기업용 어플리케이션을 개발할때 필요한 화면, DB, 서버, 코드)
- 하나의 perspective안에 여러개의 view가 모여있다. 
                           
-위에 window preperence는 속성을 저장해둔거임

* 파일생성
Package Explorer에서 마우스 오른쪽 눌러서 new->Java Project를 눌러서 Project Name 선택
name :  day01
입력 후 next누름.
소스코드는 src에 컴파일한 파일(class파일)은 day01/bin에 들어간다.

* window->preperences->java->Installed JREs 가면 jdk 경로로 되어 있어야 한다.
만약 jre로 되어 있으면 editor 선택해서 Directory들어가서 jdk를 선택해서 넣는다.


*소스 만들기

프로젝트 파일에서 src->new->class

window->preperence-> 텍스트창에(syntax입력)하면 syntax Coloring에서 들어가면 컬러가 지정된 것들이 나온다.

* name :  HumanDTO
  Package :  kosta.dto

* 소스 넣기위한 자리에 커서 놓고 마우스 오른쪽 source->Generate Constructor Using Feild(생성자 만들기)
source->Generate getter/setter

* 소스파일 작성에 대한 규칙
-src file Layout

package선언은 1번
import 구문 - 0~n번
class 선언 및 구현
한 파일당 class 선언 및 구현은 여러개 가능
public class는 파일당 하나만 가능
+class A{}
 class B{}
 class C{}
file명 :  A.java
javac A.java를 하게되면 A.class, B.class, C.class가 생긴다.

public class 이름->src코드 file명.
.class 파일은 class 선언당 하나씩 생긴다.
class안에서 생성자, 메소드, attribute 순서는 상관없다.

* static - 메소드, Attribute(local 변수 X(로컬변수는 class꺼라기보다 메소드 것이기 때문)), nested class(class안에 선언된 class)에 사용되는 제한자(moditier)
nested class 예제
static(x) class A{
 static classB{}
}

- staic은 class의 멤버가 된다.
- 객체의 것이 아니라 class것이다. (객체와는 관계 없다)
- 호출 : class이름.멤버
class A{
static int a;
staic void go(){}
}
이렇게 했을시 접근은 A.a=10; A.go();로 호출 가능하다.

ex :
Math.random();
System.out.println();
random()과 println()이 Math라는 class와 System이라는 클래스안에 static으로 되어 있어서 접근 가능하다.

* static변수 , static 메소드는 그 class에서 생성된 모든 객체들이 똑같은 값(변수)과 똑같은 기능을 실행하는 경우(메소드) class의 멤버(소속)으로 처리한다.
ex :  static double pi == 3.141592;
      static double sin(double a){}

* 대표 static class는 java.lang.Math

************** static을 하는 가장 중요한 이유는 어떤 것을 호출 하든지 같은 결과가 나오기 때문이다.

구문, 변수
접근제한자 static type 이름[=값];
메소드
접근제한자 static returntype 이름([매개변수]){}

* instance멤버 변수
class 멤버 변수(static 변수)->Field(class 블럭에 선언된 변수)

* class
package : statictest
Name :  StaticTest

package : statictest
Name :  CustomerDTO


ex :

package statictest;

public class StaticTest {
 public static void main(String[] args) {
  //CustomerDTO 객체 3개 생성
  CustomerDTO c1 = new CustomerDTO("홍길동", 20);
  CustomerDTO c2 = new CustomerDTO("이순신", 28);
  CustomerDTO c3 = new CustomerDTO("길무스", 20);
  
  System.out.println(c1.getName());
  System.out.println(c2.getName());
  //어떤 객체한테 일을 시켰느냐에 따라 결과가 다르게 나온다. 그래서 getter/setter는 객체껄로 한다. 구현은 class에 했어도 객체꺼다. 객체를 생성해야지만 사용가능하다.
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c1.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c2.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c3.getTotalInstanceCount());

  CustomerDTO c4 = new CustomerDTO();  

  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());//static변수를 사용해서 class의 메소드로 만들고 class명.메소드이름 으로 count에 접근하게 한다.
 }
}


-------------------------

package statictest;

public class CustomerDTO {
 private String name;
 private int age;
 private static int totalInstanceCount=0;   //클래스에서 생성된 객체의 개수를 저장.
 
 
 //생성자, setter,getter, toString()
 public CustomerDTO(){
  totalInstanceCount++;
 }

 public CustomerDTO(String name, int age) {
  this.name = name;
  this.age = age;
  totalInstanceCount++;
 }

 public static int getTotalInstanceCount(){
  return totalInstanceCount;
 }
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public String toString() {
  return "CustomerDTO [name=" + name + ", age=" + age + "]";
 }


 
}
----------------------------

* 메소드 안에 선언되면 local변수로 스택에 저장된다. args,c1,c2,c3,c4
* class 변수 static붙은 변수 totalInstanceCount
* instance변수는 private로 class에 선언된 변수는 힙에 저장된다. name,age

* compile 시점
1. class Loading ->이 시점에 static변수나 static 메소드는 메모리에 올라온다.
2. 실행 -> main()

메소드 영역                           static영역                              Coastant Pool
->메소드 코드                         ->static 멤버 -변수                     ->final 변수
                                                    -메소드 
CustomerDTO(){}                       int totalInstanceCount;
CustomerDTO(String name,int age){}    getTotalInstanceCount(){}
getName(){}
setName(){}
getAge(){}
setAge(){}
gettotalInstanceCount(){}

class영역(Area)->class별로 구분

* static 변수는 메인 메소드 실행전에 class 로딩시에 하나만 만들어 지고(class에 만들어짐) Instance변수는 객체 생성시마다 여러개가 생성된다.

* static영역은 코드만 있고 직접 접근이 안되서 실행시 클래스로 접근해야 하고, Instance영역은 객체를 통해서 접근해야 한다.
 
* static변수의 묵시적인 초기화 예제

package statictest;

public class StaticTest {
 public static void main(String[] args) {
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());
  //CustomerDTO 객체 3개 생성
  CustomerDTO c1 = new CustomerDTO("홍길동", 20);
  CustomerDTO c2 = new CustomerDTO("이순신", 28);
  CustomerDTO c3 = new CustomerDTO("길무스", 20);
  
  System.out.println(c1.getName());
  System.out.println(c2.getName());
  //어떤 객체한테 일을 시켰느냐에 따라 결과가 다르게 나온다. 그래서 getter/setter는 객체껄로 한다. 구현은 class에 했어도 객체꺼다. 객체를 생성해야지만 사용가능하다.
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c1.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c2.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c3.getTotalInstanceCount());
  
  CustomerDTO c4 = new CustomerDTO();
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());//static변수를 사용해서 class의 메소드로 만들고 class명.메소드이름 으로 count에 접근하게 한다.
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());
 }
}

실행화면 :

지금까지 CustomerDTO class에서 생성된 객체의 개수 :  0
홍길동
이순신
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  4
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  4


-------------------------------

 
* 생성 시점이 달라서 static 메소드 안에 Instance객체나 메소드를 부를수 없다.
  만약 부르고 싶다면 static 메소드 안에서 객체를 생성해서 객체를 통해서 접근해야 한다.
  static 메소드는 static 멤버만 접근 가능하다. -> Instance 변수, Instance 메소드는 접근 불가.


*
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
변수종류            |   선언             |   묵시적 초기화(default초기화) |  저장 메모리 영역                |   점근 범위 scope(변수의 lifecycle)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      | instance    |   class block내    |              0                 |       Heap                       |   객체생성~객체 소멸까지(X)(객체를 참조할 수 있을 때까지(O) :  만약에 CDTO c = new CDTO();생성 후 c = null;해서 주소를 지워버리면 객체의 접근 범위가 사라진다. )
field |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      | static변수  |   class block내    |              0                 |       class영역의 static영역     |   program 시작~program이 종료
      | (class변수) |   (static 제한자)  |                                |                                  |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local               |    메소드 block내  |              x                 |   실행 stack                 |   메소드가 실행하는 동안->선언부 실행
                    |                    |                                |                                  |   메소드 시작~메소드 종료
method              |                    |                                |                                  |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

* 정적 초기화영역

class A{
 static{

}
}

1. class loading
2. static block실행
3. main()

ex :  class A{
 private static CustomerDTO c;
 static{
  c = new CDTO();
 }
}

* static 블럭 실행 시점 예제

* class
package : staictest
Name : StaticBlockTest

 

package statictest;

public class StaticBlockTest {
  static{
   System.out.println("static 블럭 1");
  }
  public static void main(String[] args) {
   System.out.println("메인 메소드 실행");
  }
}

----------------
실행화면
static 블럭 1
메인 메소드 실행
(메인보다 static블럭1이 먼저 실행된 것을 볼 수 있다. )
-------------------------------------------

예제2

package statictest;

public class StaticBlockTest {
  static{
   System.out.println("static 블럭 1");
  }
  static{
   System.out.println("static 블럭 2");
  }
}
-------------------------------------------------

실행 화면

static 블럭 1
static 블럭 2
java.lang.NoSuchMethodError: main
Exception in thread "main"

static블럭 찍게 되면 순서 대로 나오고 메인이 없어서 메인이 없다는 에러를 내준다.
----------------------------------------------------

* instance 변수 - 객체마다 다른 값을 가지면 사용한다.
* static 변수 - 공통적인 값, 공통코드값(PI, 비율, 세율) : 비지니스 로직이 많다.

* 싱글턴 디자인 패턴 -> 일하는 객체를 정의하는 class(우리가 했던 것 중에는 productManagerService, ProductDTO(관리하는 사람은 한 사람만 필요하다.)) ->Business Service
- 클래스를 만들때 객체를 오직 하나만 만들수 있는 class(오직 하나의 객체를 공유한다)

ex :
DTO는 값을 표현하기 위해서 만들어진 객체기 때문에 객체를 하나만 부를수는 없다.


* 2012-3-13

* 싱글턴 패턴

package statictest;

public class TestSingleton {

 /**
  * @param args
  */
 public static void main(String[] args) {
  SingletonClass sc1 = SingletonClass.getInstance();
  sc1.setNum(100);
  SingletonClass sc2 = SingletonClass.getInstance();
  System.out.println(sc2.getNum());
  
  SingletonClass2 sc3 = SingletonClass2.getInstance();
  sc3.setNum(200);
  SingletonClass2 sc4 = SingletonClass2.getInstance();
  System.out.println(sc4.getNum());

 }

}

----------------------------------

package statictest;
/*싱클톤 패턴
1. 생성자의 접근 제한자를 private
2. private static 변수로 자신의 타입의 변수를 선언
3. public static 메소드를 통해 2번의 static 변수에 할당된 자신 타입의 객체를 return
*/
public class SingletonClass {
 private static SingletonClass instance = new SingletonClass();
 private int num;
 private SingletonClass(){}
 public static SingletonClass getInstance(){
  return instance;
 }
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 
}

------------------------------------

package statictest;

public class SingletonClass2 {
 private static SingletonClass2 instance;
 private int num;
 private SingletonClass2(){}
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 //처음 요청이 들어왔을때 객체를 생성하여 객체 생성을 늦추는 방식.
 public static SingletonClass2 getInstance() {
  if(instance == null){
   instance = new SingletonClass2();
  }
  return instance;
 }
 
}

----------------------------------------

* alt+shift+R 리네임
* alt+shift+s getter/setter키


*project : productManager_Array
package : ProductManagerService -> product.service
   ProductDTO -> product.dto
class : ProductManagerService -> 싱글톤 패턴으로 변경

* 상속(Inheritance) : 기존의 class에 정의된 변수나 메소드를 재사용하여 새로운 class를 만드는것(물려받는것.- 확장성이 좋아짐)
->객체간의 상속

 

하나의 클래스에서 똑같은 코드를 물려 받아서 사용하는것.
부모-자식 관계

* 객체지향의 장점
1. 확장성
2. 재사용성
3. 유지보수

 

개 : 이름, 성별, 무게, 나이 , 색, 종, 키
      짖는다(),배설한다(),먹는다(),잔다()
고양이 :  이름, 성별, 무게, 나이, 종, 색, 키
  운다(), 배설한다(), 핱힌다(), 먹는다(), 잔다()
사람 : 이름, 나이, 성별, 무게, 키, 국적, 혈액형
          잔다(), 먹는다(), 말한다(), 일한다(),

동물 :  이름, 성별, 무게, 나이, 키
           먹는다(), 배설한다(), 잔다()

* 개, 고양이, 사람은 동물이기에 공통적인 속성을 동물에게 상속받는다.

물려주는 동물 class를 부모(super)class라 하고
물려받는 개, 사람, 고양이는 자식(sub)class라 한다.

* 상속 : is a 관계
-개(서브class) is a 동물(super class)
  개는 동물이다.
- 동물이면 개다.(x)

----------동물-----------
|                         -개 --           |
|                         |        |            |
|                         -----            |
-------------------------

- 동물의 type > 개의 type
   부모 type > 자식 type

* 상속 관계 일때만 type을 부모가 자식보다 type이 크다고 할수 있다.
(다형성에서 부모type이 자식type 보다 더 크다는 것을 사용한다.)
(부모는 추상적, 자식은 구체적)

* 추상화 :  공통점을 뽑아 내는것.(공통적인 것을 뽑아내서 새로운 것을 만들어 내는것.)
(고양이와, 개에 종과, 색이 공통적으로 있지만 사람에 없기때문에 동물로 빼낼 수 없다.)

* 다중 상속 : 부모class를 여러개 갖는것.
* 단일 상속 :  부모class를 하나만 갖는것.

* 자바는 단일 상속을 지원한다. ->class간의 상속을 할 시에는 단일 상속을 지원한다. (여러개의 상속을 하기 위해서는 interface를 지원한다)

동물                                                어류
키, 나이, 성별, 이름
먹는다(), 잔다()                          헤엄친다(), 먹는다()
           ^                                                   ^
           |                                                    |
           ---------------------------
   사람
   국적, 혈액형
   생각한다(), 말한다()

* 다중상속을 하면 상속에 상속을 갖는 구조가 되어 중복되는 메소드가 생겨 오류가 생길 수 있다.
(설계시 코드가 복잡하고 못쓰는 메소드가 생길 수 있어서 자바는 다중 상속을 지원하지 않는다. )

anmal(super class)
 ^
 | (상속)
Human(sub class)

- 코드구현

public class Animal {}
public class Human extends Animal{}

[제한자]class 식별자 extends 부모class이름{ 구현 }

* 상속되어 있는 부모 class가 없으면 object class(최상위 class)가 보이진 않지만 java.lang.Object가 상속되어 있다.
public class Animal extends Object{}

*사람으로 따지면 단군할아버지다.
-Object class에는 속성은 없고 메소드만 가지고 있다. ex :  toString(){}

*
Employee(직원)
-------------
+ id : String
+ name : String
+ salary : int
-------------
+getDetails() : String


Manager(관리자)
--------------
+ id : String
+ name : String
+ salary : int                                             //id,name,dalary,getDetails()는 직원의 것을 가져다 쓴다.
+department : String
---------------
+getDetails() : String


project : day15
package : inheritance.member
class : Employee
    Manager


//MemberTest.java

package inheritance.member;

/*public class MemberTest {
 public static void main(String[] args) {
  Employee emp = new Employee();
  emp.id = "emp-111";
  emp.name = "홍길동";
  emp.salary = 10000000;
  
  String str = emp.getDetails();
  System.out.println(str);
  
  
  Manager man = new Manager();
  man.id = "man-111";
  man.name = "이순신";
  man.salary = 2000000;
  man.department = "개발부";
   str = man.getDetails();
  System.out.println(str);
 }
}
*//*
public class MemberTest {
 public static void main(String[] args) {
  Employee emp = new Employee();
  emp.setId("emp-111");
  emp.setName("홍길동");
  emp.setSalary(10000000);
  
  String str = emp.getDetails();
  System.out.println(str);
  
  
  Manager man = new Manager();
  man.setId("man-111");
  man.setName("이순신");
  man.setSalary(2000000);
  man.department = "개발부";
  str = man.getDetails();
  System.out.println(str);
 }
}
*/
public class MemberTest {
 public static void main(String[] args) {
 Manager m = new Manager("m-111","이순신",200000,"영업부");
 String str = m.getDetails();
 System.out.println(str);
 }
}

 

//Manager.java

package inheritance.member;

public class Manager extends Employee{
 public String department;
 
 public Manager(){}
 public Manager(String id, String name, int salary, String department){
  
//  this.id = id;
//  this.name = name;
//  this.department = department;
  
  super(id,name,salary);
  this.department = department;
  
 }
 public String getDetails(){
  return  this.getClass().getSimpleName()+"[id=" + super.getId() + ", name=" + super.getName() + ", salary=" + super.getSalary()+" department = "+department+ "]";
  
 }
}


//Employee.java

package inheritance.member;

public class Employee {
 private String id;
 private String name;
 private int salary;
 
 //생성자
 public Employee(String id, String name, int salary){
  this.id = id;
  this.name = name;
  this.salary = salary;
 }
 public Employee(){}  //습관적으로 no-argument 생성자를 만들어라
 public String getDetails() {
  return this.getClass().getSimpleName()+"[id=" + id + ", name=" + name + ", salary=" + salary+ "]";
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getSalary() {
  return salary;
 }
 public void setSalary(int salary) {
  this.salary = salary;
 }
 
}
----------------------------------------------------

* super
1. 부모의 생성자 호출 시 사용(중요함, )
-생성자는 class와 이름이 같아야 하므로 부모class의 생성자는 상속이 안된다.
단, 자식 class의 생성자에서 부모의 생성자 호출은 가능.
- super([argument, ...]);
->생성자 구현부의 첫 명령어로 와야한다. (this도 생성자 구현부의 첫 명령어로 와야함으로 this와 super는 함께 쓸수 없다. )
->생성자 구현부에 this()나 super() 코드가 없으면 super();<-부모의 no-argument 생성자 호출 하는 코드가 자동으로 들어간다.
2. 부모의 객체를 참조하는 변수(중요도가 약간 떨어짐)

* this
1. overloading 된 생성자 호출(몰라도 프로그램 짜는데 이상이 없음, 프로그램 코딩을 다해주면됨. 코드 라인을 줄여주는 역할)
->생성자 구현부의 첫 명령어로 와야한다.
2.현재 일하는 메소드의 객체 - local

* 메소드 overriding(메소드 재정의) :  하위 class에서 부모 class에 정의된 메소드의 구현을 재정의 하는것. (자기만의 특징을 넣어서 다시 구현하고 싶을 때 메소드를 다시 정의하는 것.)
- 규칙 : 부모 안에 있는 메소드를 자식에서 똑같이 만들어서 내용만 바꾸는 것이다.
             전제 :  상속관계
      1. 이름, return type, 매개변수가 같아야 한다.
      2. 접근 제한자의 범위가 부모와 같거나 더 넓어야 한다. (만약 접근제한자의 범위가 부모가 protected면 자식은 protected나 public 이어야 한다.만약 접근제한자의 범위가 부모가 public이면 자식은 public이어야한다.단, 부모가 private면 상속해서 받아 올 수 없기때문에 오버라이딩이 아니다.)
* 메소드 overloading - 다른 메소드인데 인자와 타입이 다르면 한 클레스 내에서 사용 가능한 것.

*exception 관련 규칙.


* 2012-3-14

- 상속 :
부모클래스 :  자식클래스의 공통적인 내용을 추려서 새로 만들어진 클래스
(추상적이다.)

* super - 생성자호출 -> 부모의 생성자를 부름
             - 객체의 참조변수
      - 생성자 구현 첫 명령에 와야 한다.
      - 하위 class의 객체에서 부모 class의 객체를 참조하는 참조변수.
      - overriding한 메소드에서 부모에 정의된 원본메소드 호출시 사용.
      사용 : super.부모의 member-변수나, 메소드

          public
넓다       |
          protected
              |
좁다   private

*
Project : day16
package : overriding.test
class : Superclass
    SubClass

package overriding.test;

public class SuperClass {
 

 public void methodA(int i){
  System.out.println("SuperClass.methodA() : "+i);
 }
}


----------------------


package overriding.test;

public class SubClass extends SuperClass {
 /*
 //overriding - return type이 틀림
 public int methodA(int i){
  System.out.println("SubClass.methodA(int) : "+i);
 }
 //overriding = 접근제한자가 부모보다 좁아서 틀림.
 protected void methodA(int i){
  System.out.println("SubClass.methodA(int) :"+i);
 }
 */
 //overriding = 정상
 public void methodA(int i){
  System.out.println("SubClass.methodA(int) :"+i);
 }
 
 //overloading
 public void methodA(){
  System.out.println("SubClass.methodA()");
 }
 //overloading
 public void methodA(String str){
  System.out.println("SubClass.methodA(String) : "+str);
 }
 public static void main(String[] args) {
  SubClass sc  = new SubClass();
  sc.methodA(10);
 }
}


------------------------------

* 도형 예제

package : overriding.figure
TestShape - main()
Rectangle -width, height
Circle - radius, PI
Triangle - width, height

Shape - public void calculate Area(){}


ex :

package overriding.test;

import overriding.figure.Circle;
import overriding.figure.Rectangle;
import overriding.figure.Triangle;

public class TestShape {

 public static void main(String[] args) {
  Circle c = new Circle(3);
  c.calculateArea();
  
  Rectangle r = new Rectangle(10,20);
  r.calculateArea();
  
  Triangle t = new Triangle(10,20);
   t.calculateArea();

 }

}

----------------------

package overriding.figure;

public class Shape {
 public void calculateArea(){}
}

-----------------------

package overriding.figure;

public class Rectangle extends Shape{
 private double width;
 private double height;
 
 public Rectangle(double width, double height) {
  this.width = width;
  this.height = height;
 }

 public void calculateArea(){
  System.out.println(" 사각형의 넓이는 : "+width*height);
 }

 
}

-------------------------

package overriding.figure;

public class Circle extends Shape{
 private double radius;
 
 public Circle(double radius) {
  this.radius = radius;
 }

 public void calculateArea(){
  
  System.out.println(" 원의 넓이는 : "+radius*radius*Math.PI);
 }
 
}


------------------------------

package overriding.figure;

public class Triangle extends Shape{
 private double width;
 private double height;
 public Triangle(double width,double height){
  this.width = width;
  this.height = height;
 }
 public void calculateArea(){
  
  System.out.println(" 삼각형의 넓이는 : "+width*height/2);
 }

 
}
-----------------------------------


* 다형성 :  하나의 타입으로 여러개의 타입을 쓸수 있는것.(상속관계일 경우 가능)

* 접근제한자 - class(public), Field(instance 멤버변수, static 멤버변수), 메소드, 생성자
   -> 호출의 범쉬를 설정.
   -> 종류 :  public, protected, package friendly(defalut), private
       넓다<-------------접근범위--------------------->좁다


 * 접근제한자

 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                               |           UML              |   같은 class 안에서 호출   |  같은 package 다른 class  | 다른 package                                                           |  어떤 상황에서도 접근 가능
 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
private                    |             -                 |     O (우리가족만 가능)     |      X                                 |  X                                                                            |  X
 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package friendly     |              x                 |     O                                |      O                                 |  X                                                                            |  X
 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
protected               |              #                 |     O                                |      O                                 |  X(상속일때는 가능(super.으로 접근가능)super.go()) |  X
 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public                     |              +                 |     O                                |      O                                 |  O                                                                            |  O
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

* 접근제한자, 사용법과 관련된 제한자(static).

* final : 변수, 메소드(instance 메소드), class

- 변경이 안된다. (더이상 바꿀 수 없다.)
- 메소드 :  하위 class에서 overriding 할 수 없다.
- class : 하위 class를 가질 수 없는 class.    
(대표 : String class, 선언 -> 한번 값이 대입되면 다시는 대입안됨.
ex :  final int i = 10; i는 프로그램이 끝날때까지 값을 바꿀 수 없고 10만을 갖는다.

변수 :  변수의 상수화-> 한번 값이 대입되면 다시는 대입안됨.
instance변수 : 묵시적 초기화(x)
->값 대입 :  명시적 대입 (명시적 초기화)
->생성자에서 대입

final 변수은 한번 생성해주고 변수를 바꿀 수 없으므로 static과 잘어울린다.

- static 변수 : 선언시 값 대입.
   ->구문 : public static final
class A{
 static final int i =10;
 }

- 지역변수 :  사용 전까지 대입.
public void go(){
 final int i;
 i = 10; (이렇게 사용전에는 대입을 해줘야 하고, 한번 대입되면 값이 바뀔 수 없다. )
 System.out.prinltl(i);
 }

* final변수의 이름 관례 : 대문자
   단어 + 단어 -> 단어_단어

* final class는 상속이 안된다.

project : day16
package : finaltest.clazz
class : SuperClass
    SubClass

package finaltest.clazz;

public final class SuperClass {

}

-----------------

package finaltest.clazz;

public class SubClass extends SuperClass{

}

--------------------

project : day16
package : finaltest.method
class : SuperClass
    SubClass

* final 이 붙은 메소드는 하위 class에서 오버라이드 할 수 없다.

package finaltest.method;

public class SuperClass {
 public final void methodB(){
   System.out.println("안녕하세요");
 }
}
---------------------

package finaltest.method;

public class SubClass extends SuperClass{
 
 @Override
 public void methodB(){
  System.out.println("SubClass 안녕하세요");
}
}

----------------------

project : day16
package : finaltest.var
class : Rectangle

package finaltest.var;

public class Rectangle {
 public static final double PI = 3.14;
 public static final int BLACK = 0;
 public static final int WHITE = 1;
 public static final int BLUE; //여기서 에러가 난다. static final 변수는 선언을 하면서 반드시 값을 대입 해줘야한다.
}
-------------------------------------------

package finaltest.var;

public class Rectangle {
 public static final double PI = 3.14;
 public static final int BLACK = 0;
 public static final int WHITE = 1;
 //public static final int BLUE; //여기서 에러가 난다. static final 변수는 선언을 하면서 반드시 값을 대입 해줘야한다.
 private final int WIDTH;          //final instance변수는 선언시 대입하거나 생성자에서 값을 대입해야한다.  처음 초기화하면 생성자에서 또 다시 값을 넣을 수 없다.
 public Rectangle(int width){
  this.WIDTH = width;
 }

}

-------------------------------------

* 값이 대입되지 않은 로컬 변수는 사용할 수 없다.

package finaltest.var;

public class Rectangle {
 public static final double PI = 3.14;
 public static final int BLACK = 0;
 public static final int WHITE = 1;
 //public static final int BLUE; //여기서 에러가 난다. static final 변수는 선언을 하면서 반드시 값을 대입 해줘야한다.
 private final int WIDTH;
 public Rectangle(int width){
  this.WIDTH = width;
 }
 public void rectMethod(){
  final int var;
  
  //var = 20;
  //var = 10; //단 값은 한번만 넣어야 한다.

  System.out.println(var);
 }
}

------------------------------------------

* 의존관계 : 하나의 class가 다른 class를 사용하는 관계
    //Animal class가 String class에 의존하는 경우
 class Animal{
  String name;
  }
   1.has a 관계 : Attribute로 사용하는 경우.

 
 - ① aggregation 관계 - whole(전체) - part(부속)

 

 - ② composition 관계 - whole - part의 lifecycle이 같은 관계

   2.use a 관계 : 메소드에서 사용하는 경우(크게 중요하지 않다.)

 
* 부엌class
냉장고, 전자렌지, 싱크대, 김치냉장고,

class 부엌 {
 냉장고type  냉장고;
 싱크대type 싱크대;
 전자렌지type 전자렌지;
 김치냉장고type  김치냉장고;
 }

- aggregation관계 : 부엌이 만들어 질때 꼭 냉장고나 싱크대가 만들어져야 하지는 않는 관계.

* 자동차

핸들, 카오디오, 타이어, 엔진

class 자동차 {
 핸들type 핸들;
 엔진type 엔진;
 타이어type 타이어;
 카오디오type 카오디오;
}

- composition 관계(has a관계) - 자동차가 만들어 질때 핸들, 엔진, 타이어 객체가 다 만들어져야만 한다.
   ->하지만 카오디오는 없어도 되므로 카오디오는 aggregation 관계(has a 관계)다.

----------------------------------

* UML
                           의존관계(dependency)
Car              ---------->               Engine
e : Engine   ◆------->(composition관계표시)   

 

     ◇----------->(aggregation관계표시)    CarAudio

- Car는 Engine은 필수적으로 필요하고(composition관계표시), CarAudio는 있어도 그만 없어도 그만이다(aggregation관계표시).

--------------------------------------

* 정리

- dependency
사용자                                                피사용자
           ---------------------->
의존                                                   의존당하는애

- aggregation
whole ◇-------------------->part

- composition( 생성자에서 값을 받는 것)
whole ◆-------------------->part

* 의존관계는 객체와 객체간의 보통 관계를 나타낼때 사용한다.

class Product{
 int name;
 }
 //이것도 의존관계 이기는 하나 프리미티브 타입하고 객체간의 관계를 나타내진 않는다.

-------------------------------------------------------------------------------

* 2012 - 3 - 15

* 의존관계
- has a ->Attribute    ex :  자동차 - 엔진         
                                                     - 타이어
   ->aggregation 부엌 - 냉장고(부엌이 만들어 질때 부품들이 채워져 있지 않고 나중에 조금씩 채운다. (life cycle이 같지 않아도 된다.)
   ->composition - 생성될 때 다 같이 생성되야 한다.(부엌이 만들어 질때 부품들이 채워져 있어야한다.)(life cycle이 같아야 한다.)
        
- use a ->메소드 -사용하고 나면 없어지는것.

 

* has a 관계 ( 의존 관계 )
ex :

package dependency;

public class AddressDTO {
 private String zipCode;
 private String addressDetail;
 public AddressDTO() {
 }

 public AddressDTO(String zipCode, String addressDetail) {
  this.zipCode = zipCode;
  this.addressDetail = addressDetail;
 }
 public String getZipCode() {
  return zipCode;
 }
 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;
 }
 public String getAddressDetail() {
  return addressDetail;
 }
 public void setAddressDetail(String addressDetail) {
  this.addressDetail = addressDetail;
 }
 @Override
 public String toString() {
  return "AddressDTO [zipCode=" + zipCode + ", addressDetail="
    + addressDetail + "]";
 }
 
}


------------------


package dependency;

public class SchoolDTO {
 private String schoolId;
 private String schoolName;
 private String schoolTelNo;
 private int enrolment;
 private AddressDTO addressTo;
 

 public SchoolDTO() {}
 public SchoolDTO(String schoolId, String schoolName, String schoolTelNo,
   int enrolment, AddressDTO addressTo) {
  this.schoolId = schoolId;
  this.schoolName = schoolName;
  this.schoolTelNo = schoolTelNo;
  this.enrolment = enrolment;
  this.addressTo = addressTo;
 }
 public String getSchoolId() {
  return schoolId;
 }
 public void setSchoolId(String schoolId) {
  this.schoolId = schoolId;
 }
 public String getSchoolName() {
  return schoolName;
 }
 public void setSchoolName(String schoolName) {
  this.schoolName = schoolName;
 }
 public String getSchoolTelNo() {
  return schoolTelNo;
 }
 public void setSchoolTelNo(String schoolTelNo) {
  this.schoolTelNo = schoolTelNo;
 }
 public int getEnrolment() {
  return enrolment;
 }
 public void setEnrolment(int enrolment) {
  this.enrolment = enrolment;
 }
 public AddressDTO getAddressTo() {
  return addressTo;
 }
 public void setAddressTo(AddressDTO addressTo) {
  this.addressTo = addressTo;
 }
 @Override
 public String toString() {
  return "SchoolDTO [schoolId=" + schoolId + ", schoolName=" + schoolName
    + ", schoolTelNo=" + schoolTelNo + ", enrolment=" + enrolment
    + ", addressTo=" + addressTo + "]";
 }
 
}

 

---------------------------

 

package dependency;

public class StudentDTO {
 private String studentId;
 private String studentName;
 private int studentAge;
 private int studentGrade;
 private int studentClazz;
 private int studentNumber;
 private SchoolDTO schoolTo;

 public StudentDTO(SchoolDTO schoolTo) {
  this.schoolTo = schoolTo;
 }
 
 public StudentDTO(String studentId, String studentName, SchoolDTO schoolTo) {
  this.studentId = studentId;
  this.studentName = studentName;
  this.schoolTo = schoolTo;
 }

 public StudentDTO(String studentId, String studentName, int studentAge,
   int studentGrade, int studentClazz, int studentNumber,
   SchoolDTO schoolTol) {
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentAge = studentAge;
  this.studentGrade = studentGrade;
  this.studentClazz = studentClazz;
  this.studentNumber = studentNumber;
  this.schoolTo = schoolTol;
 }
 public String getStudentId() {
  return studentId;
 }
 public void setStudentId(String studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
 public int getStudentAge() {
  return studentAge;
 }
 public void setStudentAge(int studentAge) {
  this.studentAge = studentAge;
 }
 public int getStudentGrade() {
  return studentGrade;
 }
 public void setStudentGrade(int studentGrade) {
  this.studentGrade = studentGrade;
 }
 public int getStudentClazz() {
  return studentClazz;
 }
 public void setStudentClazz(int studentClazz) {
  this.studentClazz = studentClazz;
 }
 public int getStudentNumber() {
  return studentNumber;
 }
 public void setStudentNumber(int studentNumber) {
  this.studentNumber = studentNumber;
 }
 public SchoolDTO getSchoolTol() {
  return schoolTo;
 }
 public void setSchoolTol(SchoolDTO schoolTol) {
  this.schoolTo = schoolTol;
 }
 @Override
 public String toString() {
  return "StudentDTO [studentId=" + studentId + ", studentName="
    + studentName + ", studentAge=" + studentAge
    + ", studentGrade=" + studentGrade + ", studentClazz="
    + studentClazz + ", studentNumber=" + studentNumber
    + ", schoolTo=" + schoolTo + "]";
 }
 
}

 

------------------------------------------------


* 다형성(polymorephism) - 부모type의 변수에 자식type의 객체를 대입

int i = 10;
long l = 10; <-작은 type을 큰 타입으로 바꿔주므로 된다. long l = 10L;

byte b = 20;
short s = 5
int i = 30;
long l = b;(o)
long l = s;(o)
long l = i;(o)

- 상속관계일 때는 저렇게 a를 생성하는게 가능하다.
Animal- Dog
      - Cat
      - Human

Animal a = new Animal();(O)
       a = new Cat();
       a = new Dog();


* 컴파일 시점에는 소스코드로 가서 본다 .

Animal
------
eat()       <------
                  |
^                 |
|                 |
Dog               Cat
----              ----
eat()             eat()
cry()             cry()


Animal c = new Cat(); ok
c.eat();  ok   //Animal class에 eat()가 있어서 되지만
c.cry();  no   //Animal class에 cry()를 찾는데 없어서 컴파일 시점에 실행되지 않는다.

이렇게 바꾸면 된다.
Animal a = new Cat();
Cat c = (Cat)a;
c.cry();


* class 변수  = new 생성자()
  변수, 메소드()

compile ->type
실행 -> 객체(값)

Animal a = new Cat();
a.eat();

eat() - compie시점 : Animal
        실행시점 :  Cat

다형성 : 부모에 선언된 메소드만 호출가능.
         자식에 선언된 메소드 사용하려면 형변환 필요.

 

Animal a = new Cat();
a.eat() - c : Animal
        - R : Cat

a.cry() - C : Animal - compile 에러

따라서

Cat c - (Cat) a ;
c.cry() - C : Cat
          R : Cat

* 다형성은 거의 배열에 정의한다.  (다형성의 개념은 중요하지만 우리가 직접 사용하지는 않는다. 쓸것은 이미 class에 다 정의 되어 있다. )

--------------------------------------

project :  day17
package : polymorphism.dto
class : Animal, Dog, Cat

project :  day17
package : polymorphism.test
class : PolymorphismTest


package polymorphism.test;

import polymorphism.dto.Animal;
import polymorphism.dto.Cat;
import polymorphism.dto.Dog;

public class PolymorphismTest {


 public static void main(String[] args) {
  //다형성을 이용해 객체 생성
  //부모 타입 변수 = 자식 타입 객체
  Animal an1 = new Dog();
  Animal an2 = new Cat();
  //모든 클래스의 최상위 -> Object
  Object obj1 = new Animal();
  Object obj2 = new Cat();
  Object obj3 = new Dog();
  
  //이런것도 Polymorphism(다형성)이다.
  Cat c = new Cat();
  Animal an3 = c;
  
  an1.eat();
  an1.sleep();
  an2.eat();
  an2.sleep();
  
  //부모타입변수, 자식의 메소드()          an2.cry();가 Animal type이라 Animal 가도 없으니 Cat type으로 형변환 시켜줘야한다.
  //an2.cry();
  
  //((Cat) an2).cry();
  Cat c2 = (Cat)an2;
  c2.cry();
 }

}

------------------------

package polymorphism.dto;

public class Animal {
 public void eat(){
  System.out.println("동물이 먹는다. ");
 }
 public void sleep(){
  System.out.println("동물이 잔다.");
 }

}


-----------------------------

package polymorphism.dto;

public class Cat extends Animal {

 @Override
 public void eat() {
  System.out.println("고양이가 고양이 밥을 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("고양이가 잔다.");
 }
 public void cry(){
  System.out.println("고양이가 운다..야옹.....");
 }
}


-----------------------------

package polymorphism.dto;

public class Dog extends Animal{

 @Override
 public void eat() {
  System.out.println("개밥 그릇에 사료를 우그적 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("개집에서 잔다.");
 }

 
}

-----------------------------

* Heterogemeous Collection - 다른 type의 Data를 모으는 배열(객체)!
                           - 배열에 다형성이 적용된 것.
////////////
//객체데이터 모음을 관리 할 수 있다.
for( Animal a : anArr){
 a.eat();
}

/////////////////

long[] l = new long[5];
l[0]=10;
l[1]=20L;
//이렇게 보면 int도 들어가고 long도 들어간다.

Animal[] anArr = new Animal[5];
anArr : Animal[]
anArr[0] : Animal

anArr[0] = new Animal();
anArr[1] = new Dog();
anArr[2] = new Cat();

* 부모 type의 배열에 자식 type 객체들을 할당(대입)

* 자바에서 존재하는 type은 1. 프리미티브 2. 레퍼런스 두개가 있다.


project :  day17
package :  polymorphism.test
class : HeterogemeousTest

package polymorphism.test;

import polymorphism.dto.Animal;
import polymorphism.dto.Cat;
import polymorphism.dto.Dog;

public class HeterogemeousTest {
 public static void main(String[] args) {
  //배열에 다형성을 적용 - 부모 type배열에 자식 타입의 객체를 넣는것.
  Animal[] an1 = new Animal[3];
  Animal[] an2 = new Cat[4];
  
  an1[0] = new Animal();
  an1[1] = new Cat();
  an1[2] = new Dog();
  
  Animal[] an3 = {new Animal(), new Dog(), new Cat()};
  for( int i = 0; i< an1.length;i++){
   an1[i].eat();
  }
  
  System.out.println("============향상된 for문==============");
  //for(변수선언 :  배열)
  for(Animal an : an3){
   if(an instanceof Cat){
   Cat c = (Cat)an;
   c.cry();
   }
   an.sleep();
  }
  boolean b = an3[0] instanceof Cat;
  String str ="abc";
  //b = str instanceof Dog; //둘이 상속이 아니라서 에러가 난다. instanceof는 상속관계에서 사용한다. if문에서 주로 객체비교 시사용
 }
}

 


*instanceof
비교할 객체 instanceof Type :  boolean

a instanceof B -> a가 참조하는 객체가 B type 인지 검사해서 맞으면 true return

boolean "abc" instanceof A; //에러난다. a와 B의 type이 상속관계에 있어야 한다.(서로 완전히 다른 객체면 비교할 필요가 없기 때문이다.)

- a의 type이 B의 상쉬 type일 때만 비교할 수 있다.


* class 는 Datatype로 사용하지만
class 가 Datatype은 아니다.

Animal an = new Animal(); //an에는 Animal, Dog, Cat 다 들어갈 수 있다.


* Polymorphic Argument -> 매개변수에 다형성이 적용된 것이다.

Animal - Cat
      <- Dog
       - Snake

void go( Cat c){
c.eat();
}

void go(Dog d){
d.eat();
}

void go(Snake s){
s.eat();
}

------------

위에 go()메소드를
void go(Animal a){
a.eat();
}
을로 바꿔주면 세개의 메소드를 한개만 만들면 된다. 대신 호출 시 go(d)나 go(c)나 go(s)로 해야한다.

 

----------------------------------------------

project : day17
package : polymorphism.test
class : Zookeeper(사육사), PolymeorphicArgsTest

project : day17
package : polymorphism.dto
class : Lion


package polymorphism.test;

import polymorphism.dto.Cat;
import polymorphism.dto.Dog;
import polymorphism.dto.Lion;

public class PolymeorphicArgsTest {
 public static void main(String[] args) {
  //사육사 객체를 생성
  ZooKeeper zk = new ZooKeeper();
  Dog d = new Dog();
  Cat c = new Cat();
  Lion l = new Lion();
  
  zk.raise(d);
  zk.raise(c);
  zk.raise(l);
 }
}


--------------------------

package polymorphism.test;

import polymorphism.dto.Animal;

public class ZooKeeper {
 /*
  * 우리 청소
  * 밥 먹이기
  * 잠 재우기
  */
 public void raise(Animal a){
  System.out.println("--------------------");
  System.out.println("우리를 청소한다.");
  a.eat();
  a.sleep();
 
 }
}


-------------------------


package polymorphism.dto;

public class Lion extends Animal{

 @Override
 public void eat() {
  System.out.println("사자가 먹는다.");
 }

 @Override
 public void sleep() {
   System.out.println("사자가 잔다.");
 }
 
}
--------------------------

package polymorphism.dto;

public class Dog extends Animal{

 @Override
 public void eat() {
  System.out.println("개밥 그릇에 사료를 우그적 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("개집에서 잔다.");
 }

 
}


---------------------------

package polymorphism.dto;

public class Cat extends Animal {

 @Override
 public void eat() {
  System.out.println("고양이가 고양이 밥을 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("고양이가 잔다.");
 }
 public void cry(){
  System.out.println("고양이가 운다..야옹.....");
 }
}

-----------------------------------

package polymorphism.dto;

public class Animal {
 public void eat(){
  System.out.println("동물이 먹는다. ");
 }
 public void sleep(){
  System.out.println("동물이 잔다.");
 }

}


-------------------------------------

============================================================================

package polymorphism.test;

import polymorphism.dto.Cat;
import polymorphism.dto.Dog;
import polymorphism.dto.Lion;
import polymorphism.dto.Tiger;

public class PolymeorphicArgsTest {
 public static void main(String[] args) {
  //사육사 객체를 생성
  ZooKeeper zk = new ZooKeeper();
  Dog d = new Dog();
  Cat c = new Cat();
  Lion l = new Lion();
  Tiger t = new Tiger();
  
  
  zk.raise(d);
  zk.raise(c);
  zk.raise(l);
  zk.raise(t);
 }
}


-------------------------------

 

package polymorphism.test;

import polymorphism.dto.Animal;
import polymorphism.dto.Tiger;

public class ZooKeeper {
 /*
  * 우리 청소
  * 밥 먹이기
  * 잠 재우기
  */
 public void raise(Animal a){
  System.out.println("--------------------");
  System.out.println("우리를 청소한다.");
  if(a instanceof Tiger){
   Tiger t = (Tiger)a;
   t.hunt();
   //((Tiger) a).hunt();
  }
  else{
  a.eat();
  }
  a.sleep();
 
 }
}


-------------------------------------

package polymorphism.dto;

public class Animal {
 public void eat(){
  System.out.println("동물이 먹는다. ");
 }
 public void sleep(){
  System.out.println("동물이 잔다.");
 }

}


package polymorphism.dto;

public class Cat extends Animal {

 @Override
 public void eat() {
  System.out.println("고양이가 고양이 밥을 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("고양이가 잔다.");
 }
 public void cry(){
  System.out.println("고양이가 운다..야옹.....");
 }
}


package polymorphism.dto;

public class Dog extends Animal{

 @Override
 public void eat() {
  System.out.println("개밥 그릇에 사료를 우그적 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("개집에서 잔다.");
 }

 
}


package polymorphism.dto;

public class Lion extends Animal{

 @Override
 public void eat() {
  System.out.println("사자가 먹는다.");
 }

 @Override
 public void sleep() {
   System.out.println("사자가 잔다.");
 }
 
}


package polymorphism.dto;

public class Tiger extends Animal{

 @Override
 public void eat() {
  System.out.println("호랑이가 먹는다.");
  }

 @Override
 public void sleep() {
  System.out.println("호랑이가 잔다.");
 }
 public void hunt(){
  System.out.println("호랑이가 사냥해서 먹는다.");
 }

 
}


---------------------------------------------------------------

=======================================================================


* 다형성 연습

UML - word

package : wordprocessorTest
class : WordUser

package : wordprocessor.word
class : Word

package : wordprocessor.format
class : Format
 AstaFormat
 EqulFormat
 SharpFormat


------


package wordprocessorTest;


import wordprocessor.format.AstaFormat;
import wordprocessor.format.Format;
import wordprocessor.format.SharpFormat;
import wordprocessor.word.Word;

public class WordUser {
 public static void main(String[] args) {
  Word word = new Word();
  Format f = new Format();
  AstaFormat af = new AstaFormat();
  SharpFormat sf = new SharpFormat();
  word.print("출력할 내용 :  Hello",f);
  word.print("출력할 내용 :  Hello",af);
  word.print("출력할 내용 :  Hello",sf);
 }
}


----------

package wordprocessor.word;

import wordprocessor.format.Format;
public class Word {
 public void print(String message, Format format){
  System.out.println(format.getFormat(message));
 }
}


----------

package wordprocessor.format;

public class Format {
 public String getFormat(String message){
  String str;
  str = "---------------------\n"+message+"\n---------------------";
  return str;
 }
}


----------

package wordprocessor.format;


public class AstaFormat extends Format{

 @Override
 public String getFormat(String message) {
  // TODO Auto-generated method stub
  return super.getFormat(message).replace('-','*');
 }
 
}


------------

package wordprocessor.format;

public class EqulFormat extends Format{

 @Override
 public String getFormat(String message) {
  // TODO Auto-generated method stub
  return super.getFormat(message).replace('-', '=');
 }
 

}


-------------

package wordprocessor.format;

public class SharpFormat extends Format{

 @Override
 public String getFormat(String message) {
  // TODO Auto-generated method stub
  return super.getFormat(message).replace('-', '#');
 }
 
}


-----------------------------------------------------------------------------------

=====================================================================================================
       


* 2012-3-16

* 다형성 - 부모tyoe  변수 - 자식객체 (compile시점에 되는 경우는 상속인 경우 부모가 자식보다 더 큰 tyoe이면 다형성이 된다) , 실행시점에서는 부모의 객체와 자식의 객체가 둘다 생성되서 접근가능.
         -> 부모에 정의된 메소드만 호출가능.

- Super s = new Super();
   s.a();(o)자식에 있는 a()를 호출
 s.b();(x)자식에는 b()가 있지만 부모에 없어서 컴파일 시점에서 에러가 난다. 
        

Super              Sub
----- <-------     ------
a()                a()
                   b()

- 배열 Heterogeneous -> reference type의 배열.


* Super = new Super()           c : o
  Sub1 sub = (Sub1)s;           R : x


* Sub1 sub1 = new Sub1();           C : X   (컴파일시점)
  Sub2 sub2 = (Sub2)sub1;           R : X   (실행시점)

* Super s = new Super();            C : O
  Sub1 s1 = (Sub1)s;                R : O

* 추상화(모든 자식class들이 동일하게 하는 것들을 모아서 부모class에 추상화 시켜 놓는 것)
- 추상메소드 :  자식클래스들이 부모클래스의 메소드를 오버라이딩 해서 사용하게 하려고 만듬.
Animal
------
eat()     <- 추상메소드


Dog       Cat        Lion
----      ----       -----
eat()     eat()      eat()

* abstact - instance 메소드, class에 사용되는 제한자
          - 의미 :  추상적이다->구현이 안되었다.
- 메소드 :  메소드 구현없이 선언만한 메소드
예) public abstact void go(); ->{}붙으면 안됨.
->하위 class에서의 overriding 을 강제한다.
->하위class들이 구현할 메소드의 template(틀)역할.


- class -> 객체생성을 못하는 class
예 ) public abstact class Animal{구현}

-abstract 메소드를 가지는 class는 반드시 abstract class가 되야한다.
-부모 class에 정의된 abstract메소드를 overriding 안하면 abstract class가 되야한다.
-abstract class는 구현된 일반메소드도 가질수 있따.

- > 역할 :  자식 class의 template, 자식 객체에 대한 type 역할 - 다형성

 

* abstract class - 일반class
                   field
                   생성자
                   메소드
                   추상메소드
                  

*
project : day18
package : abstr.test
class : AbstractTest

package abstr.test;

abstract class Super{
 int num;

 public Super() {}

 public Super(int num) {
  this.num = num;
 }
 public abstract void methodA();
 public void templateMethod(){
  System.out.println("하위클래스의 구현이 모두 같은 메소드 : "+num);
 }
}
class Sub extends Super{
 public Sub(){}
 public Sub(int num){
  super(num);
 }
 
 public void methodA(){
  System.out.println("Sub.methodA()");
 }
}
public class AbstractTest {
 public static void main(String[] args) {
  //Super s = new Super(); //추상클래스는 객체 생성을 할 수 없다.
  Sub sub = new Sub();
  sub.methodA();
  Sub sub2 = new Sub(100);
  sub2.templateMethod();
 }
}

---------------------------------

project : day18
package : abstr.animal
class : PolymorphicArgsTest


package abstr.animal;

public class PolymorphicArgsTest {
 public void raise(Animal an){
  an.eat();
  an.sleep();
  
 }
 public static void main(String[] args) {
  Dog d = new Dog();
  Lion l = new Lion();
  
  d.eat();
  d.sleep();
  
  System.out.println("------------------------");
  
  PolymorphicArgsTest pt = new PolymorphicArgsTest();
  pt.raise(d);
  pt.raise(l);
 }
}


------


package abstr.animal;

//하위클래스들의 type, 하위클래스들의 틀(Template) -> 추상클래스
public abstract class Animal {
 public abstract void eat();
 public abstract void sleep();

}

---------

package abstr.animal;

public class Lion extends Animal{

 @Override
 public void eat() {
  System.out.println("사자가 먹는다.");
 }

 @Override
 public void sleep() {
   System.out.println("사자가 잔다.");
 }
 
}


------

package abstr.animal;

public class Dog extends Animal{

 @Override
 public void eat() {
  System.out.println("개밥 그릇에 사료를 우그적 먹는다.");
 }

 @Override
 public void sleep() {
  System.out.println("개집에서 잔다.");
 }

 
}


----------------------------------------------------------
=======================================================================
* interface

* abstract는 class가 가진 것 모두 가질수 있다.
* 인터페이스는 컴파일 시점에 오로지 부모 타입의 역할만 하지만 abstract는 메소드도 만들어 사용도 가능하다.
* interface(기본적으로 abstract와 같으나 부모의 역할만 하고 type의 역할만하고 객체를 생성할수는 없으나(abstract), interface는 추상메소드와 static final 변수만 가질 수 있다. 생성자도 없고, 구현된 메소드없고 타입 역할만 하는 것이다. )
- interface : 완벽히 추상화된 구조.
- 역할 :  상위 Type으로서의 역할 - 자식(하위)클래스에 대한 type과 template을 위한 구조.
- 구문 : [접근제한자] interface 이름[extends 인터페이스,...] <- 인터페이스만 상속받을 수 있고, 인터페이스 끼리는 다중 상속이 된다.
 {
  구현 :  [ public static final ] 변수 = 값;   //[]안에 내용은 생략가능 자동으로 컴파일러가 넣어준다. 무조건 있어야 하므로
   [ public abstract ] 메소드 선언;
 }

-> 접근제한자에는 : publc과 package friendly만 올 수 있다. (인터페이스는 누구든 접근 가능해야 하므로 대부분 public 을 쓴다.)


* interface

- class에서 interface 상속 - 다중상속 가능
  - 구문
    [제한자] class 이름 extends class명 implements interface명, interface명, ....
    {

    }

    public class A extends B implements interfaceA, interfaceB, interfaceC{

    }

* uml

B            <<interface>>          <<interface>>
             interfaceA             interfaceB
^
|                 ^                     ^
                  |                     |
A----------------------------------------

* 기본적으로 자바에서 단일 상속을 지원하는 이유
  A            B
----          ----
go()          go()
 ^             ^
 |             |
 |--------------
        C
       ----
       go()

* interface는 상위 클래스에는 추상화 된 구문만 받아오므로 아래 C에서 go()를 불러도 오버라이딩 된 C의 메소드가 불릴 것이기 때문에 다중 상속이 가능하다.


C                                      A<<interface>>
--------                              ---------------
+void go(){}      ----------------->   void go();
+void come(){}
                                          |
                                          |
                                          V
                                      B<<interface>>
                                      ----------------
                                      +void come();

* class에서 interface 상속 - 다중상속가능
class ->(가 class를 상속할때) class : extends, 단일 상속
interface -> interface : extends, 다중상속
class -> interface : implements, 다중상속

- 역할 : 상위 type - 하위 class가 정의할 메소드 선언(추상)(반드시 오버라이딩하게 만들어 둠)
                   - 다형성에서 하위 객체를 대입할 변수의 type

- public static final 변수 = 값; (여러 곳에서 사용할 수 있는 코드값, 불변의 값을 만들때 사용)
- program의 다른 class들에서 사용할 상수값 선언->코드값, 불변의 값

- 크게 관계 없는 class들을 하나의 type으로 묶을 때 사용.
ex :                                                                       수퍼히어로
                이동수단                 Flyer                               ^                                                 
                                           ^                                  |
                    ^                      |                --------------------------------------
                    |                      |----------------|                 |                  |
-------------------------------------------                슈퍼맨        스파이더맨        배트맨
|                   |                     |               
자동차              배               비행기           

 

* 공통적인 동작을 뽑아서 만든 인터페이스에는 Able을 뒤에 붙인다. (ex : FlyerAble)

*
project : day18
package : interfacetest
class : InterfaceTest
interface : InterfaceA
interface : InterfaceB <- InterfaceA를 상속
interface : interfaceC


package interfacetest;

public class InterfaceTest {
 public static void main(String[] args) {
  SubClass1 s1 = new SubClass1();
  InterfaceA s2 = new SubClass1();
  InterfaceB s3 = new SubClass1();
  
  s2.methodA();
  //s2.methodB();
  s3.methodA();
  s3.methodB();

 }

}


--------

package interfacetest;

public interface InterfaceA {
 public static final int CONST_A = 10;
 //int CONST_A = 10;//public static final을 생략하면 컴파일러가 자동으로 만들어 준다. 위 아래 두개가 같은식이다.
 public abstract void methodA();
 //void methodA(); //public abstract를 생략하면 컴파일러가 자동으로 만들어 준다. 위 아래 두개가 같은식이다.(컴파일러가 자동 생성해 주는 이유는 무조건 필요하기 때문이다.
 
}

---------
package interfacetest;

public interface InterfaceB extends InterfaceA {
 public abstract void methodB();
}

------
package interfacetest;

public interface InterfaceC {
 public abstract void methodC();
}


-----
package interfacetest;


public class SubClass1 implements InterfaceB {

 @Override
 public void methodA() {
  System.out.println("SubClass1.methodA()");

 }

 @Override
 public void methodB() {

  System.out.println("SubClass1.methodB()");

 }

}


--------
================================================================================================

* interface는 class가 아니고 타입의 역할만 하는 거다. 객체화 되지 않는다.
* 추상화class는 class 되고 객체화 되고, 타입의 역할도 한다.

package interfacetest;

public class InterfaceTest {
 public static void main(String[] args) {
  SubClass1 s1 = new SubClass1();
  InterfaceA s2 = new SubClass1();
  InterfaceB s3 = new SubClass1();
  
  s2.methodA();
  //s2.methodB();  //InterfaceB에 선언된 메소드 이므로 컴파일 에러
  s3.methodA();
  s3.methodB();
  SubClass2 su1 = new SubClass2();
  InterfaceA su2  = new SubClass2();
  InterfaceB su3 = new SubClass2();
  InterfaceC su4 = new SubClass2();
  
 }

}


---------

package interfacetest;


public class SubClass1 implements InterfaceB {

 @Override
 public void methodA() {
  System.out.println("SubClass1.methodA()");

 }

 @Override
 public void methodB() {

  System.out.println("SubClass1.methodB()");

 }

}


--------

package interfacetest;


public class SubClass2 implements InterfaceB, InterfaceC {

 @Override
 public void methodA() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void methodC() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void methodB() {
  // TODO Auto-generated method stub
  
 }
 
}

--------

package interfacetest;

public interface InterfaceA {
 public static final int CONST_A = 10;
 //int CONST_A = 10;//public static final을 생략하면 컴파일러가 자동으로 만들어 준다. 위 아래 두개가 같은식이다.
 public abstract void methodA();
 //void methodA(); //public abstract를 생략하면 컴파일러가 자동으로 만들어 준다. 위 아래 두개가 같은식이다.(컴파일러가 자동 생성해 주는 이유는 무조건 필요하기 때문이다.
 
}

-------

package interfacetest;

public interface InterfaceB extends InterfaceA {
 public abstract void methodB();
}

--------

package interfacetest;

public interface InterfaceC {
 public abstract void methodC();
}

-----------
==================================================================================================

* API 표준은 정해져 있음 ->대부분 중요한 API는 Interface로 되어 있다.
* JDBC : JAVA DATABASE Connection( 오라클, msmql, DB2(IBM DB))


* 2012-3-19

- Collection API - data들를 모아서 관리하는 객체들. (배열 - Object[])
- 모으는 방법에 따라 여러 class로 제공.

*collection

* 배열은 크기가 한번 정해지면 바뀌지 않는다.
- Collection은 데이터를 계속 집어 넣을 수 있다. (Collection은 자체적으로 데이터를 계속 넣어준다. )
추가 :  add(Object) : boolean (추가가 성공하면 return true, 실패하면 return false)
삭제 :  remove(Object) : boolean (삭제가 성공하면 return true, 실패하면 return false)
조회 : X -> iterator() : Iterator
크기 : size() : int ->관리하는 객체의 수
확인 : contains(Object) : boolean -> 인수로 받은 객체가 collection 안에 있는지 조회.
삭제 : clear() -> 컬렉션 내의 모든 객체 삭체

- Collection<<interface>> -> 값만 모음 - Set : 중복허용(X)
                                               순서(X)

- ~Set - HashSet - 그냥 모으는것.
        TreeSet - 정렬이 필요한 것.


           - List : 중복허용(O)(ex : 똑같은 것을 담을 수 있다.)
       순서(O)(ex : 칸막이가있다.index번호가 생김.배열과 비슷)


 
- ~List - Vector
        - ArrayList(List 중 가장 많이 쓰임) : 전체조회시 좋음.
 - LinkedList : data를 삽입, 삭제시 좋음.

List :  - 추가 :  add(int idx, Object) - 삽입(데이터를 데이터 중간에 넣어주는 것.중간에 값을 넣어주고 데이터가 하나씩 밀려난다.)
            ->idx = 객체를 삽입할 index
        - List는 중간 idx에 null이 있으면 에러가 난다.
 - 수정 : set(int idx, Object) - 교체
 - 구문 : list.Set(2,a);
 - 삭제 : remove(int 삭제할 idx) : Object
  ->특정 idx의 객체를 삭제하고 그 객체를 return
 - 조회 : get(int idx) : Object
         ->특정 index의 객체를 return ->조회
 - indexOf(Object) :  int
  ->인수로 받은 객체의 index(중복된 idx의 0번 idx부터 찾음)를 알려준다.
 - lastIndexOf(Object) : int
  ->인수로 받은 객체의 index(중복된 idx의 마지막 idx)를 알려준다. (ps. 대신 중간에 있는 것은 찾을 수 없다.)

* List ->list -> ArrayList의 객체.

배열 0 ~ length 
for(int i=0;i<list.size();i++){
 Object o = list.get(i);
}

//향상된 for문)
for(Object o : list){
 s.o.p(o);
}


- Map<<interface>> -> 키->값을 쌍으로 모음.  key - value

 

* HashSet ex :

project : day19
package : collection.set
class : SetTest

package collection.set;

import java.util.HashSet;
import java.util.TreeSet;

public class SetTest {
 public static void main(String[] args) {

  // Set - Collection 계열(값만 저장) - 순서 : X, 중복허용 : X
  // HashSet, TreeSet(정렬기능)
  HashSet set = new HashSet();
  // 추가
  set.add("홍길동");
  set.add("이순신");
  set.add("유재석");
  set.add("박명수");
  System.out.println(set);// [객체.toString(), 객체.toString()]
  // 출력 [박명수, 이순신, 홍길동, 유재석] // 이걸 보면 순서가 없다는 것을 알 수 있다.
  boolean flag = set.add("이순신");
  System.out.println(flag + " : " + set);// 중복허용이 안되서 false가 들어가고, 값이 안들어가
            // 있는 것을 볼 수 있다.
  System.out.println("총 객체의 수 : " + set.size()); // 삭제전 총 객체의 수
  // 삭제
  flag = set.remove("박명수");
  System.out.println("박명수 삭제 여부 - " + flag + " : " + set);
  System.out.println("총 객체의 수 : " + set.size());// 삭제 후 총 객체의 수

  System.out.println("------------TreeSet------------");
  TreeSet tSet = new TreeSet(); // 출력 : [길성준, 노홍철, 박명수, 유재석, 정준하, 정형돈, 하하]
          // 내부적으로 ㄱ,ㄴ,ㄷ,ㄹ식으로 정렬되어 나온다.
  tSet.add("유재석");// 정렬기능이 필요할 때 쓴다.
  tSet.add("박명수");
  tSet.add("노홍철");
  tSet.add("정형돈");
  tSet.add("길성준");
  tSet.add("정준하");
  tSet.add("하하");
  System.out.println(tSet);
  flag = tSet.contains("정형돈");// tSet에 정형돈 값을 가지는 String 객체가 있는지를 조회
  System.out.println("정형돈 객체 유무 : " + flag);// 정형돈이 tSet에 들어가 있어서 true가
             // 출력된다.

  // 향상된 for를 이용해 전체 데이터(객체)들 조회 - jdk1.5이상 사용가능.
  for (Object o : tSet) {
   System.out.println(o);
  }

  flag = tSet.isEmpty();// 컬렉션의 size()가 0이면 true
  System.out.println(flag);// tSet에 데이터가 들어가 있으므로 false가 출력
  if (!flag) {// tSet이 비어 있지 않으면
   tSet.clear();
  }
  System.out.println("clear() 후 : " + tSet+", tSet.size() : "+tSet.size()); //컬렉션 내 모든 객체를 remove
  tSet.add(1);//TreeSet의 경우는 같은 데이터만 들어가고 HashSet은 다른 타입도 들어간다.
  tSet.add(2);//기본타입데이터(프리미티브 타입)를 추가 하는 것은 jdk1.5 이상에서만 가능
  tSet.add(3);
  tSet.add(4);
 // tSet.add("abcde");
 // tSet.add(true);
  tSet.add(new Integer(5));//jdk 1.4이하에서의 추가 방법
  System.out.println(tSet);

 }

}

---------------------------------------

=====================================================================
project :  day19
package : collection
class : Lotto


package collection;

import java.util.HashSet;
import java.util.TreeSet;

public class Lotto {

 public static void main(String[] args) {
  //1~45의 숫자중 중복하지 않는 숫자 6개를 만들어 출력하시오.
  //[5,23,1,8,9,14]
  //랜덤한 숫자
  //숫자 - 6개
  //중복되지 않는 숫자를 어떻게 모을 것인가.
  TreeSet ts = new TreeSet();
  int cnt = 0;
  
  //while로 하는 방법
  while(true){
   ts.add((int)(Math.random()*45+1));
   //System.out.println(hs.size());
   cnt++;
   if(ts.size()==6){
    break;
   }
  }
  System.out.println("반복 횟수 : "+cnt);
  System.out.println("로또 예상 : "+ts);
  
  ts.clear();
  cnt=0;
  while(ts.size()<6){
   cnt++;
   ts.add((int)(Math.random()*45+1));
  }
  System.out.println("반복 횟수 : "+cnt);
  System.out.println("로또 예상 : "+ts);
  
  //for로 하는 방법
//  for(;ts.size()<6;){
//   ts.add((int)(Math.random()*45+1));
//  }
//  System.out.println(ts);


 }

}

* project : day19
package : collection.list
class : ArrayListTest

 

package collection.list;

import java.util.ArrayList;

public class ArrayListTest {
 public static void main(String[] args) {
  arraylistBasic();
 }
 public static void arraylistBasic(){
  ArrayList list = new ArrayList(); //배열에 몇개 들어갈지 모르겠다 하면 이렇게 선언하고 딱 몇개 들어갈지 알면 아래와 같이 생성하는게 좋다. 수행시간이 짧아진다.
  //ArrayList list = new ArrayList(10);//초기 length(저장할 수 있는 크기)
  //추가
  list.add("유재석");
  list.add("박명수");
  list.add("정준하");
  list.add("노홍철");
  System.out.println(list);
  
  //조회 - get(int idx) : Object - index의 시작 : 0
  String str = (String) list.get(0);
  System.out.println(str);
  
  System.out.println("-----전체 조회 패턴-----");
  //전체 조회 패턴
  for(int idx=0;idx<list.size();idx++){
   System.out.println(list.get(idx));
  }
  System.out.println("-----향상된 for문 이용 조회 1.5 이상----------");
  for(Object o : list){
   System.out.println(o);
  }
  
  System.out.println("-----삭제----------");
  boolean flag = list.remove("유재석");
  System.out.println("삭제여부 : "+flag+" - "+list);
  
  Object obj = list.remove(1);
  System.out.println("삭제된 객체 : "+obj);
  System.out.println("삭제여부 : "+flag+" - "+list);
  
 }
}


* project : day19
package : collection.dto
class : PersonDTO


package collection.list;

import java.util.ArrayList;

import collection.dto.PersonDTO;

public class ArrayListTest {
 public static void main(String[] args) {
  // arraylistBasic();
  arraylistDTO();
 }

 public static void arraylistDTO() {
  ArrayList list = new ArrayList();
  PersonDTO pdto = new PersonDTO("id-1", "홍길동", 20, "서울");
  list.add(pdto);

  list.add(new PersonDTO("id-2", "이순신", 30, "인천"));
  list.add(new PersonDTO("id-3", "강감찬", 40, "부산"));
  list.add(new PersonDTO("id-4", "김유신", 50, "천안"));
  for (int idx = 0; idx < list.size(); idx++) {
   Object obj = list.get(idx);
   System.out.println(obj.toString());
  }
  System.out.println("-------이름들만 출력 getName()---------");
  for (int idx = 0; idx < list.size(); idx++) {
   PersonDTO obj = (PersonDTO) list.get(idx);
   System.out.println(obj.getName());
  }
  System.out.println("-------향상된 for문을 이용해 나이만 출력---------");
  for (Object o : list) {
   // PersonDTO pto = (PersonDTO)o;
   // System.out.println(pto.getAge());

   System.out.println(((PersonDTO) o).getAge());

  }
 }

 public static void arraylistBasic() {
  ArrayList list = new ArrayList(); // 배열에 몇개 들어갈지 모르겠다 하면 이렇게 선언하고 딱 몇개
           // 들어갈지 알면 아래와 같이 생성하는게 좋다. 수행시간이
           // 짧아진다.
  // ArrayList list = new ArrayList(10);//초기 length(저장할 수 있는 크기)
  // 추가
  list.add("유재석");
  list.add("박명수");
  list.add("정준하");
  list.add("노홍철");
  System.out.println(list);

  // 조회 - get(int idx) : Object - index의 시작 : 0
  String str = (String) list.get(0);
  System.out.println(str);

  System.out.println("-----전체 조회 패턴-----");
  // 전체 조회 패턴
  for (int idx = 0; idx < list.size(); idx++) {
   System.out.println(list.get(idx));
  }
  System.out.println("-----향상된 for문 이용 조회 1.5 이상----------");
  for (Object o : list) {
   System.out.println(o);
  }

  System.out.println("-----삭제----------");
  boolean flag = list.remove("유재석");
  System.out.println("삭제여부 : " + flag + " - " + list);

  Object obj = list.remove(1);
  System.out.println("삭제된 객체 : " + obj);
  System.out.println("삭제여부 : " + flag + " - " + list);

 }
}


* 5개의 로또번호 출력하기
ex :

package collection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;

public class Lotto {

 public static void main(String[] args) {
  //1~45의 숫자중 중복하지 않는 숫자 6개를 만들어 출력하시오.
  //[5,23,1,8,9,14]
  //랜덤한 숫자
  //숫자 - 6개
  //중복되지 않는 숫자를 어떻게 모을 것인가.
  
  ArrayList arrList = new ArrayList();
  //TreeSet lotto=null;

  for(int i =0;i<5;i++){
   TreeSet  lotto = new TreeSet();
   while(true){
    
    lotto.add((int)(Math.random()*45+1));

    if(lotto.size()==6){
  
     break;
    }
   }
  arrList.add(lotto);
  }
  System.out.println("로또 예상 : ");
  System.out.println(arrList);
  
  System.out.println("로또 예상 : ");
  for(int i=0;i<arrList.size();i++){
   System.out.println(arrList.get(i));
  }
  System.out.println("-----------향상된 for문----------");
  for(Object obj : arrList){
   //TreeSet ts = (TreeSet)obj;
   //System.out.println(ts);
   System.out.println(obj.toString());
   
  }

 }

}

* 2012-3-20

* ArrayList - 불안전한 대신에 퍼포먼스가 빠르다.(안전한 상황을 만들 수 있다.)
* Vector - 안전한 대신에 퍼포먼스가 느리다.
* Set - 순서허용X      추가 :  add(추가할 객체)
 중복허용X      삭제 : remove(삭제할 객체) : Object
* List- 순서허용       크기 : size()
 중복허용       조회 : set : X
                              List : get(index)
* Map - HashMap
      - HashTable <- Properties(어떤 설정을 저장할 때 사용)

* ProductManagerArrayList
  Package : product.dto ->DTO 클래스
       product.service -> ProductManagerService
     product.test -> ProductTest
  class :

1. DTO(tel, dvd)
2. ProductManagerService - Attribute,Product(),생성자, printProductList()

ex :
//TestProductManager.java


package product.test;
import java.util.ArrayList;
import java.util.List;

import product.dto.DVDPlayer;
import product.dto.ProductDTO;
import product.dto.Television;
import product.service.ProductManagerService;

public class TestProductManager{
 public static void main(String[] args){
  Television tv1 = new Television("tv-111", "LG-3D TV", 2000000, "LG", "최신형 티비", true, true, true);
  Television tv2 = new Television("tv-222", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
//  Television tv2 = new Television("tv-111", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
  DVDPlayer dvd1 = new DVDPlayer("dvd-111", "Bluelay-one", 120000, "삼성", "최신형 블루레이 플레이어", "C", true);
  DVDPlayer dvd2 = new DVDPlayer("dvd-222", "dvd-one", 50000, "LG", "DVD-RW 플레이어", "C", false);
  //관리자인 ProductManagerService객체 생성
  ProductManagerService pm = new ProductManagerService();
  pm.addProduct(tv1);
  pm.addProduct(tv2);
  pm.addProduct(dvd1); 
  pm.addProduct(dvd2);
  System.out.println("-------------상품 추가후---------------");
  pm.printProductList();//productList에 저장된 모든 ProductDTO 정보를 프린트
  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pm.searchProductById("tv-111");
  System.out.println("tv-111 제품 정보 : "+p1);
  ProductDTO p2 = pm.searchProductById("tv-222");
  System.out.println("tv-222 제품 정보 : "+p2);
  ProductDTO p3 = pm.searchProductById("dvd-111");
  System.out.println("dvd-111 제품 정보 : "+p3);
  //없는 ID로 조회
  ProductDTO p4 = pm.searchProductById("dvd-222");
  System.out.println("dvd-222 제품 정보 : "+p4);
  System.out.println("-----------정보수정--------------");
  dvd2 = new DVDPlayer("dvd-222", "dvd-one", 70000, "LG", "DVD-RW 플레이어", "Code free", true);
  pm.modifyProductInfo(dvd2);
  pm.printProductList();
  System.out.println("--------삭제----------");
  pm.removeProductById("tv-111");
  pm.printProductList();
  System.out.println("--------Maker조회----------");
  
  ArrayList list = pm.searchProductsByMaker("삼성");
  
  for(int i=0;i<list.size();i++){
   System.out.println(list.get(i));
  }
  
  System.out.println("--------remove조회----------");
  
 
  for(Object o : list){
   ProductDTO p = (ProductDTO)o;
   pm.removeProductById(p.getProductId());
  }
  pm.printProductList();
 }
}
-------------------------

package product.service;

import java.util.ArrayList;

import product.dto.ProductDTO;

public class ProductManagerService {
 private ArrayList productList;

 // private ArrayList productList = new ArrayList();

 // 생성자
 public ProductManagerService() {
  productList = new ArrayList();
 }

 private boolean isNull(Object obj) {
  // boolean flag = false;
  // if(obj ==null){
  // flag =true;
  // }
  // return flag;
  return obj == null;
 }

 // productList에 저장된 모든 제품 정보 출력
 public void printProductList() {
  // for(int i=0;i<productList.size();i++){
  // System.out.println(productList.get(i));
  // }
  for (Object obj : productList) {
   System.out.println(obj);
  }
 }

 // 추가
 public void addProduct(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("Null 데이터는 추가할 수 없습니다.");
   return;
  }

  ProductDTO pt = searchProductById(pdto.getProductId());
  if (!isNull(pt)) {
   System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요.");
   return;
  }
  /*
   * //같은 ID가 있는지 비교. for(int i=0;i<productList.size();i++){ // ProductDTO
   * pto = (ProductDTO)productList.get(i); //
   * if(pdto.getProductId().equals(pto.getProductId())){ // // }
   * if(((ProductDTO)
   * productList.get(i)).getProductId().equals(pdto.getProductId())){
   * System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요."); return; } }
   */

  productList.add(pdto);
 }

 // id로 제품을 조회해서 return
 public ProductDTO searchProductById(String productId) {

  ProductDTO pDTO = null;
  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return pDTO;
  }

  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId())
     .equals(productId)) {
    pDTO = ((ProductDTO) productList.get(i));
    break;
   }
  }
  return pDTO;

 }

 public void modifyProductInfo(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId()).equals(pdto
     .getProductId())) {
    productList.set(i, pdto);
    break;
   }
  }
 }

 public void removeProductById(String productId) {

  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
/*  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId())
     .equals(productId)) {
    //productList.remove(i);
    
    // productList.remove(productId);//객체를 전부 지워야하는데 이름만 넘겨서 이름만 지우는 역할을 한다.
   }

  }*/
  ProductDTO pto = searchProductById(productId);
  productList.remove(pto);
 }
 public ArrayList searchProductsByMaker(String productsMaker){
  ArrayList productMakers = new ArrayList();
  for(int i=0;i<productList.size();i++){
   if((((ProductDTO) productList.get(i)).getProductMaker()).equals(productsMaker)){
    productMakers.add(productList.get(i));
   }
  }
  return productMakers;
  
 }
}


--------------------

package product.dto;

public class ProductDTO {
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;
 public ProductDTO(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  this.productId = productId;
  this.productName = productName;
  this.productPrice = productPrice;
  this.productMaker = productMaker;
  this.productInfo = productInfo;
 }
 public ProductDTO() {
 }
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getProductPrice() {
  return productPrice;
 }
 public void setProductPrice(int productPrice) {
  this.productPrice = productPrice;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 public String getProductInfo() {
  return productInfo;
 }
 public void setProductInfo(String productInfo) {
  this.productInfo = productInfo;
 }
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", productPrice=" + productPrice
    + ", productMaker=" + productMaker + ", productInfo="
    + productInfo + "]";
 }
 
}


-----------------


package product.dto;

public class Television extends ProductDTO{
 private boolean threeD;
 private boolean smartTV;
 private boolean usb;
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo, boolean threeD,
   boolean smartTV, boolean usb) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.threeD = threeD;
  this.smartTV = smartTV;
  this.usb = usb;
 }
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public boolean isThreeD() {
  return threeD;
 }
 public void setThreeD(boolean threeD) {
  this.threeD = threeD;
 }
 public boolean isSmartTV() {
  return smartTV;
 }
 public void setSmartTV(boolean smartTV) {
  this.smartTV = smartTV;
 }
 public boolean isUsb() {
  return usb;
 }
 public void setUsb(boolean usb) {
  this.usb = usb;
 }
 @Override
 public String toString() {
  return "Television [threeD=" + (threeD ? "3DTV" : "2GTV") + ", smartTV=" + (smartTV ? "스마트TV" : "일반TV")
    + ", usb=" + (usb ? "Usb사용가능" : "usb사용불가능") + ", 일반제품정보=" + super.toString() + "]";
 }

 

 
 
}


---------------------

package product.dto;

public class DVDPlayer extends ProductDTO{
 private String areaCode;
 private boolean bluelay;
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo, String areaCode,
   boolean bluelay) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.areaCode = areaCode;
  this.bluelay = bluelay;
 }
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public String getAreaCode() {
  return areaCode;
 }
 public void setAreaCode(String areaCode) {
  this.areaCode = areaCode;
 }
 public boolean isBluelay() {
  return bluelay;
 }
 public void setBluelay(boolean bluelay) {
  this.bluelay = bluelay;
 }
 @Override
 public String toString() {
  return "DVDPlayer [areaCode=" + areaCode + ", bluelay=" + (bluelay? "사용가능" : "사용불가능")
    + ", 일반제품정보=" + super.toString() + "]";
 }

 

}

----------------------------

===========================================================================================

* 2012-3-21

* 전체적으로 조회하는 것은 List가 좋고, 키 값을 가지고 딱 하나만 찾아 낼때는 Map이 편하다.
* Map -* HashTable <- Properties(객체와 객체에서 문자열로 특화시킨 것) <- key(String)
                                    value(String)
      -* HashMap <- key(Object) : key값 안에 들어가는 타입은 거의 String이 들어간다.
      중복허용(X)
      같은 Key-Object추가
      replace처리.
                    value(Object) : 중복허용(O)
        순서개념 없다.
* Map -* key - value
        (Object) (Object)

         - key와 value를 합치면 entry라 부른다.

- 메소드

추가, 변경(replace) : put(Object key,Object value)
조회 : get(Object key) : Object(Value)
삭제 : remove(Object key) : Object(Value)
Key값들(전체)을 조회하는 메소드 : keySet() : Set
entry들(전체)을 조회하는 메소드 : entrySet() : Entry
전체데이터 삭제 : clear()
entry의 개수 : size() : int

* key값의 존재 유무 :  containsKey(Object key) : boolean
  Value값의 존재 유무 :  containsValue(Object value) : boolean

* Map은 테이블 형태로 들어간다.

key    value
-----------------
| k1   |   1    |->entry
|-------------
| k2   |   2    |
|---------------
 

* project : day19
  package : collection.map
  class : MapTest

*new버전 :  java.util.Iterator (Interface) - 조회와 삭제가 가능
 old버전 : (java.util.Enumeration) (Interface) -  조회만 가능
 ->Collection(Interface) 객체가 관리하는 값(객체)들을 조회.

* Iterator : 조회와 삭제를 해준다.(데이터를 모아놓은 List나 Map이 있으면 옆에 붙어서 데이터를 조회 삭제만 한다. 데이터를 직접 모으진 않는다.)
  (장점 :  List나 Map, Set 등의 방법을 Iterator를 통해서 조회해 올수 있다. Set은 조회 방법이 없는데 Iterator를 통해서는 가능하다.)
  -> 값을 순서적으로 돌면서 하나씩 넘겨준다. 값이 없으면 값을 넘기지 않는다.

- Iterator메소드
가져올 값(return할 값)이 있는지 유무 :  hasNext() : boolean
값 리턴 : next() : Object
값 삭제 : remove() : void

- Enumeration
가져올 값(return할 값)이 있는지 유무 :  hasMoreElements() : boolean
값 리턴 : nextElement() : Object

* 사용법

Collection객체.iterator() -> Iterator
Collection객체 = Set,List..


* iterator를 사용한 조회
ex :
  System.out.println("----------Iterator를 이용한 조회-----------------");
  
  Iterator itr = set.iterator();
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
  
  while(itr.hasNext()){
   Object obj = itr.next();
   System.out.println(obj);
  }

-------------------------------------------------------------------------------

* Map을 사용한 상품관리 소스

package product.test;
import java.util.ArrayList;
import java.util.List;

import product.dto.DVDPlayer;
import product.dto.ProductDTO;
import product.dto.Television;
import product.service.ProductManagerService;
import product.service.ProductManagerServiceMap;

public class TestProductManagerMap{
 public static void main(String[] args){
  Television tv1 = new Television("tv-111", "LG-3D TV", 2000000, "LG", "최신형 티비", true, true, true);
  Television tv2 = new Television("tv-222", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
//  Television tv2 = new Television("tv-111", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
  DVDPlayer dvd1 = new DVDPlayer("dvd-111", "Bluelay-one", 120000, "삼성", "최신형 블루레이 플레이어", "C", true);
  DVDPlayer dvd2 = new DVDPlayer("dvd-222", "dvd-one", 50000, "LG", "DVD-RW 플레이어", "C", false);
  //관리자인 ProductManagerService객체 생성
  ProductManagerServiceMap pm = new ProductManagerServiceMap();
  pm.addProduct(tv1);
  pm.addProduct(tv2);
  pm.addProduct(dvd1); 
  pm.addProduct(dvd2);
  System.out.println("-------------상품 추가후---------------");
  pm.printProductList();//productList에 저장된 모든 ProductDTO 정보를 프린트
  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pm.searchProductById("tv-111");
  System.out.println("tv-111 제품 정보 : "+p1);
  ProductDTO p2 = pm.searchProductById("tv-222");
  System.out.println("tv-222 제품 정보 : "+p2);
  ProductDTO p3 = pm.searchProductById("dvd-111");
  System.out.println("dvd-111 제품 정보 : "+p3);
  //없는 ID로 조회
  ProductDTO p4 = pm.searchProductById("dvd-222");
  System.out.println("dvd-222 제품 정보 : "+p4);
  System.out.println("-----------정보수정--------------");
  dvd2 = new DVDPlayer("dvd-222", "dvd-one", 702010, "LG", "DVD-RW 플레이어", "Code free", true);
  pm.modifyProductInfo(dvd2);
  pm.printProductList();
  System.out.println("--------삭제----------");
  pm.removeProductById("tv-111");
  pm.printProductList();
  System.out.println("--------Maker조회----------");
  
  ArrayList list = pm.searchProductsByMaker("삼성");
  
  for(int i=0;i<list.size();i++){
   System.out.println(list.get(i));
  }
  
  System.out.println("--------remove조회(Maker로 조회해서 온것 다 삭제----------");
  
 
  for(Object o : list){
   ProductDTO p = (ProductDTO)o;
   pm.removeProductById(p.getProductId());
  }
  pm.printProductList();
 }
}
---------------------------------

package product.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

 

import product.dto.ProductDTO;

public class ProductManagerServiceMap {
 private HashMap productList;

 // private ArrayList productList = new ArrayList();

 // 생성자
 public ProductManagerServiceMap() {
  productList = new HashMap();
 }

 private boolean isNull(Object obj) {
  // boolean flag = false;
  // if(obj ==null){
  // flag =true;
  // }
  // return flag;
  return obj == null;
 }

 // productList에 저장된 모든 제품 정보 출력
 public void printProductList() {

  Set key = productList.keySet();
  Iterator itr = key.iterator();
  while(itr.hasNext()){
//   Object key1 = itr.next();
//   ProductDTO value1 = (ProductDTO) productList.get(key1);
//   System.out.println(value1);
   System.out.println((ProductDTO) productList.get(itr.next()));
   
  }
//  for (Object obj : productList) {
//   System.out.println(obj);
//  }
 }

 // 추가
 public void addProduct(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("Null 데이터는 추가할 수 없습니다.");
   return;
  }

  /*
   * //같은 ID가 있는지 비교. for(int i=0;i<productList.size();i++){ // ProductDTO
   * pto = (ProductDTO)productList.get(i); //
   * if(pdto.getProductId().equals(pto.getProductId())){ // // }
   * if(((ProductDTO)
   * productList.get(i)).getProductId().equals(pdto.getProductId())){
   * System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요."); return; } }
   */
  if(productList.containsKey(pdto.getProductId())){
   System.out.println("동일한 아이디가 있습니다.");
   return;
  }
  productList.put(pdto.getProductId(), pdto);
 }

 // id로 제품을 조회해서 return
 public ProductDTO searchProductById(String productId) {

  return (ProductDTO) productList.get(productId);

 }

 public void modifyProductInfo(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  if(!productList.containsKey(pdto.getProductId())){
   System.out.println("동일한 Id가 없습니다.");
   return;
  }
  productList.put(pdto.getProductId(), pdto);

 }

 public void removeProductById(String productId) {

  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  if(!productList.containsKey(productId)){
   System.out.println("동일한 아이디가 없습니다.");
   return;
  }
  productList.remove(productId);
  
 }
 public ArrayList searchProductsByMaker(String productsMaker){
  ArrayList list = new ArrayList();
  

  Set keys = productList.keySet();
  Iterator itr = keys.iterator();
  while(itr.hasNext()){
   Object id = itr.next();
   ProductDTO pto = (ProductDTO) productList.get(id);
   if(productsMaker.equals(pto.getProductMaker())){
    list.add(pto);
   }
  }
  return list;
  
 }
}


---------------------------------

package product.dto;

public class ProductDTO {
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;
 public ProductDTO(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  this.productId = productId;
  this.productName = productName;
  this.productPrice = productPrice;
  this.productMaker = productMaker;
  this.productInfo = productInfo;
 }
 public ProductDTO() {
 }
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getProductPrice() {
  return productPrice;
 }
 public void setProductPrice(int productPrice) {
  this.productPrice = productPrice;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 public String getProductInfo() {
  return productInfo;
 }
 public void setProductInfo(String productInfo) {
  this.productInfo = productInfo;
 }
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", productPrice=" + productPrice
    + ", productMaker=" + productMaker + ", productInfo="
    + productInfo + "]";
 }
 
}


-----------------------

package product.dto;

public class Television extends ProductDTO{
 private boolean threeD;
 private boolean smartTV;
 private boolean usb;
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo, boolean threeD,
   boolean smartTV, boolean usb) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.threeD = threeD;
  this.smartTV = smartTV;
  this.usb = usb;
 }
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public boolean isThreeD() {
  return threeD;
 }
 public void setThreeD(boolean threeD) {
  this.threeD = threeD;
 }
 public boolean isSmartTV() {
  return smartTV;
 }
 public void setSmartTV(boolean smartTV) {
  this.smartTV = smartTV;
 }
 public boolean isUsb() {
  return usb;
 }
 public void setUsb(boolean usb) {
  this.usb = usb;
 }
 @Override
 public String toString() {
  return "Television [threeD=" + (threeD ? "3DTV" : "2GTV") + ", smartTV=" + (smartTV ? "스마트TV" : "일반TV")
    + ", usb=" + (usb ? "Usb사용가능" : "usb사용불가능") + ", 일반제품정보=" + super.toString() + "]";
 }

 

 
 
}


------------------------

package product.dto;

public class DVDPlayer extends ProductDTO{
 private String areaCode;
 private boolean bluelay;
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo, String areaCode,
   boolean bluelay) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.areaCode = areaCode;
  this.bluelay = bluelay;
 }
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public String getAreaCode() {
  return areaCode;
 }
 public void setAreaCode(String areaCode) {
  this.areaCode = areaCode;
 }
 public boolean isBluelay() {
  return bluelay;
 }
 public void setBluelay(boolean bluelay) {
  this.bluelay = bluelay;
 }
 @Override
 public String toString() {
  return "DVDPlayer [areaCode=" + areaCode + ", bluelay=" + (bluelay? "사용가능" : "사용불가능")
    + ", 일반제품정보=" + super.toString() + "]";
 }

 

}


----------------------


* map 타입 맞추기
HashMap map = new HashMap();
map.put("name","홍길동");
map.put("age",10);

Set ke = map.keySet();
Iterator itr = ke.iterator();
while(itr.hasNext()){
String k = (String)itr.next();
String v = (String)map.get(k);  //이렇게 하면 age의 10인 Integer를 받아올 때 실행시점에 에러가 난다.

그래서 제너릭을 사용해서 map만들 시에 타입을 HashMap<String, String> map = new HashMap(); 이렇게 해서 String 타입만 넣을 수 있게 한다.
제너릭은 실행 시점에 지정한다.

* Generic(제너릭) : class에서 사용할 type을 class작성시 지정하는 것이 아니라 사용시점에 지정하는 것.
구문 :  class선언
public class ClassName<E>{
public void go(E e){
}

사용
ClassName<String> c1 = new ClassNAme<String>();
ClassName<Human> c2 = new ClassName<Human>();

c1.go(String s);//(O)
c1.go(Integer i);//(X)


* Generic파라미터는 static 멤버에서는 사용 불가능 하다.

ArrayList<String> list = new ArrayList<String>();
list.add("aaa");
String str = list.get(0);
//list.add(new Human());//(X)

* 2012-3-22

* Enumeration enu;

while(enu.hasMoreElements()){
Object obj = enu.nextElement();
}

* 값 빼오는 패턴
1. 배열 - arr

for(int idx = 0;idx<arr.length;idx++)
{
 arr[idx];
}

2. List( ArrayList ) - list

for(int idx = 0; idx <list.size(); idx++){
 Object obj = list.get(idx); 
 
}

3. Set - set

Iterator itr = set.iterator();
while(itr.hasNext()){
 Object obj = itr.next();
}

1.5버전 이상일때는 향상된 for문도 된다
for(Object o : set){
 Object obj = o;
}

4. Map - map

Set keys = map.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()){
 Object key = itr.next();
 Object value = map.get(key);
}

* 제너릭 -1.5 : class에 사용할 type - class 작성 X
                                    - 사용시점에 지정 - O


ex :

A<String> a = new A<String>();

class A<String>{
 public void go(String a){
 }
}


위처럼 하면 A<String> a = new A<String>();
a.go();<-를 하면 String 값을 넘기는 것 밖에 안된다.
* 제너릭을 사용하지 않으면 실행은 잘되는데 컴파일 시점에 문제가 생길 수 있다.
제너릭을 쓰는 이유 Object 타입으로 썼을 경우 다른 객체들이 들어오는 건 장점이기도 하지만, 형변환시 문제가 생길 수 있기에 사용한다.
(타입에 대한 불안정을 해결해 준다.)


Project : day22
package : generic
class :   GenericTest


package generic;
class BasicGeneric<E , K>{
 
 public void printInfo(E obj){
//  if(obj instanceof String){
//  String str = (String)obj;
//  }
  System.out.println(obj);
 }

 public void test(K k){
  
 }
}
public class GenericTest {
 public static void main(String[] args) {
  BasicGeneric<String,String> b = new BasicGeneric<String,String>();
  b.printInfo("abcde");
  //b.printInfo(new Integer(10));
  BasicGeneric<Integer,String> b2 = new BasicGeneric<Integer,String>();
  b2.printInfo(new Integer(10));
 // b2.printInfo("abcde");
  BasicGeneric b3 = new BasicGeneric();//BasicGeneric<Object> b2 = new BasicGeneric<Object>();
  b3.printInfo("abcde");
  b3.printInfo(new Integer(20));
 }
}

-----------------
=============================================


Project : day22
package : generic
class :   CollectionGeneric

package generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class CollectionGeneric {
 public static void main(String[] args) {
  ArrayList<String> list = new ArrayList<String>();
  list.add("String1");
  list.add("String2");
  //list.add(new Integer(10));
  //list.add(new CollectionGeneric());
  String str = list.get(0);
  
  for(String o : list){
   System.out.println(o); 
  }
  //////////map//////////
  HashMap<String,Integer> map = new HashMap<String,Integer>();
  //map.put("name", "홍길동");
  map.put("age", 10);
  map.put("age", new Integer(20));
  Integer age = map.get("age");
  Set<String> keys = map.keySet();
  Iterator<String> itr = keys.iterator();
  while(itr.hasNext()){
   String key = itr.next();
   Integer value = map.get(key);
   System.out.println(key+"-"+value);
  }
 }
}

---------
=====================================================

* Object class
- java.lang.Object : 모든 class의 최상위->모든 객체의 type이 될 수 있다.

* Object class는 추상적이어서 여기 있는 메소드를 직접 사용하는게 중요한게 아니라 하위 클래스에서 오버라이딩 해서 사용하는 것이 중요하다.
* +toString() : String -> 객체(Object)를 String으로 변환
- 메서드 이름이 객체.toXXXX()로 되면
to -> 변환

ex :
ProductDTO p = new ProductDTO();
p.toString(); <- p객체를 String으로 바꿔라.
* class이름@16진수 "ProductDTO@a567.." 이런식으로 바꿔준다. @a567...은 hashCode(객체의 가상의주소)로 바꿔준다.
->Object 타입의 toString()은 사용하지 않는다. 중요한 것은 오버라이딩 해서 사용하는 것이 중요한 것이다.
->toString()을 오버라이딩 할 시에는 Attribute들을 문자열로 return해줌.
(대표적인 toString()오버라이드한 객체들 String, StringBuffer, WrapperClass, Collection)

*equals(obj : Object) : boolean
- 매개변수로 받은 객체가 같은 객체인지 비교
ex)  obj1.equals(obj2); -> obj1==obj2


- overriding : 두객체의 attribute의 값이 같다면 true 리턴

equals overriding
public boolean equals(Object obj){
 1. obj가 null인지
 2. obj가 같은지
 3. 속성값들이 같은지
}
- equals()메소드를 오버라이딩 할때 반드시 hashCode()메소드도 같이 overriding한다.
-> + int hashCode()도 오버로딩 해야함.

o1.equals(o2); ==> true 면
o1.hashCode() ==> attribute가 같으면 hashCode()도 같게 나오게 해야한다.
o2.hashCode() ==> 디 둘도 true가 나와야 같은 객체라 생각한다.

* 값을 비교할때 equals를 쓴다. 따라서 attribute가 같으면 같은 객체다. equals메소드가 true가 나오고 hashCode()값도 true가 나와야 같은 객체다.
(equals overriding하면 hashCode()도 오버라이딩 해라.

project : day22
package : object.method
class :  ProductDTO

 

package object.method;

public class ProductDTO {
 private String productId;
 private String productName;
 private int price;
 private String productMaker;
 
 //생성자
 public ProductDTO() {
 }
 public ProductDTO(String productId, String productName, int price,
   String productMaker) {
  this.productId = productId;
  this.productName = productName;
  this.price = price;
  this.productMaker = productMaker;
 }
 
 //getter/setter
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getPrice() {
  return price;
 }
 public void setPrice(int price) {
  this.price = price;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 //toString()
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", price=" + price + ", productMaker="
    + productMaker + "]";
 }
 //equals(), hashCode()
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + price;
  result = prime * result
    + ((productId == null) ? 0 : productId.hashCode());
  result = prime * result
    + ((productMaker == null) ? 0 : productMaker.hashCode());
  result = prime * result
    + ((productName == null) ? 0 : productName.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  ProductDTO other = (ProductDTO) obj;
  if (price != other.price)
   return false;
  if (productId == null) {
   if (other.productId != null)
    return false;
  } else if (!productId.equals(other.productId))
   return false;
  if (productMaker == null) {
   if (other.productMaker != null)
    return false;
  } else if (!productMaker.equals(other.productMaker))
   return false;
  if (productName == null) {
   if (other.productName != null)
    return false;
  } else if (!productName.equals(other.productName))
   return false;
  return true;
 }
}


-----------------

package object.method;

import java.util.HashSet;

public class TestEquals {
 public static void main(String[] args) {
  ProductDTO pto1 = new ProductDTO("p-1","TV",2000,"LG");
  ProductDTO pto2 = new ProductDTO("p-1","TV",2000,"LG");
  System.out.println("pto1 == pto2 - >"+(pto1==pto2));//객체의 주소값 비교
  boolean flag = pto1.equals(pto2);
  System.out.println("pto1.equals(pto2) -> "+flag);
  HashSet set = new HashSet(); //중복허용 X
  set.add(pto1);
  set.add(pto2);
  System.out.println(set);//equals와 hashCode를 둘다 오버라이딩 해야 같은 객체로 판단한다.
 }
}


---------------
===============================================================

* DTO - 값표현 (type) - 값
  1. private Attribute(instance 변수)
  2. 생성자 - no-args
     - 모든 Attribute값 설정
  3. public setter/getter 메소드
  4. toString(), equals(), hashCode() -> overrding 하는 것 까지가 기본이다.
1.3번을 합쳐서 property라 한다.


* java.lang.Class : class의 정보를 처리하는 객체

->1. Object : +getClass() : Class

Class c = obj.getClass();

  2. Class이름.class -> Class객체
Class c = ProductDTO.class

  3. Class.forName("class의 fullyNAme");
     Class c = Class.forName("dto.ProductDTO");


Class cls = obj.getClass();
String str = cls.getName();
Field[] = cls.getDeclaredFields();
Method[] = cls.getDeclaredMethods();

* Wrapper 클래스 : 자바의 프리미티브 타입을 객체화 시킬때 사용 (프리미티브 타입이 8개 있어서 Wrapper 타입도 8개가 있다)
- 자바에서 타입은 프리미티브 타입(int, double, float,...)과 레퍼런스 타입이 있다.
int i = 20;
ArrayList list = new ArrauList();
list.add(i);

ArrayList에는 세상에 존재하는 모든 객체를 넣어서 관리할 수 있지만 세상에 존재하는 모든 값들을 넣어서 관리할 수 있지는 않다.
객체들 밖에 못넣기때문에 프리미티브 타입은 넣을 수 없다.
프리미티브 타입을 객체로 만들어서 넣어야한다.

* 프리미티브 타입

char - Character
int - Integer
long - Long
double - double
float - float
byte - Byte
short - short
boolean - Boolean

* boxing : primitive - > Wrapper객체화
생성자의 argument로 넣어 객체 생성.
ex:
   new Integer(10);
   new Integer("10");// 숫자로 받을 수 있는 문자열도 넣을 수 있다.
   new Long(l); //long, double, float... 다 마찬가지로 숫자와 문자열을 넣을 수 있다.

- unboxing :  Wrapper객체 -> primitive
       wrapper객체.xxxValue();//xxx에는 primitive type이 온다.

int i = in.intValue();
long l = ln.longValue();

jdk1.5버전 이상부터는 자동으로 일어난다.
- autoboxing
int i = 10;
Integer in = new Integer(i);
Integer in = i;
Long l = 10L;

 

- autounboxing
Integer in = new Integer(10);
int i = in.intValue();
int i = in;

*
project : day22
package : wrapper
class : WrapperTest


package wrapper;

import java.util.ArrayList;

public class WrapperTest {
 public static void boxingUnboxingTest(){
  //boxing : primitive -> 객체(Wrapper)
  int i=10;
  Integer in = new Integer(i);
  Boolean b = new Boolean(false);
  Long l = new Long("10");
  //unboxing : Wrapper 객체 -> primitive
  int j = in.intValue();
  boolean b2 = b.booleanValue();
  long l2 = l.longValue();
  System.out.println(in+" - "+j);
 }
 public static void autoBoxingUnboxing(){
  //auto boxing
  Integer in =10;
  Boolean b1 = true;
  
  //auto unboxing
  int i = in;
  boolean b = b1;
  
  ArrayList list = new ArrayList();
  list.add(20);//Integer객체
  list.add(50L);//Long 객체
  list.add(false);//Boolean 객체
  int j = (Integer)list.get(0);
  long l = (Long)list.get(1);
  boolean b2 = (Boolean)list.get(2);
  ArrayList<Integer> list2 = new ArrayList<Integer>();
  list2.add(10);
  list2.add(20);
  int k = list2.get(0);
  //향상된 for문으로 list 출력
  for(Object o : list){
   System.out.println(o);
  }
 }
 public static void StringToWrapper(){
  //문자열 값을 Wrapper 객체에 넣기.
  //Integer in = "10";
  Integer in = new Integer("10");
  int i = in;
  Boolean b1 = new Boolean("false");
  //Long l1 = new Long("abcde");//숫자형태가 아니기 떄문에 컴파일 시점에는 괜찮지만 실행시점에서 에러가 난다.
  //Long l1 = new Long("10abcde");
  Long l1 = new Long("10");
  //String -> primitive
  //WrapperClass.parseXXXX(xxxx); XXXX프리미티브
  int r = Integer.parseInt("20030");
  double d = Double.parseDouble("2030.12");
  boolean b = Boolean.parseBoolean("false");
  //float f = Float.parseFloat("abcde"); //숫자로 바꿀수 없기때문에 컴파일은 되도 실행시점에서 오류가 난다. 숫자로 바꿀수 있는 문자열을 넣어야 한다.
  //char c = Character.parseChar("a");//이런건 없다.
  char c = "a".charAt(0);
 }
 public static void main(String[] args) {
  boxingUnboxingTest();
  autoBoxingUnboxing();
  StringToWrapper();
 }
}

---------------------
=============================================================================

* 2012-3-23
toString()
equals()
hashCode()


* toString() - 객체를 String으로 바꿔주는 것.
- Object의 toString은 @16진수값으로 나오기때문에 자기가 쓸 것에 맞춰서 오버라이딩 해야한다.
-> 객체가 가지고 있는 Attribute 값을 알려주기 위해 작성한다.

* equals는 호출한 객체와 매개변수로 받은 객체가 완전 똑같은 객체냐고 비교한다. (객체==매개변수로 받은 객체)
->객체는 다르지만 안에 들은 값이 같냐고 묻는 경우에는 오버라이딩 해야한다.

*
1. o1.equals(o2); //true
2. int i = o1.hashCode();
int j = o2.hashCode();
i == j 가 같아야 같은 객체다.

* boxing : primitive를 객체로 만드는 것
int i = 20;
Integer in = new Integer(i);
                         <- ("20");
* autoboxing
Charactor c = 'A';

* unboxing : 객체를 primitive로 만드는 것
1.4 : int i = in.intValue();
1.5 : int i = in;

* primitive를 객체화 시키는 이유는 Collection이 객체만 담기 때문에 Collection에 넣기 위해서 이다.
* String을 primitive로 바꾸는 경우
ex : "20" + "30";

int i = Integer.parseInt("10");
long l = Long.parseLong("10");
boolean = Boolean.parseBoolean("false");

//char만 변환시킬수 없다. 나머지 프리미티브 타입은 다되고, 반드시 바뀔 수 있는 형태의 문자열이어야 한다.

 

* api에서 제공해주는 소스를 보려면
C:\Program Files\Java\jdk1.6.0_31\src.zip\java\lang
가서 봐라.

* 문자열 관리해주는 class - String, StringBuffer(String에 가기 전 임시저장소), StringBuilder
                            ->char[]로 처리한다. -> length : 글자수
                                                 -> idx : 글자의 위치

String s = "Hello";
     idx가  01234
만약에 s.charAt(4);//o 가 나온다.

char c1 = 'H';
char c2 = 'e';
char c3 = 'l';
char c4 = 'l';
char c5 = 'o';

char[] c = {'H','e','l','l','o'};

* String - 한번 객체가 만들어 지면 그 값은 절대 불변.
ex:
String s = "abc";//String s = new String("abc"); //한번 abc 문자열이 들어가면 죽을 때 까지 abc를 가지고 있는 객체가 된다.
s.concat("def"); //abc def가 따로 객체가 2개가 생긴다.
system.out.println(s); //결과 : abc

->값 : " "
  객체 : String s = "abc";
  String s = new String("abc");


* project : day23
  package : string
  class : StringTest

package string;

public class StringTest {
 public static void main(String[] args) {
  String s1 = "abcde";
  String s2 = new String("abcde");
  String s3 = "ABCDE";
  //글자수를 조회하는 메소드
  int strLength = s1.length();
  System.out.println(strLength);
  //두 String의 내용값이 같은지 비교
  System.out.println("s1 == s2 : "+(s1 == s2));//주소값 비교  다른객체를 비교하니 결과 :  false
  System.out.println("s1.equals(s2) : "+s1.equals(s2));//내용값 비교      //내용이 같으니 결과 : true
  System.out.println("s1.equals(s3) : "+s1.equals(s3));                     //대소문자가 달라서 결과 : false
  System.out.println("s1.equalsIgnoreCase(s3) : "+s1.equalsIgnoreCase(s3));//대소문자 무시하고 내용값 비교  //대소문자를 무시하니 결과 : true
  //조회하는 메소드들
  //특정문자열로 시작/끝나는지 비교
  //시작
  boolean flag = s1.startsWith("ab");//ab로 시작하는지?
  System.out.println("s1.startsWith(\"ab\") : "+flag);
  System.out.println("s1.endsWith(\"ef\") : "+s1.endsWith("ef"));
  //특정 문자나 문자열이 몇번째 글자인지 조회
  String s4 = "abc abc abcdef";//a : 0, 4, 8
  int idx = s4.indexOf("a");        
  System.out.println("s4.indexOf(\"a\") : "+idx); //찾아서 a를 딱 찾으면 그 index만 리턴
  System.out.println("s4.indexOf(\" abc\") : "+s4.indexOf(" abc")); //공백 index는 3번에 있다
  //뒤에서부터 조회
  System.out.println("s4.lastIndexOf(\"a\") : "+s4.lastIndexOf("a"));//뒤에서 부터 a를 찾으면 8번이 된다.
  System.out.println("s4.lastIndexOf(\" abc\") : "+s4.lastIndexOf(" abc")); //뒤어서 부터 공백abc를 찾으면 7이 된다.
  System.out.println("s4.indexOf(\"a\", 2) : "+s4.indexOf("a", 2));//2번 index에서부터 찾기 시작
  //String 에서 특정 index의 문자를 조회
  char c = s4.charAt(5);//5번 index의 char를 return
  System.out.println("s4.charAt(5) : "+c);  //5번에 있는 문자를 리턴해서 b리턴
  //문자열 일부분을 조회
  String s5 = "안녕하세요. Hello. 반갑습니다.";
  //반 : 14 H : 7 , 12
  String ss = s5.substring(14);//14번 index 부터 끝까지
  System.out.println("s5.substring(14) : "+ss);//14번 index 부터 끝까지  결과 :  반갑습니다.
  System.out.println("s5.substring(7, 12) : "+s5.substring(7, 12));//7~12-1 결과 : Hello
  //변경 하는 메소드
  //대문자->소문자
  ss = s3.toLowerCase(); //객체가 따로 만들어 지므로 변수에 대입해야 한다. 결과 : abcde 문자열 전부 대문자로 바꾸기 ctrl + shift + x, 소문자로 바꾸기 ctrl + shift + y
  System.out.println(s3+","+ss);
  //소문자 -> 대문자
  ss = s1.toUpperCase();
  System.out.println(s1+","+ss);
  //특정 char를 다른 char로 변경
  String s6 = "ababaaabb";
  //'a' -> 'k'
  ss = s6.replace('a', 'k');
  System.out.println(s6+","+ss);
  //특정 문자열을 다른 문자열로 변경
  ss = s5.replaceAll("Hello", "헬로");
  System.out.println(s5+","+ss);
  String s7 = "사과.배.귤,포도,딸기,메론,바나나";
  //String [] fruit = s7.split("\\.");
  String [] fruit = s7.split(",");
  //String [] fruit = s7.split(" ");
  System.out.println("------split() : 과일들----");
  for(String str : fruit){
   System.out.println(str);
  }

 }
}
//StringTest.java

-----------
================================================================

* project : day23
  package : string
  class : GetExention


package string;

public class GetExtention {

 public static void main(String[] args) {
  // command line argument로 파일명.확장자를 받아서 확장자만 출력하는 로직 구현
  // abc.txt -> txt
  // System.out.println(args[0]);
  System.out.println(args[0]);
  if(args.length!=1){
   System.out.println("사용법 : java GetExtension");
   return ;
  }
  String fileName = args[0];
  
  int idx = args[0].lastIndexOf(".");
  if(idx !=-1){
  String str = args[0].substring(idx+1);
  System.out.println(str);

  }else{
   System.out.println("확장자가 없습니다.");
  }
 }

}


------------------------
===========================================================================


* StringBuffer --
                 |->문자열을 다루기(변경) 위한 class
  StringBuilder--
  (->String을 만들기위해서 만든것)

String s = "abc";
String s2 = s.concat("def");

StringBuffer sb = new StringBuffer("abc");
sb.append("def");

system.out.println(sb); //결과 : abcdef

* 문자열을 붙일때는 String을 사용하면 여러개의 객체가 생겨서 좋지 않고, 임시적으로 데이터를 저장하기 위해서는 StringBuffer가 좋다. (중간에 문자열을 바꿔나갈때는 StringBuffer가 좋다. 결과는 마지막에 String에 담아 주면 된다.)

* 처음에 StringBuffer나 StringBuilder에 크기를 정해 놓고 할 수 있다. 미리 정해 두고 하는게 속도 측면에서 좋다. new StringBuffer("초기 문자열");
* 초기 문자열을 넣어두고 시작할 수 있다. new StringBuffer(10); //초기 문자열을 넣어두고 넘치면 그 글자수가 늘어난다.

----------------------------------------------------------------------------

* 시간, 날짜 처리
java.util.Date
java.util.Calendar

- GregorianCalendar

생성자 종류
GregorianCalendar()
GregorianCalendar(int y, m, d)
GregorianCalendar(int y, m, d, h, m)

.get(int year)

- 요일 (일요일(0)~토요일(6))

package calendar;

import java.util.*;
public class CalendarTest {
 public static void main(String[] args) {
  //현재 시간을 출력하는 프로그램을 만드세요.- Calendar, GregroianCalendar
  //Calendar c = Calendar.getInstance();    //아래 GregorianCalendar gc = new GregorianCalendar(); 이렇게 사용한 것과 같다.
//  GregorianCalendar gc = new GregorianCalendar();
//  TimeZone tz = TimeZone.getTimeZone("Europe/London");
//  gc.setTimeZone(tz);//영국시간대로 변경
  GregorianCalendar gc = new GregorianCalendar(2005,2, 20);

//  System.out.println(gc.isLeapYear(2012));  //윤년이 있는지 없는지를 알려줌.
  int year = gc.get(Calendar.YEAR);
  int month = gc.get(Calendar.MONTH)+1;
  int day = gc.get(Calendar.DATE);//Calendar.DAY_OF_MONTH
  String amPm = (gc.get(Calendar.AM_PM)==Calendar.AM) ? "오전":"오후";
  int hour = gc.get(Calendar.HOUR);//0~11, Calendar.HOUR_OF_DAY:0~23
  int minute = gc.get(Calendar.MINUTE);
  int second = gc.get(Calendar.SECOND);
  String dayOfWeek = null;
  switch(gc.get(Calendar.DAY_OF_WEEK)){
   case Calendar.SUNDAY:
    dayOfWeek = "일요일";
    break;
   case Calendar.MONDAY:
    dayOfWeek = "월요일";
    break;
   case Calendar.TUESDAY:
    dayOfWeek = "화요일";
    break;
   case Calendar.FRIDAY:
    dayOfWeek = "금요일";
    break;
   
  }
  //2011년 10월 4일 오전 11시 21분 23초 화요일
  System.out.println(year+"년 "+month+"월 "+day+"일 "+amPm+" "+hour+"시 "+minute+"분 "+second+"초 "+dayOfWeek);

 }
}


---------------
=======================================================

*세계시간 구하기(타임존 구하기)

package calendar;

import java.util.TimeZone;

public class PrintTimeZone {
 public static void main(String[] args) {
 String [] timeZone = TimeZone.getAvailableIDs();
  for(String tz : timeZone){
   System.out.println(tz);
  }
 }
}

----------
========================================================

* project : day23
package : calendar
class : CalendarTest2


package calendar;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarTest2 {
 public static void main(String[] args) {
  long l1 = System.currentTimeMillis(); //현재시간을 1/1000 초로 알려줌. 1970.1.1.0.0.0.0초 부터
  for(int i =0;i<1000;i++){
//   System.out.println(i);
  }
  System.out.println(l1);
  long l2 = System.currentTimeMillis();
  System.err.println(l2 - l1);
  GregorianCalendar gc = new GregorianCalendar();
  long miliS = gc.getTimeInMillis();
  System.out.println(miliS);
  
  System.out.println("-----------SimpleDateFormat을 이용--------------");
  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd a HH : mm : ss E"); //a는 오전,오후 E는 요일
  //String str = sf.format(gc); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  
  Date d = gc.getTime();//GregorianCalendar을 Date 타입으로 바꿔준다.
  String str = sf.format(d); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  System.out.println(str);
 }
 
}

-------------------------
=======================================================

* double d = Math.random(); //난수 발생 범위(0.0 <= x < 1.0)
* java.util.Random r = new Random();
Int i = r.nextInt();//인트의 범위까지 정수형을 리턴한다.
int i1 = r.nextInt(100);//0~(100-1)까지의 숫자를 랜덤적으로 리턴한다.

package random;

import java.util.Random;

public class RandomTest {

 public static void main(String[] args) {
  Random r = new Random();
  System.out.println(r.nextInt());//int 범위에있는 모든 수를 random하게
  System.out.println(r.nextBoolean());
  System.out.println(r.nextDouble());;
  System.out.println(r.nextLong());
  int i = r.nextInt();
  while(i>=0){
   i = r.nextInt();
  }
  System.out.println(i);
  i = r.nextInt(10);//0~9까지 리턴
  while(i!=10){
   i = r.nextInt(10);
  }
  System.out.println(i);
 }

}
--------------------------------
================================================================

* 2012-3-26
* Java.math.BigDecimal - double로 표현이 안되는 부동 소숫점 표현  -> 구문 :  new (BigDecimal("10.5");
            BigInteger - long으로 표현이 안되는 정수를 표현

* project : day23
  package : number
  class : BigDecimalTest


package number;

import java.math.BigDecimal;

public class BigDecimalTest {
 public static void main(String[] args) {
  System.out.println(2.00-1.11);
  BigDecimal d1 = new BigDecimal("2.0");
  BigDecimal d2 = new BigDecimal("1.10");
  // + : add(), - : substract(), / : divide(), * : multiply()
  BigDecimal result  = d1.subtract(d2);
  double d = result.doubleValue();
  System.out.println(result +" : "+ d);
  //1 : 나눌 수, 2 : scale - 소숫점 이하 몇자리 까지보여줄것인지, 3 : 소숫점 이하 처리방식
  result = d1.divide(d2,3,BigDecimal.ROUND_CEILING);//소수점 3자리까지 나타내라.
  System.out.println("나눈 결과 : "+result);
 }
}


---------------------------------

========================================================================

* 예외 : 프로그래머가 원하지 않는 방향으로 가는 것.
* 오류 : 프로그램이 정상적으로 실행하지 못하는 상황.
  1. Error : 심각한 오류(프로그램을 멈춰야 하는 오류) - H/W적 오류
  2. Exception : mild오류(심각하지 않음 오류) - s/w적오류(실행시 정상적인흐름(programmer가 의도한 흐름)으로 가지 못한 상황.

* Exception Handling(예외처리)
- 예외가 발생되었을때 프로그램이 정상적으로 처리되도록 해주는 것.

Throwable - 오류의 최상위
^       ^
|       |
Error   Exception
           ^
           |
     ---------------
     |             |
   Runtime        나머지
   (unchecked)    (checked)

 

 

 


- Exception - unchecked 계열(Handleing(처리) : compiler가 신경쓰지 않음), checked 계열(compiler가 체크)
- unchecked : 컴파일러가 Exceoption 처리여부를 체크 않함
  발생이유 : code상의 문제 때문에 발생 (100퍼센트 실행 시 오류가 남. 코드를 수정해 주는 것이 맞음)
             compiler의 check가 불가능한 경우.
             -> 처리(Handling)보다는 code 수정

- checked 계열 Exception : 컴파일러가 Exception 처리여부를 check
                         하지 않았을 경우 컴파일 에러 발생
  발생이유 :  code상 문제가 아니라 user가 잘못 사용하였거나 실행 환경상 문제로 발생
  - 발생 확률 :  50 : 50
  -> 처리가 필요.

* 오류가 나면 그자리에서 처리 하는게 아니라 오류가 나는 곳의 상위에서 처리한다.
* throw, throws, try, catch, finally
throw :  오류를 발생시키는 것
throws, try, catch, finally : 오류를 처리하는 것.(try, catch, finally는 셋이 같이 붙어 다닌다. )
* Exception class 정의하는 법.

* Exception class 작성(교재 P537)
  1. checked :  Exception을 extends
     unchecked : RuntimeException을 extends
  2. public class
  3. no-arg 생성자
     String 인수로 받는 생성자
  4. 필요한 Attribute, 메소드를 구현.
     이름 ; ~Exception

* project : day24
  package : exception.sample
  class : ExceptionTest
          Divide
          ZeroDivideException

 


package exception.sample;

public class ExceptionTest {
 public static void main(String[] args){
 Divide d = new Divide();
 int result = 0;
 try{
  result = d.divide(10,0);
 }catch(ZeroDivideException ze){
      System.out.println("오류가 발생했습니다.");
      try {
   result = d.divide(10, 5);
  } catch (ZeroDivideException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 System.out.println("나눈 결과 : "+result);
 }
}

---------

 

package exception.sample;

public class Divide {
 
 public int divide(int num1, int num2) throws ZeroDivideException{
   //num1을 num2로 나눈 값(몫)을 return
  if(num2==0){ //예외상황
   throw new ZeroDivideException();
   
  }
  return num1/num2;
 }
}


-----------

package exception.sample;
/*
 * Exception 클래스
 * 0으로 숫자를 나눴을 때의 예외상황을 표현하기 위한 클래스
 */
public class ZeroDivideException extends Exception{
 public ZeroDivideException(){}
 public ZeroDivideException(String message){
  super(message);
 }
}


------------
==========================================================
* Exception 발생(던진다) - throw (호출해준 사람한테 예외를 던져준다.)
  구문 :  throw Throwable의 객체;

num2 = 0;

* 예외처리 : throws - 예외발생할 메소드를 호출한 caller메소드에서 처리하도록 하는 것.
             try,catch,finally - 발생한 예외를 직접처리하는 것.

 
- 메서드 구문 :  [제한자] return type 이름([매개변수들]) throws [ExceptionType, . . .]{}
ex :  public void go() throws AEception, BException{}


                 
* 메소드 overriding - 하위 class에서 부모의 메소드 재정의
        (instance 메소드)
- 규칙 - 전제; 이름동일
  1. return type, 매개변수가 동일
  2. 하위의 접근제한자가 상위 것과 같거나 더 넓어야한다.
* 3. 부모가 throws 한것만 할 수 있다.( exception )
     -> 부모에서 throws 한것 안 할 수 있다.


* Exception

     ^
     |
  --------
  |       |
AException BException
  |      
------
|    |
A1Exception A2Exception


Super

public void go() throws AE{}

Sub
public void go(){} ok
public void go() throws AE,BE{} no
public void go() throws A1E,A2E extends Super(){}  ok

- try, catch, finally - 오류처리

try{
 오류(예외)발생 가능성이 있는 코드 ->throw
                                          ->메소드 호출 -> throws

}catch(예외(오류) type 변수선언){
 처리코드;
}

* ex :
try{
 1.AE
 2.BE
 3.CE
}catch(AE a){
 4.
}catch(BE b){
 5.
}catch(CE c){
 6.
}
 7.

2. BE발생

1.->2.X->5.->7. //이렇게 이동. 만약 위에 것에 오류가 나면 아래 있는 것이 실행할 의미가 없으면 이렇게 하고, 아랫것도 실행해야 되면 try{}catch(){}를 따로 잡아줘야 한다.


*

project : day24
package : exception.trycatch
class : ExceptionTest1


package exception.trycatch;

public class ExceptionTest1 {
 public static void main(String[] args) {
  /*
   * uncheck 계열의 Exception
   * ArrayIndexOutOfBoundsException - 배열의 index 범위를 넘었을때 발생
   * NullPointerException - null값을 가진 변수의 instance멤버 호출시 발생
   * ArithmethicException - 산술 연산상 문제 발생시 발생(0으로 나눈 경우)
   */
  String str = null;
  try{
  System.out.println(str.concat("def"));//100%이므로 수정하는게 맞지만 연습용으로 try{}catch(){}를 쓴다.
  }catch(NullPointerException ne){
   System.out.println("NullPointerException 발생");
   
  }try{
  System.out.println(10/0);
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException 발생");
  }
  int[] arr = {10,20,30};
  try{
  System.out.println(arr[10]);
  }catch(ArrayIndexOutOfBoundsException arre){
   System.out.println("ArrayIndexOutOfBoundsException 발생");
  }
  System.out.println("메인메소드 종료");
 }
}


---------
============================================================================
*
package exception.trycatch;

public class ExceptionTest2 {
 public static void main(String[] args) {
  String str = null;
  try{
  str.concat("def");
  int result = 10/0;
  int arr[]= {10,20,30};
  System.out.println(arr[0]);
  
  int i = Integer.parseInt("abcde");
  }catch(NullPointerException e){
   System.out.println("NullPointerException발생");
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException발생");
  }catch(ArrayIndexOutOfBoundsException ae){
   System.out.println("ArrayIndexOutOfBoundsException발생");
  }catch(Exception e){ //모든 Exception의 상위 개념으로 위에서 잡은 것 말고는 다 여기서 잡는다.
   System.out.println("Exception e");
  }
  System.out.println("메인메소드 종료");
 }
 
}
----------------------
==========================================================================

--------------------
=============================================================================


 
* 2012-3-27

 오류                                                
          |
----------------------
|                     |
에러                 예외
심각한H/w적           S/W적

 

 Throwable
            |
--------------------------
|                         |
Error                    Exception
                          |
                   --------------------------
                   |                         |
     unchecked : RunTimeException   checked : exception(checked 는 사용자가 메뉴얼 대로 사용하지 않거나 호출이 잘못되었을 시 사용하는 exception이다.)

* 오버라이딩 규칙에 걸려서 exception을 던지지 못할 경우에는 Runtime계열의 Exception을 만들어 던진다.
ex : ABCException a = new ABCException();
     WrapperException we = new WrapperException(a);
     throw new we;

* exception은 잘못된 상황이 나오면 잘못된 상황을 표현하기 위한 class(exception)를 만들면된다.
  
* RuntimeException도 컴파일시 구문에 적어주지 않아도 에러가 나지 않지만 구문만 보고도 사용자가 Exception이 난다는 것을 알아야 하기 때문에 구문에 throws를 사용해서 나타내준다.
ex :

public void b() throws NullPointerException{

 throw new NullPointerException();
}

* 상속구조의 Exception을 잡을 시에는 하위 것부터 잡아야 한다. 왜냐하면 상위를 먼저 잡으면 상위에서 예외를 다 처리하여 하위 예외는 왜 썼냐고 물으면서 에러를 내기 때문이다.
* catch안에 아무것도 구현안해도 예외처리를 한것이기는 하나 로그를 남겨야 한다. (오류를 남겨 두지 않으면 프로그램이 아무 이상 없는 것으로 보이는데 프로그램이 실행이 안되는 경우가 생길 수 있다.)

* Exception 발생
public void addProduct()throws SameIDException{
  throw new SameIDException();
}
  메소드 호출
try{
pm.addProduct();
}catch(SameIDException se){
}


* 개발에서는 catch에 printStackTrace();를 한다.

*
try{
 예외가 날 확률이 있는 코드
}catch(  e){
 예외처리
}finally{
무조건 실행
}

----------------------------

try{ 1->4->5
1       - AE발생
2
3
}catch(AE e){
4
}
5

-----------------------------


try{
1     
2
3
}catch(AE e){
4
}finally{
5
}

예외가 없으면 1->2->3->5
1번에서 예외가 나면 1->4->5
1번에서 catch에서 잡지 않는 에러가 나면 1->5


----------------------------------
*IO
try{

 1.연결
 2.교환

}catch(){

 예외처리

}finally{

 3.연결끊기

}

----------------------------------
try : 오류날 가능성이 있는 코드-->실행코드(정상)
catch : try 블럭에서 난 오류를 처리하는 코드
finally : try와 catch의 상황과 상관 없이 무조건 실행되야 하는 코드.->실행코드(정상)

* 가능
- try{}catch(){}finally{}
- try{}finally{}
- try{}catch{}

 

* 2012-3-28

* I/O (Input/Output) - 연결하고 읽고 쓰고, 끊는다.

- 표준입출력 : 키보드로 입력받고 모니터로 출력
- 파일입출력 : 파일의 것을 읽거나 파일로 출력
- network : 네트워크로 연결되어 있는 다른 컴퓨터와 교환
- 객체 직렬화 : 기본 데이터 (프리미티브 타입+문자열)
                객체 데이터       : 읽고 쓰는 대상이 객체 일때
데이터를 저장 :  배열, ArrayList, Map, 파일, DB(select, update, delete, insert, trigger, tranjection, join)

- Stream : 데이터의 흐름(ex : 물이 흘러가는 통로)
- input : 데이터를 읽어 들이는 통
- output : 데이터를 흘려 보내는 통
* 항상 읽고 쓰는 것의 기준은 프로그램이다.


* java.io  (성격에 따라서 세가지 구분법이 있다.)
1. Input/Output 계열로 구분
2. Node/Filter  계열로 구분

3. byte/char    계열로 구분

- Node : 연결이 목적인 Stream class
연결이 목적이 있는 입출력을 위한 기능만 제공
- Filter계열 : 기존의 stream(연결)에 읽고 쓰는 기능을 추가하는 class
기능 주기가 목적이므로 연결기능은 없다.
->Node로 연결하고 Filter로 기능추가.


* I/O

try{
 1. 연결 - Node
 기능추가 - Filter
 2.I/O
}finally{
 3.연결끊기 - Filter
}

--------------------------


- byte 계열 : 1byte단위 입출력처리 하는 Stream
  binart code 입출력시 사용.
- charater 계열 :  2byte 단위 입출력 처리 Stream class
  text 입출력시 사용

 

*I/O정리
--------------------------------------------------------------------------------------------
            |           Input계열                  |  Output계열
--------------------------------------------------------------------------------------------
            | byte계열          | character계열    |  byte계열          |  character계열
--------------------------------------------------------------------------------------------
최상위class | InputStream       | Reader           | OutputStream       |  Writer
(추상)      |                   |                  |                    |              
--------------------------------------------------------------------------------------------
Node계열    | FileInputStream   | FileReader       | FileOuputStream    |  FileWriter
--------------------------------------------------------------------------------------------
Filter계열  | ObjectInputStream | BufferedReader   | ObjectOutputStream | BufferedWriter 
            |  DataInputStream  | InputStreamReder | DataOutputStream   | OuputStreamWriter
            |                   |                  |                    | PrintWriter
--------------------------------------------------------------------------------------------

* Text를 I/o할때는 BufferedReader로 읽어 들이고 PrintWriter로 써준다.

* Node 계열의 생성자의 인수 : 연결대상.
  Filter계열 생성자의 인수 :  Stream class type
                              Reader/Writer
                              InputStream/OutputStream

InputStream                      
- 1byte - read() : int ->char(1byte)
- EOF : -1

byte b[] = new byte[100];
read(byte[]) : int //int는 읽은 byte의 수를 리턴해준다. EOF를 만나면 -1을 리턴해준다.

 

Reader
- read() : int ->char(2byte)
EOF : -1

char b[] = new char[100];
read(char[]) : int //int는 읽은 글자의 수를 리턴해준다. EOF를 만나면 -1을 리턴해준다.

 

ex :

int i =in.read();
while(i!=-1){
 i=in.read();
}

//파일에 내용이 있을때까지 내용을 읽어 들어라.

* byte나 char 만 읽어 오므로 부호비트가 무조건 0이어서 -가 나올 수 없다. 그래서 EOF는 -1을 쓴다.

* close();연결끝는 메소드 , 이 메소드는 finally에 들어간다. (예외처리중)

* in.read()는 읽을게 없으면 읽을게 생길때 까지 기다린다.(멈춰있다가 읽을게 생기면 읽는다.) //I/O blocking.

* 출력
1. OutputStream
write(int) : void
인수로 받은 byte를 출력

* write(byte[]) //byte배열내의 data들을 한번에 출력, 만약 byte[10]이라면 10개의 글자를 읽어와서 한번에 출력한다.
  write(byte[], int startIndex, int length) //byte배열내의 data중 startIndex에서 length만큼의 data출력.

 
2. Writer
write(int) : void
인수로 받은 char를 출력

* EOF는 -1을 읽어서 -1을 리턴하는 것이 아니라 EOF 파일의 끝을 만나면 -1을 리턴해주는 것이다.
  write(char[])
  write(char[], int idx, int length)
  write(String)
 
*  OutputStream 와 Writer의 공통 메소드
- close(); : 연결끊기
- flush() : 버퍼를 이용하는 stream의 버퍼내 Data들을 강제출력 처리.(ex : 화장실물내리기,)//close()전에 사용해서 버퍼에 있는 것을 다 출력시킨 후에 연결을 끊어주는 경우가 많다.

* 입출력 코딩 pattern
try{
1. 연결 - Node계열의 stream으로 연결한다.
   Filter추가 - Filter계열의 Stream을 추가해 준다.
2. I/O 작업 read() - Filter로 읽고 쓴다.
            write()
}finally{
3. 연결끊기 close() - Filter를 끊으면 Node도 같이 끊어진다.
}

       Filter
*       |              Node로 연결
        |             |
    ㅡㅡ|ㅡㅡㅡㅡㅡㅡ |ㅡㅡ
p/g ----|------------------  File
    ----|------------------
    ㅡㅡ|ㅡㅡㅡㅡㅡㅡㅡㅡㅡ
        |        |
               Filter

* Node로 통로를 만들고 Filter로 통로를 확장시키고 다 사용했다 하면 Filter로 연결을 끊어 주면 Node와 Filter다 연결이 끊어진다.
* File IO - 파일과 연결해서 I/O.

FileInputStream/ FileOutputStream
(binary code를 읽음.ex: 그림)
FileReader    /  FileWriter
(byte)           (char)

(String file명)

ex :

FileWriter fw = new FileWriter("a.txt");
                                  ^
                                  |
                                상대 경로 : 나를 기준으로(<-를 실행하고 있는 class파일을 기준으로 찾아 들어간다.) ..->부모 디렉토리, .->현재 디렉토리(폴더)
                                절대 경로 : C://a.txt 파일이 있는 전체주소를 다 써준다.

* 파일을 찾을 수 없으면 FileNotFoundException을 낸다.

-------------------------------------------------------------------------

*
project : day26
package : file.io
class : FileStreamTest
 
D:\Penguins.jpg


package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   //fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   fo = new  FileOutputStream("d:\\Penguins.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
   int data = fi.read(); //1 바이트를 읽어옴
   int count = 0;
   
   long l1 = System.currentTimeMillis();
   while(data!=-1){
    fo.write(data);//출력
    data = fi.read();//입력
    count++;
   }
   long l2 = System.currentTimeMillis();
   
   System.out.println("읽은 횟수 : "+count);
   System.out.println("처리 시간 : "+(l2-l1)+"밀리초");
   System.out.println("처리 시간 : "+(l2-l1)/1000+"초");
  //3.정상적으로 끝났을 시에만 연결끊기
  //fi.close(); 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

--------------------
===============================================================


*
project : day26
package : file.io
class : FileArrayStreamTest
 
package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamArrayTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   //fo = new  FileOutputStream("d:\\Penguins2.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
     long l1 = System.currentTimeMillis();
     int count = 0;
     byte[] buff = new byte[10000];
     int length = fi.read(buff);
     while(length !=-1){
      fo.write(buff);
      length = fi.read(buff);
      count++;
     }
     long l2 = System.currentTimeMillis();
     System.out.println("반복횟 수 : "+count);
     System.out.println("걸린 시간 : "+(l2-l1)+"밀리초");
     System.out.println("걸린 시간 : "+(l2-l1)/1000+"초");   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
  
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

-----------------------------
============================================================

file - 17byte
byte[] b = new byte[5];
int i = fi.read(b);
while(i!=-1){
 fo.write(b);
 i = fi.read(b);
}

배열의 크기가 5므로 2byte까지 넣고 3byte가 남아서 파일의 크기가 커진다.

그래서 파일의 크기를 같게 해주려면

file - 17byte
byte[] b = new byte[5];
int i = fi.read(b);
while(i!=-1){
 fo.write(b,0,i);
 i = fi.read(b);
}

를 해줘야한다.

위에 꺼 수정 예제

package file.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamArrayTest {
 public static void main(String[] args) {
  FileInputStream fi = null;
  FileOutputStream fo = null;
  try {
   //1.연결
   fi = new FileInputStream("d:\\Penguins.jpg");//파일이 있다면 그림파일과 연결이 끝난 상태가 된다.
   fo = new FileOutputStream("d:\\Penguins2.jpg"); //기존 데이터 붙여쓰기
   //fo = new  FileOutputStream("d:\\Penguins2.jpg",true); //파일 이어 붙이기
   //2. I/O 작업(읽는 작업, 쓰는 작업)
     long l1 = System.currentTimeMillis();
     int count = 0;
     byte[] buff = new byte[10000];
     int length = fi.read(buff);
     while(length !=-1){
      fo.write(buff,0,length);
      length = fi.read(buff);
      count++;
     }
     long l2 = System.currentTimeMillis();
     System.out.println("반복횟 수 : "+count);
     System.out.println("걸린 시간 : "+(l2-l1)+"밀리초");
     System.out.println("걸린 시간 : "+(l2-l1)/1000+"초");   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
  
   e.printStackTrace();
  }finally{
   //3. 연결끊기
   if(fi!=null){//끝는 객체가 null이 아닌 경우에만 연결을 끊어라.(연결이 되어있는 경우만)
   try {
    fi.close();
   } catch (IOException e) {
   
    e.printStackTrace();
   } 
   }
   if(fo!=null){
    try {
     fo.close();
    } catch (IOException e) {
    
     e.printStackTrace();
    }
   }
  }
 }
}

*


--------------------------
====================================================================

*
project : day26
package : file.io.character
class : FileReaderWriterTest


package file.io.character;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriterTest {
 public static void main(String[] args) {
  FileReader fr = null;
  FileWriter fw = null;
  //d:\news.txt 읽어서 d:\news2.txt로 쓰기 - char[]
  
  try {
   fr = new FileReader("d:\\news.txt");
   fw = new FileWriter("d:\\news2.txt"); //연결할때마다 다 지우고 새로쓴다.
   //fw = new FileWriter("d:\\news2.txt",true); //연결할때 이어쓴다.
   
   char[] buff = new char[10000];
   int count = 0;
   int length = fr.read(buff);
   while(length!=-1){
    fw.write(buff,0,length); //읽은 글자 수만큼만 써라.
    length = fr.read(buff);
    count++;
   }
   System.out.println("반복횟수 : "+count);
  } catch (FileNotFoundException e) {

   e.printStackTrace();
  } catch (IOException e) {

   e.printStackTrace();
  }finally{
   if(fr!=null){ //파일연결이 실패하면 null이 들어간다. 그래서 null이 아닐시만 연결을 끊어줘야한다.
   try {
    fr.close();
   } catch (IOException e) {

    e.printStackTrace();
   }
   }
   if(fw!=null){
    try {
     fw.close();
    } catch (IOException e) {

     e.printStackTrace();
    }
   }
  }
  
 }
}

-----------------------------------
========================================================================

* 2012-3-29

- Input/Output

- Node계열(연결) / Filter계열(기능추가)

- byte계열(1byte) / character(2byte) - 언제쓰는지 질문
* a.txt
FileReader
FileWriter

* BufferedReader : Enter를 기준으로 읽어 들이는 기능.(라인단위로 받아옴)


*     char(txt)    byte(binary)
----------------------------------
I :   Reader       InputStream
O :   Writer       OutputStream

 

Node : 연결대상
Filter : InputStream

* 사용
try{
1. 연결 - Node
   Filter추가
2. 읽고쓰기
}finally{
3. close();
}


-----------------------------------------------------------------------------
==============================================================================

 

*
project : day26
package : file.io.character.filter
class : BufferReaderWriterTest


package file.io.character.filter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 

public class BufferReaderWriterTest {
 public static void main(String[] args) {
  
 
 //Filter Stream을 이용한 입출력
 //BufferedReader와 PrintWriter를 이용해 news.txt->new3.txt로 입/출력
 FileReader fr = null;
 FileWriter fw = null;
 //Filter스트림
 BufferedReader br = null; //버퍼를 이용, 라인단위로 읽는 기능
 PrintWriter pw = null; //데이터 포멧에 맞게 출력, println(), print()기능
 try {
  //1-1연결
  fr = new FileReader("d:\\news.txt");
  fw = new FileWriter("d:\\news3.txt");
  //1-2 filter 스트림 추가
  br = new BufferedReader(fr);
  //pw = new PrintWriter(fw);
  pw = new PrintWriter(fw, true);//true : auto flush - println()하면 바로 출력된다. 버퍼를 이용하지 않고(쓸때마다 출력해야 하는 경우 사용한다.ex : 채팅프로그램)
  //2 read(BufferedReader)/writer(PrintWriter)
  String str = br.readLine();//엔터를 기준으로 읽어들임(엔터는 않읽는다.)//읽은것을 String으로 리턴
  while(str!=null){ //EOF : null을 리턴
   System.out.println(str);
   pw.println(str); //버퍼에 출력할것을 담아둔다.(버퍼의 크기가 꽉차면 그 버퍼만큼은 출력해준다.)
   str = br.readLine();
  }
 // pw.flush();//버퍼의 내용을 다 출력해준다.(버퍼에 있는 데이터를 최종 출력장소로 밀어내는 메소드
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  //3 연결 끊기
  if(br!=null){
  try {
   br.close(); //버퍼를 닫으면 연결이 끊어진다.
  } catch (IOException e) {
  
   e.printStackTrace();
  }
  }
  if(pw!=null){
    pw.close();
  }
 }

 }
}
//파일에 enter가 들어가면 파일의 크기가 약간 커질수도 있다.

--------------------------------------
======================================================================================================
* byte계열
  DataInputStream   -|
                     |-Primitive Data를 입출력하는 기능제공.
  DataOutputStream  -|

int i = 1456729;

FileOutputStream fo;
fo.write(i);

* project : day27
  package : file.io.filter
  class : DataStreamTest

package file.io.filter;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamTest {
 private static String fileName = "d:\\prim.dat";
 public static void writeData(){
  DataOutputStream dos = null;
  try {
   dos = new DataOutputStream(new FileOutputStream(fileName));
   dos.writeInt(301201001);
   dos.writeBoolean(false);
   dos.writeLong(200100101010100L);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(dos!=null){
     try {
     dos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static void readData(){
  DataInputStream dis = DataInputStream();
  try {
   dis = new DataInputStream(new FileInputStream(fileName));
   int i = dis.readInt();
   boolean b = dis.readBoolean();
   long l = dis.readLong();
   System.out.println(i);
   System.out.println(b);
   System.out.println(l);
//   System.out.println(i+b+l);
   System.out.println(i+"\n"+b+"\n"+l);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(dis!=null){
    try {
     dis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
 private static DataInputStream DataInputStream() {
  // TODO Auto-generated method stub
  return null;
 }
 public static void main(String[] args) {
  writeData();//binary로 생겨서 editor로 안읽힌다.
  readData();//파일로부터 저장되어있는 값을 읽어 들인다.
 }
 
}

--------------------
==========================================================================

* 예제
Human h = new Human("홍길동",20,'B',170.9,new AddressDTO("111-222","서울특별시 송파구");
DataOutStream dos = new DataOuputStream(new FileOutputStream("human.dat");
dos.writeUTF(h.getName());
dos.writeInt(h.getAge());
dos.writeUTF(h.getAddress().getZipCode());

* ObjectInputStream   -           입력 -> 객체 역직렬화
                       |- 객체를  입출력 하기위한 기능을 제공
  ObjectOutputStream  -           출력 -> 객체 직렬화


- java.io - Serializable를 implements한 class의 객체들만 직렬화 할 수 있다. (크게 공통점이 없는 것들을 하나의 것으로 만들어 주는 것이 인터페이스다. 뒤에 able이 붙는다.)
                 

       직렬화
name = "홍길동"   --------------------> 홍길동 10 b 180
age = 10;         <--------------------
bloodType = 'b'      역직렬화
tall = 180

package : day27

 

* project : day27
  package : file.io.filter
  class : ObjectStreamTest
   PersonDTO


package file.io.filter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectStreamTest {
 private static String fileName = "d:\\person.obj";
 public static void wrtiteObject(Object obj){
  //인수로 받은 객체를 person.obj에 출력
  //ObjectOutputStream 이용. 객체를 출력 - 객체 직렬화,
  //                                            출력대상 :  instance변수의 값(attribute)
  ObjectOutputStream oos = null;
  try {
   //연결 + 필터
   oos = new ObjectOutputStream(new FileOutputStream(fileName));
   //쓰기 - writeObject(object)
   oos.writeObject(obj);
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if (oos != null) {
    try {
     oos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static Object readObject(){
  //Person.obj파일에 저장된 객체 정보를 읽어 들여 다시 객체로 만든다.
  //ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화
  //메소드 : readObject() ; Object
  ObjectInputStream ois = null;
  Object obj = null;
  //연결 + 필터
  try {
   ois = new ObjectInputStream(new FileInputStream(fileName));
   //읽기
   obj = ois.readObject();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }finally{
   if (ois != null) {
    try {
     ois.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return obj;
 }
 public static void main(String[] args) {
  AddressDTO address = new AddressDTO("111-222","서울시 송파구 가락동");
  PersonDTO p = new PersonDTO("id-111","1111","홍길동",20,address);
  wrtiteObject(p);
  Object obj = readObject();
  PersonDTO pto = (PersonDTO) obj;
  System.out.println(pto);
 }
}

-------------------
package file.io.filter;

import java.io.Serializable;

public class PersonDTO implements Serializable{
 private String id;
 private String password;
 private String name;
 private int age;
 private AddressDTO address;
 //생성자, setter/getter, toString
 public PersonDTO() {
 }
 public PersonDTO(String id, String password, String name, int age) {
  this.id = id;
  this.password = password;
  this.name = name;
  this.age = age;
 }

 public PersonDTO(String id, String password, String name, int age,
   AddressDTO address) {
  this.id = id;
  this.password = password;
  this.name = name;
  this.age = age;
  this.address = address;
 }
 public AddressDTO getAddress() {
  return address;
 }
 public void setAddress(AddressDTO address) {
  this.address = address;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return "PersonDTO [id=" + id + ", password=" + password + ", name="
    + name + ", age=" + age + ", address=" + address + "]";
 }
 
}

-----------------------
package file.io.filter;

import java.io.Serializable;

public class AddressDTO implements Serializable{
 private String zipcode;
 private String address;
 //생성자, setter/getter, toString
 public AddressDTO(String zipcode, String address) {
  this.zipcode = zipcode;
  this.address = address;
 }
 public String getZipcode() {
  return zipcode;
 }
 public void setZipcode(String zipcode) {
  this.zipcode = zipcode;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 @Override
 public String toString() {
  return "AddressDTO [zipcode=" + zipcode + ", address=" + address + "]";
 }
 
}

//결과 : PersonDTO [id=id-111, password=1111, name=홍길동, age=20, address=AddressDTO [zipcode=111-222, address=서울시 송파구 가락동]]

---------------------
================================================================================================

* transient : instance 변수에 사용하는 제한자
              직렬화 대상에서 뺀다.
              -> 보안상 이유
                 직렬화 안되는 DataType

- 직렬화 가능 DataType : primitive Type, serializable implements한 class객체


package file.io.filter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectStreamTest {
 private static String fileName = "d:\\person.obj";
 public static void wrtiteObject(Object obj){
  //인수로 받은 객체를 person.obj에 출력
  //ObjectOutputStream 이용. 객체를 출력 - 객체 직렬화,
  //                                            출력대상 :  instance변수의 값(attribute)
  ObjectOutputStream oos = null;
  try {
   //연결 + 필터
   oos = new ObjectOutputStream(new FileOutputStream(fileName));
   //쓰기 - writeObject(object)
   oos.writeObject(obj);
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if (oos != null) {
    try {
     oos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static Object readObject(){
  //Person.obj파일에 저장된 객체 정보를 읽어 들여 다시 객체로 만든다.
  //ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화
  //메소드 : readObject() ; Object
  ObjectInputStream ois = null;
  Object obj = null;
  //연결 + 필터
  try {
   ois = new ObjectInputStream(new FileInputStream(fileName));
   //읽기
   obj = ois.readObject();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }finally{
   if (ois != null) {
    try {
     ois.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return obj;
 }
 public static void main(String[] args) {
  AddressDTO address = new AddressDTO("111-222","서울시 송파구 가락동");
  PersonDTO p = new PersonDTO("id-111","1111","홍길동",20,address);
  wrtiteObject(p);
  Object obj = readObject();
  PersonDTO pto = (PersonDTO) obj;
  System.out.println(pto);
 }
}

//결과 : PersonDTO [id=id-111, password=null, name=홍길동, age=20, address=null]

-----------------
==============================================

 

* Filter - ObjectStream - 객체 읽기
  (기능)   DataStream - 데이터 읽기
           BufferedReader -라인단위 읽기
    PrintWriter - 라인단위 쓰기

* 표준 입출력 : keyboard로 부터 입력 -
                                      |-console(cmd창에서 실행)
                모니터에 출력        -

+ static out                -
                             |- PrintStream ->모니터와 연결된 Stream
         err(에러메세지출력)-
System.out.println();

+ static in -> InputStream  - input계열,                      ->키보드와 연결된 Stream(표준입력)
                              byte계열,   ->최상위(추상class)

구문 : System.in.read(); // 1byte를 읽는다.

byte계열을 char계열로 바꿔주는것 ->InputStreamReader


* project : day27
  package : file.io.stn
  class : StandardIOTest1


package file.io.stn;

import java.io.IOException;

public class StandardIOTest1 {
 public static void main(String[] args) {
  System.out.println("안녕하세요");
  System.out.print("안녕");
  System.err.println("에러메세지 입니다.");
  try {
   System.out.println((char)System.in.read());//read();는 리턴형이 int다.
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

--------
==========================================================================


* project : day27
  package : file.io.stn
  class : StandardIOTest2

package file.io.stn;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StandardIOTest2 {
 public static void main(String[] args) {
  InputStream in = System.in;
  InputStreamReader ir = new InputStreamReader(in);    //InputStream을 Reader로 바꿔준다.
  try {                                                                      //Reader계열은 char로 2바이트를 읽어 온다.
   System.out.println((char)ir.read());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

------------
========================================================================

Keybord - consoleMemo - memo.txt
        |             |
      system.in      FileWriter


* project : day27
  package : file.io.stn
  class : ConsoleMemo


package file.io.stn;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ConsoleMemo {
 public static void main(String[] args) {
  String fileName = "d:\\memo.txt";

  PrintWriter pw = null;
  String str = null;
  BufferedReader br = null;
  try {
   pw = new PrintWriter(new FileWriter(fileName));
   br = new BufferedReader(new InputStreamReader(System.in));
   str = br.readLine();
   while (!str.equals("/q")) {
    pw.println(str);
    str = br.readLine();

   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    br.close();
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }

   pw.close();

  }

 }
}


----------
========================================================================


package file.io.stn;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ConsoleMemo {
 public static void main(String[] args) {
  String fileName = "d:\\memo.txt";

  //표준입출력을 위한 선언.
  InputStream in = System.in;
  //InputStream type을 Reader type으로 바꿔준다.
  InputStreamReader ir = new InputStreamReader(in);

  PrintWriter pw = null;
  String str = null;
  BufferedReader br = null;
  try {
   pw = new PrintWriter(new FileWriter(fileName));
   br = new BufferedReader(ir);
   str = br.readLine();
   while (!str.equals("/q")) {
    pw.println(str);
    str = br.readLine();

   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    br.close();
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }

   pw.close();

  }

 }
}


-------------------------------
================================================================================================

* 2012-3-30

InputStream은 byte(1byte)용 이어서 InputStreamReader로 char(2byte)용으로 바꿔줬다.그후 Reader계열로 바뀌었기때문에 bufferedReader에 연결했다.
BufferedReader는 한라인씩 읽어 들인다.
text를 쓰는 거라서 Node를 FileWriter를 써주고 필터를 PrintWriter의 println()을 사용해서 출력해줬다.

 package file.io.stn;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ConsoleMemo {
 public static void main(String[] args) {
  BufferedReader br = null;
  PrintWriter out = null;
  try {
   //연결
   InputStreamReader ir = new InputStreamReader(System.in);
   br = new BufferedReader(ir);
   out = new PrintWriter("d:\\memo.txt");
   System.out.println("글을 입력하세요..종료하려면/q나 ctrl-z를 입력하고 enter를 누르시오 : ");
   //read/write
   String txt = br.readLine();
   while (txt != null) {
    if (txt.equals("/q")) {
     break;
    }
    out.println(txt);
    txt = br.readLine();
   }
   System.out.println("저장되었습니다.");
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   //close
   if (br != null) {
    try {
     br.close();
    } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
   }
   if (out != null) {
    out.close();
   }
  }

 }
}

//강사님 표준입출력 답

-----------------------------
========================================================================================

project :  day27
package : file.io.stn
class : PersonInfo

//DTO class만들지 않고 배열로 처리

package file.io.stn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PersonInfo {
 public static void main(String[] args) {
  String[] person = null;

  InputStreamReader ir = null;
  BufferedReader br = null;

  ArrayList<String[]> al = new ArrayList<String[]>();
  
  ir = new InputStreamReader(System.in);
  br = new BufferedReader(ir);
  try {
   while (true) {
    person = new String[3];
    System.out.println("1.입력, 2:출력, 3:종료 : ");
    String txt = br.readLine();

    if (txt.equals("1")) {
     System.out.println("이름을 입력하시오 : ");
     person[0] = br.readLine();
     System.out.println("나이를 입력하시오 : ");
     person[1] = br.readLine();
     System.out.println("주소를 입력하시오 : ");
     person[2] = br.readLine();
     al.add(person);
    } else if (txt.equals("2")) {
     for(int i=0;i<al.size();i++){
     System.out.println("이름 : " + al.get(i)[0] + " 나이 : " + al.get(i)[1] + " 주소 : "
       + al.get(i)[2]);
     }
    } else if (txt.equals("3")) {
     System.out.println("프로그램을 종료합니다.");
     return;
    }

   }
  } catch (IOException e) {
   e.printStackTrace();

  } catch (NullPointerException e) {
   e.printStackTrace();
  }finally {
   if (br != null) {
    try {
     br.close();
    } catch (IOException e) {

     e.printStackTrace();
    }
   }
  }
 }
}


------------
============================================================
project :  day27
package : file.io.stn
class : PersonInfo


package file.io.stn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PersonInfo {
 public static void main(String[] args) {
  PersonDTO person = null;
//  String[] person = null;

  InputStreamReader ir = null;
  BufferedReader br = null;

  ArrayList<PersonDTO> al = new ArrayList<PersonDTO>();

  ir = new InputStreamReader(System.in);
  br = new BufferedReader(ir);
  try {
   while (true) {
    person = new PersonDTO();
//    person = new String[3];
    System.out.println("1.입력, 2:출력, 3:종료 : ");
    String txt = br.readLine();

    if (txt.equals("1")) {
     System.out.println("이름을 입력하시오 : ");
     person.setName(br.readLine());
     System.out.println("나이를 입력하시오 : ");
     person.setAge(Integer.parseInt(br.readLine()));
     System.out.println("주소를 입력하시오 : ");
     person.setAddress(br.readLine());
     al.add(person);
    } else if (txt.equals("2")) {
     for(int i=0;i<al.size();i++){
     System.out.println(al.get(i).toString());
     }
    } else if (txt.equals("3")) {
     System.out.println("프로그램을 종료합니다.");
     return;
    }

   }
  } catch (IOException e) {
   e.printStackTrace();

  } catch (NullPointerException e) {
   e.printStackTrace();
  }finally {
   if (br != null) {
    try {
     br.close();
    } catch (IOException e) {

     e.printStackTrace();
    }
   }
  }
 }
}

-------------
package file.io.stn;

public class PersonDTO {
 private String name;
 private int age;
 private String address;
 public PersonDTO() {
 }
 public PersonDTO(String name, int age, String address) {
  this.name = name;
  this.age = age;
  this.address = address;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 @Override
 public String toString() {
  return "이름=" + name + ", 나이=" + age + ", 주소="
    + address;
 }
 
}

------------------
=========================================

//강사님 답
project :  day27
package : file.io.stn
class : PersonInfo

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PersonInfo {
 public static void main(String[] args) {
  // 연결
 
  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader in = new BufferedReader(ir);
  String name = null;
  int age = 0;
  String address = null;
  // 읽고 쓰는 작업
  while (true) {

   try {
    // 메뉴조회
    System.out.println("1:입력, 2:출력, 3:종료 : ");
    int index = Integer.parseInt(in.readLine());
    // 입력의 경우
    if (index == 1) {
     System.out.println("이름을 입력하세요 : ");
     // trim()은 좌우 공백을 띄워줌
     name = in.readLine().trim();
     if (name.equals("")) {
      System.out.println("이름은 한글자 이상 입력하세요");
      continue;
     }
     System.out.println("나이를 입력하세요 : ");
     age = Integer.parseInt(in.readLine().trim());
     System.out.println("주소를 입력하세요 : ");
     address = in.readLine().trim();
     if (address.equals("")) {
      System.out.println("주소는 한글자 이상 입력하세요 ");
      continue;
     }
    }
    //출력의 경우
    else if (index == 2) {
     System.out.println("이름 : " + name + " 나이 : " + age
       + " 주소 : " + address);
    }
    //종료의 경우
    else if (index == 3) {
     System.out.println("프로그램이 종료되었습니다.");
     in.close();
     return;
    }

   } catch (IOException e) {
    System.out.println("프로그램 오류입니다.");
   } catch (NumberFormatException e) {
    System.out.println("잘못된 입력입니다.");
   }
  }

 }
}

-------------------
=====================================================

//ArrayList로 넣기

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PersonInfo {
 public static void main(String[] args) {
  // 연결
 
  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader in = new BufferedReader(ir);
  String name = null;
  int age = 0;
  String address = null;
  ArrayList<PersonDTO> list = new ArrayList<PersonDTO>();
  // 읽고 쓰는 작업
  while (true) {

   try {
    // 메뉴조회
    System.out.println("1:입력, 2:출력, 3:종료 : ");
    int index = Integer.parseInt(in.readLine());
    // 입력의 경우
    if (index == 1) {
     System.out.println("이름을 입력하세요 : ");
     // trim()은 좌우 공백을 띄워줌
     name = in.readLine().trim();
     if (name.equals("")) {
      System.out.println("이름은 한글자 이상 입력하세요");
      continue;
     }
     System.out.println("나이를 입력하세요 : ");
     age = Integer.parseInt(in.readLine().trim());
     System.out.println("주소를 입력하세요 : ");
     address = in.readLine().trim();
     if (address.equals("")) {
      System.out.println("주소는 한글자 이상 입력하세요 ");
      continue;
     }
     PersonDTO pto = new PersonDTO(name,age,address);
     list.add(pto);
    }
    //출력의 경우
    else if (index == 2){
     
     for(PersonDTO pto : list){
      System.out.println(pto);
     }
    }
    //종료의 경우
    else if (index == 3) {
     System.out.println("프로그램이 종료되었습니다.");
     in.close();
     return;
    }

   } catch (IOException e) {
    System.out.println("프로그램 오류입니다.");
   } catch (NumberFormatException e) {
    System.out.println("잘못된 입력입니다.");
   }
  }

 }
}

-----------------------------------
========================================================================================
//파일로 출력, 리드

package test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class PersonInfo {

 private static String fileName = "d:\\person.txt";

 public static void wrtiteObject(Object obj) {
  // 인수로 받은 객체를 person.obj에 출력
  // ObjectOutputStream 이용. 객체를 출력 - 객체 직렬화,
  // 출력대상 : instance변수의 값(attribute)
  ObjectOutputStream oos = null;
  try {
   // 연결 + 필터
   oos = new ObjectOutputStream(new FileOutputStream(fileName));
   // 쓰기 - writeObject(object)
   oos.writeObject(obj);

  } catch (FileNotFoundException e) {
   System.out.println("파일이 없습니다.");
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (oos != null) {
    try {
     oos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 public static Object readObject() throws IOException{
  // Person.obj파일에 저장된 객체 정보를 읽어 들여 다시 객체로 만든다.
  // ObjectInputStream - 객체를 입력받는 메소드 : 객체 역직렬화
  // 메소드 : readObject() ; Object
  ObjectInputStream ois = null;
  Object obj = null;
  // 연결 + 필터
  try {
   ois = new ObjectInputStream(new FileInputStream(fileName));
   // 읽기
   obj = ois.readObject();
  }  catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (ois != null) {
    try {
     ois.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return obj;
 }

 public static void main(String[] args) {
  // 연결

  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader in = new BufferedReader(ir);
  String name = null;
  int age = 0;
  String address = null;
  ArrayList<PersonDTO> list = null;
  // 읽고 쓰는 작업
  // 파일이 없을경우 읽어 오지 못함.
  try{
   Object obj = readObject();
 
   list = (ArrayList) obj;
  }catch(IOException e){
   list = new ArrayList<PersonDTO>();
   
   System.out.println("파일이 없습니다.");
  }
  while (true) {

   try {
    // 메뉴조회
    System.out.println("1:입력, 2:출력, 3:종료 : ");
    int index = Integer.parseInt(in.readLine());
    // 입력의 경우
    if (index == 1) {
     System.out.println("이름을 입력하세요 : ");
     // trim()은 좌우 공백을 띄워줌
     name = in.readLine().trim();
     if (name.equals("")) {
      System.out.println("이름은 한글자 이상 입력하세요");
      continue;
     }
     System.out.println("나이를 입력하세요 : ");
     age = Integer.parseInt(in.readLine().trim());
     System.out.println("주소를 입력하세요 : ");
     address = in.readLine().trim();
     if (address.equals("")) {
      System.out.println("주소는 한글자 이상 입력하세요 ");
      continue;
     }
     PersonDTO pto1 = new PersonDTO(name, age, address);
     list.add(pto1);
    }
    // 출력의 경우
    else if (index == 2) {

     for (PersonDTO pto1 : list) {
      System.out.println(pto1);
     }
    }
    // 종료의 경우
    else if (index == 3) {
     System.out.println("프로그램이 종료되었습니다.");
     wrtiteObject(list);
     in.close();

     return;
    }

   } catch (IOException e) {
    System.out.println("프로그램 오류입니다.");
   } catch (NumberFormatException e) {
    System.out.println("잘못된 입력입니다.");
   }

  }

 }

}

---------------

package test;

import java.io.Serializable;

public class PersonDTO  implements Serializable{
 private String name;
 private int age;
 private String address;
 public PersonDTO() {
 }
 public PersonDTO(String name, int age, String address) {
  this.name = name;
  this.age = age;
  this.address = address;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 @Override
 public String toString() {
  return "이름=" + name + ", 나이=" + age + ", 주소="
    + address;
 }
 
}


--------------
===========================================================================================================


* java.io.File.file/directory를 조회, 조작하는 class
생성자 :  ("directory+file");

* project : day27
  package : file.io.file
  class : FileTest


package file.io.file;

import java.io.File;
import java.io.IOException;

public class FileTest {
 public static void main(String[] args) {
  File file = new File("D:\\temp\\TestImport.java");// path(directory+file
  // File file = new File("D\\temp","TestImport.java");//parent, child
  // 조회
  System.out.println("파일의 경로(path) : " + file.getPath());
  System.out.println("파일의 parent : " + file.getParent());
  System.out.println("파일의 child : " + file.getName());
  System.out.println("존재여부 : " + file.exists());
  System.out.println("파일인지 조회 : " + file.isFile()); // true면 파일이다.
  System.out.println("디렉토리인지 조회 :  " + file.isDirectory());
  System.out.println("읽을 수 있는 파일인가? : " + file.canRead());
  System.out.println("쓸 수 있는 파일인가? : " + file.canWrite());
  System.out.println("실행할 수 있는 파일인가? : " + file.canExecute());
  System.out.println("파일의 크기 : " + file.length() + "byte");
  System.out.println("파일의 마지막 수정 시간 : " + file.lastModified());// 1970년1월1일부터
                  // 수정했을
                  // 시까지
                  // 밀리
                  // 세컨드로
                  // 계산해준다.//그레고리안
                  // 켈린더
                  // 객체
                  // 생성시file.lastModified()를
                  // 넣고
                  // 실행하라.

  File dir = new File("D:\\temp");// directory
  boolean flag = dir.isDirectory();
  System.out.println("디렉토리 여부 : " + flag);
  if (flag) {
   String[] list = dir.list();// 디렉토리 내의 sub 디렉토리, 파일 명을 String[]로 리턴
   for (String str : list) {
    System.out.println(str);
   }
  }
  // 조작(변경, 생성)
  // 디렉토리 생성
  flag = dir.mkdir();// 생성을 성공 - true
  System.out.println("디렉토리 생성여부 :  " + flag);

  System.out.println(new File("d:\\abcde").mkdir());
  File file2 = new File("d:\\oldFile.txt");
  // 파일 생성
  try {
   flag = file2.createNewFile();
  } catch (IOException e) {

   e.printStackTrace();
  }
  System.out.println("파일 생성 여부 : "+flag);
//  renameTo(File 변경할 파일)//파일 변경, 파일 이동
  File file3 = new File("d:\\temp\\oldFile2.txt");
  flag = file2.renameTo(file3);
  System.out.println(flag);
 }
}

----------------------------------------------------------
=================================================================================================

* java.util.Properties

- setProperty(String k , String v)
- getProperrty(String k) : String v

- 키값만 리턴 : propertyNames() : Enumeration (키값을 하나씩 가져옴)

Enumeration은 Iterator의 옛날 버전이다.
Enumeration -> hasMoreElements()와 nextElemet()로 데이터를 뽑아낸다.
Iterator -> hasNext()와 next()로 데이터를 뽑아낸다.

- load(Input계열 Stream)
- store(output계열 Stream, String comment(주석))


* project : day27
  package : file.io
  class : PropertiesTest


package file.io;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesTest {
 public static void main(String[] args) throws Exception {
  //storeProperties();
  loadProperties();
  
 }
 public static void loadProperties() throws Exception{
  //file에 저장된 key=value 값들을 읽어 Properties객체에 저장
  FileReader fr = new FileReader("d:\\temp\\person.properties");
  Properties props = new Properties();//비어있는 map객체 생성
  props.load(fr);   //Properties 객체와 FileReader연결해서 파일을 읽어옴
  Enumeration enu = props.propertyNames();//KEY값들을 조회
  while(enu.hasMoreElements()){          //데이터가 있을때까지 돈다.
   String key = (String) enu.nextElement(); //key값을 뽑아옴
   String value = props.getProperty(key);    //value값을 뽑아옴
   System.out.println(key+" - "+value);      //key - value 출력
  }
  
 }
 public static void storeProperties() throws Exception{//실행 흐름만 확인하기 위해 우선은 예외를 던진다.
  //Properties 객체에 저장된 내용을 file에 출력
  Properties props = new Properties();//비어있는 map객체 생성
  props.setProperty("id", "id-111"); //map에서 put과 같은 역할
  props.setProperty("name", "홍길동");
  props.setProperty("age", "20");
  props.setProperty("address", "서울시");
  FileWriter fw = new FileWriter("d:\\temp\\person.properties");
  props.store(fw,"person info코덕");//"person info"저장하려는 데이터의 주석 //한글로 넣게 되면 unicode로 나온다. //추석을 달아주고 객체의 내용을 파일에 찍어줌.
 }
}

//Store보다는 load가 더 많이 쓰인다.
//설정적보를 파일에 저장해 두고 파일을 읽어 들인다.
//프로그램은 바꿀 필요없이 파일의 내용만 변경해서 읽어 들여서 사용할때 사용된다.
//프로그램에서 사용할 문자열들을 외부에 저장해 놓고 프로그램의 변경없이 사용할때 Properties를 사용한다.
--------------------------------------------

===============================================================================================

* 2012-4-2
내가 정리

* network Programming 

- 연결 ->  network으로 I/O를 가져옴 -> close(연결해제)

- server
자원을 보유하여 client에게 자원을 제공하는 H/W 또는 S/W

- client
server에서 자원을 제공받아 사용하는 H/W 또는 S/W

client        -      서버(소식, 뉴스)
(서버로부터 내용을 받는다)

 


- client ---2.요청---> 서버
         ---1.연결--->
         <--3.응답----


- Protocal : client와 서버간에 통신하기 위한 통신규약
(ex : HTTP, FTP,
- IP주소 : 네트웍을 통한 컴퓨터로 찾아가기 위한 주소.
- Port번호 :  한 컴퓨터에서 제공하는 서버프로그램을 구분하기 위한 번호
(하드웨어 적으로 접근한 후에 S/W적으로 접근하는 것.)

----------------------------------------------------------------
강사님 말씀
* Network Programing : Network으로 연결된 computer들이 Data를 읽고 쓰기 위한 Program작성
-> Java.net패키지의 api 이용
- Protocil : 통신규약 - 서버와 client가 Data를 요청/응답하기 위한 규약. ex) TCP, HTTP
- TCP : 연결지향 protocol. HTTP, FTP등의 기반 protocol
  특징 :  신뢰적, 쌍방향성.

- IP주소 : 인터넷에 연결된 컴퓨터들을 구별하기 위한 4byte 형태의 주소.
           모든 computer들은 유일한 주소를 부여 받는다.
           ->IP주소를 통해 연결되 있는 컴퓨터에 접근
(주소 :  장소를 찾아가기 위한 사람에게 필요한 장소의 정보)
- 프로세스 :  실행중인 프로그램
- Port번호 :  컴퓨터 내의 서버 Program 들을 구분하기 위한 번호.
       0~65535 사이의 번호를 가진다.
       0~1023은 예약된 번호로 사용하지 않는 것이 좋다.


- Socket통신
  -> Socket : 서버와 client의 연결점

* client단 Programming pattern

try{
 1. 소켓 생성 -> Socket
    -> 서버와 연결
    -> 생성자로(IP와 포트번호)를 알려줌. new Socket("ip",port:int) //이렇게 생성해주면 서버단 network와 연결된 거다.

 2. InputStream/OutputStream을 Socket으로 부터 조회.
    소켓객체.getInputStream() : InputStream /소켓객체.getOutputStream() : OutputStream -> byte계열
 3. I/O작업
    -> Filter Stream 추가.
    -> Read, write작엊
}finally{
 4. 연결끊기(I/O close(), Socket close())
}

 

* 서버단 program 패턴
- ServerSocket : Socket을 만들어 주소 객체
                 ->client 연결을 기다리다 연결이 들어오면 Socket객체 생성.
1. ServerSocket 생성 -> protNuo
2. client요청 기다리기 ServerSocket.accept();
3. Socket 객체를 통해 InputStream/OutputStream조회
4. I/O작업
5. 연결 close()
I/O close(), Socket Close()


*
Project : day29
package : network.simple1.client
class : SimpleClient
 
pakage : network.simple1.server
class : SimpleServer


package network.simple1.server;
//import : java.net.java.io
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer {
 public static void main(String[] args) {
  /*
   * 서버단 프로그램 작성
   */
  ServerSocket serverSocket = null;
  Socket socket = null;
  PrintWriter out = null;
  //1. ServerSocket 객체 생성 - 생성자 인수 : port 번호 -0~65535
  try {//생성자가 throws Exception처리 되어 있기때문에, 예외처리 잡아주지 않으면 컴파일 에러가 나므로 잡아준다.
   System.out.println("----클라이언트의 연결을 기다립니다.----");
   serverSocket = new ServerSocket(5555);//서버에 접근하려면 5555번 port로 접근해라.
   socket = serverSocket.accept();//소켓 연결 //클라이언트의 연결을 기다리고 있는다.
      System.out.println("----클라이언트가 연결되었습니다.----");
      //2.IO작업
      //IO Stream객체를 소켓으로 부터 조회
      OutputStream os = socket.getOutputStream();
      //Filter추가
      out = new PrintWriter(os);//FileName, Output등등 받아서 다 출력시킨다. 자체가 연결 스트림은 아니다. 필터
      //읽고/쓰는 작업 처리
      out.println("아는척하지 말고 빨리돌아와 ㅋㅋ");
     
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   //3.연결닫기
   //Stream 연결 닫기
   if(out!=null){
    out.close();
   }
   //소켓 연결 닫기
   if(socket!=null){
    try {
     socket.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
}
//JVM_Bind 에러가 나면 이미 사용중인 포트번호로 포트번호를 바꿔주던가 그 포트를 꺼줘야한다.


----------------

package network.simple1.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleClient {
 public static void main(String[] args) {
  //클라이언트단 프로그램
  Socket socket = null;
  BufferedReader br = null;
  //1. Socket 객체 생성 - 연결 끝 :  생성자 인수 - ip, port
  try {
   socket = new Socket("192.168.0.9",5555);//127.0.0.1 로콜호스트의 IP(자신의 컴퓨터 내부 IP) //이렇게 클라이언트단에서 소켓을 생성해주면 서버단과 연결된다.
   //2.Stream 조회
   InputStream in = socket.getInputStream();
   //IO작업 - filter추가
   br = new BufferedReader(new InputStreamReader(in));
   //읽고/쓰기 작업
   String str = br.readLine();
   System.out.println("서버로 부터 읽은 글 : "+str);
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally{
   //3.연결 닫기
   //Stream 닫기
   if(br!=null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   //Socket 닫기
   if(socket!=null){
    try {
     socket.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
}


-------------
===========================================================================


*
Project : day29
package : network.simple1_1.client
class : SimpleFileClient
 
pakage : network.simple1_1.server
class : SimpleFileServer

 

 

package network.simple1.client;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleClientTeacher {
 //서버에서 보내온 파일을 d:\\temp\\koala2.jpg파일로 출력
 public static void main(String[] args) {
  Socket socket = null;
  InputStream in = null;
  FileOutputStream fos = null;
  try {
   socket = new Socket("127.0.0.1",5500);
   in = socket.getInputStream();
   fos = new FileOutputStream("d:\\temp\\koala2.jpg");
   byte[] buff = new byte[1024];
   int cnt = in.read(buff);
   while(cnt!=-1){
    fos.write(buff,0,cnt);
    cnt = in.read(buff);
   }
   System.out.println("서버로 부터 파일을 모두 읽었습니다.");
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{

   if(fos!=null){
    try {
     fos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(in!=null){
    try {
     in.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(socket!=null){
    try {
     socket.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
    
 }
}


----------

package network.simple1.server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServerTeacher {
 //d:\\temp\\koala.jpg을 읽어서 연결된 클라이언트에 전송
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  FileInputStream fis = null;
  OutputStream os = null;
  //서버 소켓 생성
  try {
   serverSocket = new ServerSocket(5500);
  } catch (IOException e) {
   e.printStackTrace();
  }
  while(true){
   try {
    //클라이언트 연결 기다리기
    System.out.println("클라이언트 연결 대기");
    socket = serverSocket.accept();
    //IO작업 - OutputStream(client와 연결)
    os = socket.getOutputStream();
    fis = new FileInputStream("d:\\temp\\koala.jpg");
    byte[] buff = new byte[1024];
    int cnt = fis.read(buff);
    while(cnt !=-1){
     os.write(buff, 0, cnt);
     cnt = fis.read(buff);
    }
    System.out.println("파일 전송 완료");
   } catch (IOException e) {
    e.printStackTrace();
   }finally{
    //연결 닫기
    if(fis!=null){
     try {
      fis.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
    if(os!=null){
     try {
      os.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
    if(socket!=null){
     try {
      socket.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
    
   }
   
  }//end of while
  
 }
}


----------------------------------------
=======================================================================================


package test;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {
 public static void main(String[] args) {
  Socket socket = null;
  InputStream inputStream = null;
  FileOutputStream fileOutputStream = null;
  
  BufferedReader bufferedReader = null;
  OutputStream outputStream = null;
  try {
   
   socket = new Socket("127.0.0.1", 5558);

   bufferedReader = new BufferedReader(new InputStreamReader(System.in));
   String str = bufferedReader.readLine();
   outputStream = socket.getOutputStream();
   PrintWriter printWriter = new PrintWriter(outputStream);
   printWriter.println(str);
   printWriter.flush();
   
   fileOutputStream = new FileOutputStream("d:\\temp\\kokokokoala.jpg");
   inputStream = socket.getInputStream();
   
   byte[] buff = new byte[1024];
   int cnt = inputStream.read(buff);
   while(cnt!=-1){
    fileOutputStream.write(buff);
    cnt = inputStream.read(buff, 0, cnt);
   }
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    fileOutputStream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   try {
    socket.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 
 }
}

-----------------------------------------------

package test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class server {
 public static void main(String[] args) {
  Socket socket = null;
  ServerSocket serverSocket = null;
  FileInputStream fileInputStream = null;
  OutputStream outputStream = null;
  BufferedReader bufferedReader = null;
  
  InputStream inputStream = null;
  try {
   serverSocket = new ServerSocket(5558);
   socket = serverSocket.accept();
   
   inputStream = socket.getInputStream();
   bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   String str = bufferedReader.readLine();
   
   fileInputStream = new FileInputStream("d:\\temp\\"+str+".jpg");
   
   outputStream = socket.getOutputStream();

   byte[] buff  = new byte[1024];
   int cnt = fileInputStream.read(buff);
   while(cnt !=-1){
    outputStream.write(buff, 0, cnt);
    cnt = fileInputStream.read(buff);
   }
   

  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally{
   if(fileInputStream!=null){
   try {
    fileInputStream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   }
   if(socket!=null){
    try {
     socket.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
    }
  }
 }
}

------------------------------------
====================================================================================

 


* 2012-4-3

project : day30
package : network.simple.client
class : SimpleClient

package : network.simple.server
class : SimpleServer

package network.simple2.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleClient {
 public static void main(String[] args) {
  Socket socket = null;
  InputStream inputStream = null;
  BufferedReader bufferedReader = null;

  OutputStream outputStream = null;

  try {
   // 서버로 부터 받기
   socket = new Socket("127.0.0.1", 5555);
   inputStream = socket.getInputStream();
   bufferedReader = new BufferedReader(new InputStreamReader(
     inputStream));
   String str = bufferedReader.readLine();
   System.out.println(str);

   // 서버로 글 보내기
   outputStream = socket.getOutputStream();
   PrintWriter printWriter = new PrintWriter(outputStream);
   printWriter.println(str);
   printWriter.flush();
   System.out.println("전송완료");
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (bufferedReader != null) {
    try {

     bufferedReader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (outputStream != null) {
    try {

     outputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (socket != null) {
    try {

     socket.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

}

------------------------

package network.simple2.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import network.util.NetworkUtil;

public class SimpleServer {
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  PrintWriter out = null;
  BufferedReader br = null;
  //1. ServerSocket 객체 생성 - 생성자 인수 : port 번호 - 0~65535
  try {
   serverSocket = new ServerSocket(5555);
  } catch (IOException e1) {   
   e1.printStackTrace();
   return;
  }
  while(true){
   try {
    System.out.println("---클라이언트의 연결을 기다립니다.---");
    socket = serverSocket.accept();//클라이언트의 연결을 기다린다.
    System.out.println("---클라이언트가 연결되었습니다.----");
    //2. IO작업
    //IO Stream객체를 소켓으로 부터 조회
    InputStream in = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    //Filter 추가
    br = new BufferedReader(new InputStreamReader(in));
    out = new PrintWriter(os, true);
    //읽고/쓰는 작업처리
    String str = br.readLine();
    System.out.println("클라이언트로 부터 읽은 글 : "+str);
    out.println(str);
    
   } catch (IOException e) {
    e.printStackTrace();
   }  finally{
    NetworkUtil.close(br);
    NetworkUtil.close(out);    
    NetworkUtil.close(socket);
   }
  }//end of while
 }
}


--------------------
=====================================================
//클라이언트에서 입력하고 서버에서는 클라이언트에서 넘어온값을 계속 다시 클라이언트에 보내줘서 화면에 찍기


package network.simple.server.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import network.util.NetworkUtil.NetworkUtil;

public class SimpleServer {
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  PrintWriter out = null;
  BufferedReader br = null;
  // 1. ServerSocket 객체 생성 - 생성자 인수 : port 번호 - 0~65535
  try {
   serverSocket = new ServerSocket(5555);
  } catch (IOException e1) {
   e1.printStackTrace();
   return;
  }
  while (true) {
   try {
    System.out.println("---클라이언트의 연결을 기다립니다.---");
    socket = serverSocket.accept();// 클라이언트의 연결을 기다린다.
    System.out.println("---클라이언트가 연결되었습니다.----");
    // 2. IO작업
    // IO Stream객체를 소켓으로 부터 조회
    InputStream in = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    // Filter 추가
    br = new BufferedReader(new InputStreamReader(in));
    out = new PrintWriter(os, true);
    // 읽고/쓰는 작업처리
    String str = br.readLine();
    while (str != null) {
    // System.out.println("클라이언트로 부터 읽은 글 : " + str);
     out.println(str);
     str = br.readLine();
    }
   } catch (IOException e) {
    e.printStackTrace();
   } finally {
    NetworkUtil.close(br);
    NetworkUtil.close(out);
    NetworkUtil.close(socket);
   }
  }// end of while
 }
}


-------------------------

package network.simple.server.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import network.util.NetworkUtil.NetworkUtil;

public class SimpleClient {
 public static void main(String[] args) {
  // 클라이언트단 프로그램
  Socket socket = null;
  BufferedReader br = null;
  BufferedReader printBr = null;
  PrintWriter out = null;
  // 1. Socket객체 생성 - 연결 끝 : 생성자 인수 - ip, port
  try {
   socket = new Socket("127.0.0.1", 5555);
   // 2. Stream 조회
   OutputStream os = socket.getOutputStream();
   InputStream in = socket.getInputStream();

   // IO작업 - filter 추가
   out = new PrintWriter(os, true);
   br = new BufferedReader(new InputStreamReader(in));
   printBr = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("입력 : ");
   String str = printBr.readLine();
   // 읽고/쓰기 작업
   while (str != null) {
    out.println(str);
    // out.flush();
    str = br.readLine();
    System.out.println("서버로 부터 읽은 글 : " + str);
    System.out.print("입력 : ");
    str = printBr.readLine();
   }
   System.out.println("클라이언트 종료");
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   NetworkUtil.close(out);
   NetworkUtil.close(br);
   NetworkUtil.close(socket);
  }
 }
}


-----------
=======================================================================================


* 멀티쓰레드 프로그래밍

- 쓰레드 : 순차적으로 일을 수행해 나가는 흐름(쓰레드를 virture CPU(가상의 CPU)라고도 부른다.)
           경량 Context라고도 부른다(실행하는데 코드랑 데이터는 없고 흐름만 있어서 가볍기 때문에 경량 Context라고도 부른다.)
(ex :

밥먹는다.
TV본다.
대화한다.

순차적으로 일어난다.

* 멀티 쓰레드  :  실행되는 흐름이 동시에 일어나는 것.(한사람이서 여러가지 일을 동시에 수행하는것)

* process(프로세스) : 실행 중인 프로그램 , Data, 코드, Thread(대표 쓰레드 : main)

- Thread : 프로세스내의 실행 흐름
- 멀티-쓰레딩(Multi Threading) : 한 프로세스에서 동시에 여러 쓰레드가 실행되는 것.
  ->쓰레드들은 프로세스의 Data와 코드를 공유한다.(쓰레드의 장점이자 단점이다)
    (쓰레드 단위로 띄우면 Data와 코드는 하나만 써서 Data를 절약할 수 있다. )
- 쓰레드의 단점 : 동시에 데이터를 관리 하다 보니 데이터가 깨질 수 있다. (ex :  100만원이 있었는데 한사람이 60 만원을 빼갔는데 다른 한사람은 100만원이 있다고 생각해서 50만원을 빼려는데 40만원 밖에 남지 않아서 오류가 나는 것)

             -----------------
CPU----------Thread|data|Code |
             -----------------


* CPU는 동시에 일을 처리 하지 못한다. 대신 일을 무진장 빨리 처리 할 수 있다. 일을 한번에 하나만 처리한다.


         시간

 ---------|--------------->저장
          |
 ---------|---------------------------->print
          |
----------|--------------------->글작성
          |

* 멀티쓰레드(쓰레드가 실행흐름 밖에 없어서 이동성이 빨라 동시에 수행하는 것처럼 보인다.) : 이렇게 한 시점에서 3개가 수행되는 것 처럼 보이지만 수행이 빨리 될 뿐 한 시점에서는 하나만 수행되고 동시에 일하는 것 처럼 보이는 것이다.


* 멀티쓰레드 : 대기중인 프로그램들을 순차적으로 OS가 실행시킨다.
- Multi-Threding 스케쥴링 - 시분할 방식.  - 대기중인 Thread들이 동일한 시간만큼 돌아가면서 일하는 방식.
                          - 우선순위 방식 - 대기중인 Thread들에 우선순위를 부여하여 우선순위 순서대로 처리하는 방식.
                         
* JAVA프로그램의 OS는 JVM이다.JVM은 Thread를 우선순위 방식으로 스케쥴링한다.

* java.lang.Thread - 에 쓰레드가 해야 하는 것은 다 정의 되어 있다.
  Thread coding : 1. Thread class를 상속
         public void run()를 overriding <- Business Logic
      2. java.lang.Runnable를 implements(구현)
       public  void run()을 overriding

1. Thread를 extends
   public class MyThread extends Thread{
 public void run(){
  실행흐름
 }
}
 
실행.main(){
MyThread t = new MyThread();
t.run();(X)
t.start();(O)
}


2. public class MyThread implements Runnable{
 public void run(){
  실행흐름
 }
   }

실행
main(){
MyThread nt = new MyThread();
 nt.start();(X)
 Thread t = new Thread(nt);
 t.start();(O)
}

//Thread를 상속을 받았을 때는 다른 클래스를 상속받을 수 없지만 implements를 받으면 여러개의 interface를 받을 수 있기 때문에 좋다.
//Thread말고 다른거 상속을 받기 위해서는 Runnable을 implements 해라.

* 2012-4-4

프로세스
   |
실행중인 프로그램
코드/Data          ----------   쓰레드 : 실행흐름

- 멀티쓰레드 : 한 프로그램 내에 여러개의 쓰레드가 동시에 작업하는 것.
- 한 프로그램에 데이터와 코드가 있는데 더 이상 데이터와 코드를 만들어 넣지 않고 여러개의 쓰레드(실행흐름)을 만들어 제어할 수 있다.
- 멀티쓰레드로 코드는 관계 없지만 데이터는 여러개의 쓰레드가 접근해서 관리하기 때문에 데이터의 일관성이 깨져버릴 수 있다.
(데이터의 일관성을 깨는 것을 프로그램으로 해결할 수 있다.)
- 프로세스 : 데이터 + 코드 + 실행흐름(쓰레드)

웹브라우저는 실행 시킬 수 있다.
1. 프로세스 단위 : 한 프로그램에서 프로세스 5개를 실행시키면 데이터+코드+실행흐름이 각각 5개가 생긴다.
2. 쓰레드 단위 : 한 프로그램에서 쓰레드 단위로 5개 실행시키면 처음 데이터+코드+실행흐름이 생기고 4개의 쓰레드만 더 생긴다. (코드와 데이터가 한번만 띄울 수 있다 (자원절약)는 장점이 있다.)

-쓰레드는 실행하는 애들이 아니라 대기하는 것이다. start()를 쓰게 되면 하나는 실행이 되되 나머지는 기다린다.
동시에 시작되는 것은 아니고 워낙 빨리 처리하다보니 그렇게 보이는 것이지 한번에 하나의 실행만한다.

- 시분할 방식 :  시간을 분할하여 돌아가면서 쓰는 것. (라운드 로빙 : 돌아가면서 사용)
- 우선순위 방식 :  우선순위를 정해놓고, 중요한 것 부터 처리하는 것. <- JVM은 우선순위 방식을 사용한다.

 

* Garbage Collection :  참조가 끊긴 필요 없는 객체를 JVM이 알아서 지워줌.

- 쓰레드를 사용할 시기 : 동시에 여러개의 프로세스가 진행되야 할때 사용한다. 서버는 accept()하게 기다리고 클라이언트와 연결해서 하는 작업이 있는데 두명이 접속하면 에러가나는데 이때 쓰레드를 사용하면 된다. (이것도 하고 저것도 해야할 때)

* 쓰레드 사용법

1. Thread class를 extends           -
                                     |- run() overriding
2. Runnable Interface를 implements  -
   -> 클래스를 만들때 쓰레드외의 여러개의 class를 상속 받아야 할 경우 사용한다.

-------------------------------------
*
project : day31
package : thread.basic
class : ThreadTest1


package thread.basic;

public class ThreadTest1 {
 public static void main(String[] args) {
//  A~Z
//  a~z
//  1~30

  for(int i = 65; i< (65+26); i++){
   System.out.println((char)i);
  }
  for(int i = 97; i< (97+26); i++){
   System.out.println((char)i);
  }
  for(int i = 1; i <= 30;i++){
   System.out.println(i);
  }
 }
}

------------------------
========================================
* //독립된 흐름으로 쓰레드를 부를때
project : day31
package : thread.basic
class : ThreadTest1

class : PrintAtoZThread
class : PrintAtoZLowThread (97~123)
class : Print1to30Thread

package thread.basic;

public class ThreadTest1 {
 public static void main(String[] args) {
//  A~Z
//  a~z
//  1~30
  PrintAtoZThread printAtoZThread = new PrintAtoZThread();
  PrintAtoZLowThread printAtoZLowThread = new PrintAtoZLowThread();
  Print1to30Thread print1to30Thread = new Print1to30Thread();
 
  printAtoZThread.start();
  printAtoZLowThread.start(); 
  print1to30Thread.start();

 }
}

--------------
===============================================


* //순차적인 흐름으로 부를때
project : day31
package : thread.basic
class : ThreadTest1

class : PrintAtoZThread
class : PrintAtoZLowThread (97~123)
class : Print1to30Thread

package thread.basic;

public class ThreadTest1 {
 public static void main(String[] args) {
//  A~Z
//  a~z
//  1~30
  PrintAtoZThread printAtoZThread = new PrintAtoZThread();
  PrintAtoZLowThread printAtoZLowThread = new PrintAtoZLowThread();
  Print1to30Thread print1to30Thread = new Print1to30Thread();
 
  printAtoZThread.run();
  printAtoZLowThread.run(); 
  print1to30Thread.run();
  
  System.out.println("main종료");
 }
}

----------------------------
============================================================
*
new MyThread()
    |
   start()
    |          JVM스케쥴러        run()종료
   Runnable   -------->     run() ---------> Dead(종료)
   실행대기   <--------           stop()
               Running실행

- run()는 기존의 실행흐름으로 실행이 되고, start()를 사용해야 쓰레드가 작동이 된다.

*

project : day31
package : thread.basic.runnable
class : ThreadTest
 Print1To99
        Print100To900Thread


package thread.basic.runnable;

public class ThreadTest {
 public static void main(String[] args) {
  Print100To900Thread print100To900Thread = new Print100To900Thread();
  Print1To99 print1To99 = new Print1To99();
  //쓰레드에 담기
  Thread t1 = new Thread(print100To900Thread);
  Thread t2 = new Thread(print1To99);
  
  t1.start();
  t2.start();
  System.out.println("메인 종료");
 }
}

--------------
===========================================

* Thread.sleep(int 밀리초) : 실행중인 쓰레드를 밀리초 동안 멈추게 한다. 밀리초 : 1/1000 초

  -> Blocked 상태가 된다.

* thread객체.join() : 특정 thread가 Dead(완료)될때까지 실행 중인 thread를 멈춘다.
  -> Blocked 상태가 된다.

* t1
        
 |

        t2.join()

        t1이 t2가 끝나야 살아난다.

*
new Mytread();
       ------------------------------------ blocked(멈춤)
    |  |   (blocked event해제)             ^ (blocked event
    |  |                                   |  sleep(),join()
    |  |                                   |  I/O blocking 
    |  |start()                            |
       V  JVM스케쥴러                      |         run()종료
Runnable -------------Running실행----------------------------Dead(종료)
(대기)                                    |
                                          |
       V
                                          t.sleep()
                                          t.join()


*
project : day31
package : thread.basic.runnable
class : ThreadSleepTest
 GoThread
        ComeThread

package thread.sleep;

public class ThreadSleepTest {
 public static void main(String[] args) {
  GoThread t1 = new GoThread();
  ComeThread t2 = new ComeThread();
  t1.start();
  t2.start();
  System.out.println("main종료");
 }
}


---------------
package thread.sleep;

public class GoThread extends Thread{
 public void run(){
  for(int i = 0;i<10;i++){
   System.out.println("GoThread : "+i);
   try {
    Thread.sleep(2000);
   } catch (InterruptedException e) {//1초 동안 멈추려는데 그 중간에 깨우면 예외오류가 난다.
    e.printStackTrace();
   }
  }
 }
}

--------------
package thread.sleep;

public class ComeThread extends Thread{
 public void run(){
  for(int i = 0;i<10;i++){
   System.out.println("ComeThread : "+i);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }   
  }
 }
}

----------------
================================================================

*
project : day31
package : thread.sleep.file
class : ThreadTest
 MakeFileThread
        MoveFileThread

package thread.sleep.file;

public class TreadTest {
 public static void main(String[] args) {
  MakeFileThread t1 = new MakeFileThread();
  MoveFileThread t2 = new MoveFileThread();
  t1.start();
  t2.start();
 }
}

------------------

package thread.sleep.file;

import java.io.File;
import java.io.IOException;

public class MakeFileThread extends Thread {
 // 매 1초당 하나의 파일 생성 1분동안 - 파일 : kosta.1,kosta.2... 디렉토리는 아무거나 선택
 // java.io.File
 public void run() {
   //디렉토리가 없으면 만들어라.
  File dir = new File("d:\\new_file");
  if(!dir.exists()){ dir.mkdir(); }
  for (int i = 1; i <= 60; i++) {
   // 생성할 파일 객체 생성
   File file = new File("d:\\new_file\\kosta" + i + ".txt");
   
   
   
   // 파일 생성하기
   try {
    file.createNewFile();
    System.out.println("kosta"+i+".txt");
   } catch (IOException e2) {
    e2.printStackTrace();
   }
   try {
    // 1초간 멈추기
    Thread.sleep(1000);
   } catch (InterruptedException e1) {
    e1.printStackTrace();
   }
  }
 }
}

--------------

package thread.sleep.file;

import java.io.File;

public class MoveFileThread extends Thread {
 // MakeFileThread에서 만든 파일을 다른 경로로 이동 - 매 20 초당 한번씩 - 1분 동안
 //java.io.f
 public void run() {

  File dir = new File("d:\\copyFile");
  if (!dir.exists()) {
   dir.mkdir();
  }
  for (int i = 1; i <= 3; i++) {

   // 20초간 지연된 시간동안에 파일 이동시키기
   for (int j = 1; j <= 60; j++) {

    File file = new File("d:\\new_file", "kosta" + j + ".txt");
    File copyFile = new File("d:\\copyFile", "kosta" + j + ".txt");
    file.renameTo(copyFile);

   }
   // 20초간 지연시키기
   try {
    Thread.sleep(20000);

   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("파일이 이동되었습니다.");
  }
 }
}

-----------
================================================================
package thread.join;

public class ThreadTest extends Thread{
 public static void main(String[] args) {

  SumThread t1 = new SumThread(1,10);
  t1.start();
  
//  try {
//   Thread.sleep(1);
//  } catch (InterruptedException e) {
//   // TODO Auto-generated catch block
//   e.printStackTrace();
//  }
  
  try {
   t1.join();//t1이 끝나기 전까지 main을 Blocked하겠다. t1이 끝나기 전에 메인쓰레드가 끝날 수 없다.
  //t1.join()은 먼저 수행을 끝내야 할 값을 먼저 수행하게 해준다.
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  int sum = t1.getSum();
  System.out.println("1~10까지의 총 합 : "+sum);
 }
}

-----------

package thread.join;

public class SumThread extends Thread{
 private int first;
 private int last;
 private int sum;
 public SumThread(int first, int last) {
  this.first = first;
  this.last = last;
  
 }
 public int getSum() {
  return sum;
 }
 public void run(){
  //first~last까지 1씩 더하기.
  for(int i = first; i<= last; i++){
   sum = sum+i;
  }
 }
 

}

-----------

==================================

* 2012-4-5

project : day30
package : network.simple4.server
class : SimpleServer
        ServerThread

package network.simple4.server;


import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;

 


/*
 * 기다린다.
 * 클라이언트와연결
 * ServerSocket 생성
 * Client의 연결을 대기 -> Socket생성
 * ServerThread를 start
 */
public class SimpleServer {
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  //1. 서버 소켓 생성
  try {
   serverSocket = new ServerSocket(5555);
  } catch (IOException e) {
   e.printStackTrace();
  }
  while(true){
   try {
    //2. 클라이언트 연결 대기
    System.out.println("---클라이언트의 연결을 기다립니다.");
    socket = serverSocket.accept();
    //2. 클라이언트와 I/O ->ServerThread
    System.out.println("---클라이언트가 연결되었습니다.");
    ServerThread serverThread = new ServerThread(socket);
    serverThread.start();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

-------------

package network.simple4.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import network.util.NetworkUtil.NetworkUtil;

 /*
  * Thread 클래스
  * Socket을 받아서 그와 연결된 클라이언트가 보내는 글을 읽어 다시 클라이언트에 전송
  */

public class ServerThread extends Thread{
 Socket socket = null;
 InputStream inputStream = null;
 OutputStream outputStream = null;
 BufferedReader bufferedReader = null;
 PrintWriter printWriter = null;
 public ServerThread(Socket socket) {
  this.socket = socket;
 }
 public void run(){
  try {
   //1.  연결
   inputStream = socket.getInputStream();
   outputStream = socket.getOutputStream();
   //2. Filter추가
   bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   printWriter = new PrintWriter(outputStream, true);
   //3. 읽고/쓰는 작업처리
   String str = bufferedReader.readLine();
   while(str!=null){
    printWriter.println(str);
    str = bufferedReader.readLine();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }  finally{
   NetworkUtil.close(bufferedReader);
   NetworkUtil.close(printWriter);    
   NetworkUtil.close(socket);
  }
 }
}


------------

package network.util.NetworkUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;

public class NetworkUtil {

 public static void close(Socket socket){
  if(socket!=null){
   try {
    socket.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 public static void close(InputStream in){
  if(in!=null){
   try {
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 public static void close(OutputStream out){
  if(out!=null){
   try {
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 public static void close(Reader reader){
  if(reader!=null){
   try {
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 public static void close(Writer writer){
  if(writer!=null){
   try {
    writer.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


-------------
==========================================================================================

 

project : day30
package : network.simple4.client
class : SimpleClient
        ClientThread


package network.simple4.client;

 

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.Socket;
import java.net.UnknownHostException;

import network.util.NetworkUtil.NetworkUtil;


/*
 * 키보드로 부터 읽은 글을 서버로 출력
 */
public class SimpleClient {
 public static void main(String[] args) {
  //1. 서버와 연결 - Socket 객체 생성
  
  //2. clientThread를 start()
  //2-1 : ClientThread 객체 생성(소켓 전달)
  //2-2 : start();
  //3, Stream 생성 - InputStream(키보드), OutputStream(서버)
  //4. keyboard 입력 -> 서버 출력 - 반복
  //5. close(i/o, socket)
  Socket socket = null;
  BufferedReader keyboardBr = null;
  OutputStream outputStream = null;
  PrintWriter printWriter = null;
  
  try {
   //1. 서버와 연결 - Socket 객체 생성
   socket = new Socket("127.0.0.1", 5555);
   outputStream = socket.getOutputStream();
   //2. clientThread를 start()
   //2-1 : ClientThread 객체 생성(소켓 전달)
   ClientThread clientThread = new ClientThread(socket);
   //2-2 : start();
   clientThread.start();
   //3, Stream 생성 - InputStream(키보드), OutputStream(서버)
   keyboardBr = new BufferedReader(new InputStreamReader(System.in));
   printWriter = new PrintWriter(outputStream, true);
   //4. keyboard 입력 -> 서버 출력 - 반복
   System.out.println("종료 : ctr - z");
   System.out.println("입력 : ");
   String str = keyboardBr.readLine();
   //읽기/쓰기
   while(str!=null){
   
   printWriter.println(str);
 
//   clientThread.join();
   System.out.print("입력 : ");
   str = keyboardBr.readLine();
   }
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }  finally{
   NetworkUtil.close(keyboardBr);
   NetworkUtil.close(printWriter);
   NetworkUtil.close(socket);
  }
  
  

 }
}

 


-------------


package network.simple4.server;


import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;

 


/*
 * 기다린다.
 * 클라이언트와연결
 * ServerSocket 생성
 * Client의 연결을 대기 -> Socket생성
 * ServerThread를 start
 */
public class SimpleServer {
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  //1. 서버 소켓 생성
  try {
   serverSocket = new ServerSocket(5555);
  } catch (IOException e) {
   e.printStackTrace();
  }
  while(true){
   try {
    //2. 클라이언트 연결 대기
    System.out.println("---클라이언트의 연결을 기다립니다.");
    socket = serverSocket.accept();
    //2. 클라이언트와 I/O ->ServerThread
    System.out.println("---클라이언트가 연결되었습니다.");
    ServerThread serverThread = new ServerThread(socket);
    serverThread.start();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

-----------
==============================================================================================
* 채팅 프로그램

project : day30
package : network.chatting.client
class : SimpleClient
        ClientThread

package network.chatting.client;

 

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.Socket;
import java.net.UnknownHostException;

import network.util.NetworkUtil.NetworkUtil;


/*
 * 키보드로 부터 읽은 글을 서버로 출력
 */
public class SimpleClient {
 public static void main(String[] args) {
  //1. 서버와 연결 - Socket 객체 생성
  
  //2. clientThread를 start()
  //2-1 : ClientThread 객체 생성(소켓 전달)
  //2-2 : start();
  //3, Stream 생성 - InputStream(키보드), OutputStream(서버)
  //4. keyboard 입력 -> 서버 출력 - 반복
  //5. close(i/o, socket)
  Socket socket = null;
  BufferedReader keyboardBr = null;
  OutputStream outputStream = null;
  PrintWriter printWriter = null;
  
  try {
   //1. 서버와 연결 - Socket 객체 생성
   socket = new Socket("127.0.0.1", 5555);
   outputStream = socket.getOutputStream();
   //2. clientThread를 start()
   //2-1 : ClientThread 객체 생성(소켓 전달)
   ClientThread clientThread = new ClientThread(socket);
   //2-2 : start();
   clientThread.start();
   //3, Stream 생성 - InputStream(키보드), OutputStream(서버)
   keyboardBr = new BufferedReader(new InputStreamReader(System.in));
   printWriter = new PrintWriter(outputStream, true);
   //4. keyboard 입력 -> 서버 출력 - 반복
   System.out.println("종료 : ctr - z");
   System.out.println("입력 : ");
   String str = keyboardBr.readLine();
   //읽기/쓰기
   while(str!=null){
   
   printWriter.println(str);
 
//   clientThread.join();
   System.out.print("입력 : ");
   str = keyboardBr.readLine();
   }
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }  finally{
   NetworkUtil.close(keyboardBr);
   NetworkUtil.close(printWriter);
   NetworkUtil.close(socket);
  }
  

 }
}


----------------------------------------

package network.chatting.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import network.util.NetworkUtil.NetworkUtil;

/*
 * 서버가 출력한 글을 읽어서 표준 출력(모니터)에 출력
 */
public class ClientThread extends Thread{
 Socket socket = null;
 InputStream inputStream = null;
 BufferedReader bufferedReader = null;
 
 public ClientThread(Socket socket) {
  this.socket = socket;
 }

 public void run(){
  //1. InputStream(서버)
  //2. 서버에서 출력한 것 읽기, 표준 출력으로 출력(반복)
  //3. close() : InputStream, socket
 
  try {
   //1. InputStream(서버)
   inputStream = socket.getInputStream();
   bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   //2. 서버에서 출력한 것 읽기, 표준 출력으로 출력(반복)
   String str = bufferedReader.readLine();
   while(str != null){
   System.out.println("서버로부터 읽은 값 : "+str);
   str = bufferedReader.readLine();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }  finally{
   NetworkUtil.close(bufferedReader);
   NetworkUtil.close(socket);
  }
 }
}

-------------------------------------

 


project : day30
package : network.chatting.server
class : SimpleServer
        ServerThread
 ServerThreadPool

package network.chatting.server;

import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;


//accept()
//ServerThread.start()
//기존 소스에 풀에 추가하는 것만 넣으면됨.
public class SimpleServer {
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  Socket socket = null;
  
  try {
   serverSocket = new ServerSocket(5555);
  } catch (IOException e) {
   e.printStackTrace();
  }
  while(true){
  try {
   System.out.println("클라이언트와 연결을 기다립니다");
   socket = serverSocket.accept();
   System.out.println("클라이언트 연결 성공");
   ServerThread serverThread = new ServerThread(socket);
   serverThread.start();
   ServerThreadPool.addServerThread(serverThread);
   
   
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }
}

----------------

package network.chatting.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import network.util.NetworkUtil.NetworkUtil;

//client.read
//client.wirte
//클라이언트한테 메서드를 받아서 출력해주는 메소드를 만들어라.
public class ServerThread extends Thread{

 private Socket socket;
 private PrintWriter printWriter;
 
 public ServerThread(Socket socket) {
  this.socket = socket;
 }
 
 //소켓으로 인풋스트림, 아웃풋 스트림을 만들어 읽고 쓰기 작업을 한다
 public void run(){
     BufferedReader bufferedReader = null;
  OutputStream outputStream = null;
  InputStream inputStream = null;
  try {
   //연결
  
   inputStream = socket.getInputStream();
   outputStream = socket.getOutputStream();
   printWriter = new PrintWriter(outputStream, true);
   //buffer추가
   bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   
   String str = bufferedReader.readLine();
   while (str != null) {
    ServerThreadPool.broadcasting(str);
    str = bufferedReader.readLine();
   }
   
  } catch (IOException e) {
  
   
   e.printStackTrace();
  } finally{
   ServerThreadPool.removeServerThread(this);
   System.out.println("클라이언트 연결종료");
   ServerThreadPool.broadcasting("한명의 클라이언트가 나갔습니다.");
  
   NetworkUtil.close(bufferedReader);
   NetworkUtil.close(printWriter);    
   NetworkUtil.close(socket);
  }
 }
 //연결된 client에게 (Socket)에게 메세지 전송
 public void sendMessage(String message) {
  printWriter.println(message);
  
 }
 

}

---------------------

package network.chatting.server;

import java.util.ArrayList;

//서버 쓰레드들을 모아둠
//서버쓰레드가 종료 되면 컬렉션에서 빼줘야한다.
//class를 만들때 Pool하면 특정 객체들를 모아서 관리하는 객체다.
public class ServerThreadPool {

 //연결된 모든 클라이언트의 정보(Socket)을 가진 ServerThread들을 모아 관리.
 private static ArrayList<ServerThread> list = new ArrayList<ServerThread>();
 public ServerThreadPool() {
 }
 //list에 ServerThread를 추가 - 클라이언트가 기다리다가 연결되는 시점(ServerThread 객체 생성후 추가)//SimpleServer메인 처리
 public static void addServerThread(ServerThread serverThread){
  list.add(serverThread);
 }
 //list에서 ServerThread를 제거 - 클라이언트와 연결 끊었을 때 - ServerThread에서 처리
 public static void removeServerThread(ServerThread serverThread){
  list.remove(serverThread);
 }
 //list에 있는 모든 클라이언트에게 메세지를 출력하는 메소드. -ServerThread에서 클라이언트가 읽으면 출력
 //클라이언트로부터 메세지(글)을 읽었을때
 public static void broadcasting(String message){
  for(ServerThread serverThread : list){
   serverThread.sendMessage(message);

  }
 }
}

----------------------

=================================================

 

* 2012-4-10

* JDBC
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib
app와 product는 기억해라.
ojdbc14.jar과 연결해야 오라클 디비와 연동이 된다.

자바실행환경과 연결을 하려면
C:\Program Files\Java\jdk1.6.0_31\jre\lib\ext 경로에 가서 ojdbc14.jar을 붙여 넣어라.(이렇게 하면 따로 환경설정을 안해도 연동시킬 수 있다.(오라클 용으로 api연결))


* 2012 - 4 - 12
project : day 36
package : jdbc.address
class name : AddressDAO
             TestAddressDAO - main


project : day 36
package : jdbc.address.prepared
class name : AddressDAO
             TestAddressDAO - main

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

클래스, 생성자  (0) 2012.07.28
editplus 다운로드 및 설치하기  (0) 2012.07.28
자바의 특징(키워드, 주석, 객체)  (0) 2012.07.28
자바의 역사 및 설치하기  (0) 2012.07.28
JAVA정리파일  (0) 2012.04.19
Posted by 조은성
,