레이블이 java oveloading인 게시물을 표시합니다. 모든 게시물 표시
레이블이 java oveloading인 게시물을 표시합니다. 모든 게시물 표시

2013년 8월 9일 금요일

(java array)자바에서의 배열에 대해 알아 보기로 하겠습니다. ORACLEJAVANEW.KR

자바에서의 배열에 대해 알아 보기로 하겠습니다.  자바에서의 배열을 잘 공부해 두시면 닷넷등에서도 비슷하게 사용 되니 닷넷을 공부 할때 도움이 되실 겁니다.  열공!!


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  


 

배열이란? 배열도 객체 이며 ,,, 그래서 Memory Heap에 메모리가 할당 됩니다. 동일한 자료형을 갖는 자료의 배열이며, 배열 선언은 선언할때 크기 명시 안 한다는곳 기억 하시구요..

int[] a; ( 혹은 int a[];)

배열에 Access 하기 위한 첨자는 int 형 이며 long 인 경우에는 Type Casting을 해야 합니다.

배열 생성
a = new int[3];
int[] a = {1, 2, 3};
int[] a; a = new int[] {1, 2, 3};

배열 길이
a.length

배열의 재사용
int[] a = {1, 2, 3};
a = new int[50]; //이때 이전의 배열a의 내용은 버려지며 새로운 메모리 공간이 할당 됩니다.

[예제]

class ArrayTest {
public static void main( String[] args ) {
int[] a = {1, 2, 3}; // int형 배열 선언 및 값 할당
int a2[]; // int형 배열 선언
a2 = new int[] {7, 8, 9, 10, 11}; // 이름 없는 배열 생성
System.arraycopy(a, 0, a2, 3, 2); //배열을 복사(a라는 배열의 0번째를 a2라는 배열의 3번째 인덱스 부터
//2개 복사하라는 의미 입니다. a2는 7,8,9,1,2가 되겟네요...
System.out.println( a.length ); // 3
for(int i = 0; i < a.length; ++i) >
System.out.print( a[i] + " "); // array

// 스트링 객체의 참조값의 배열 생성
String[] as = { "i", "am", "boy", };
String[] as2 = { "me", "to", };

System.out.println("\n" + as.length ); // 3
for(int i = 0; i < as.length; ++i) >
System.out.print( as[i] + " "); //i am boy

as = as2;

System.out.println("\n" + as.length ); // 2
for(int i = 0; i < as.length; ++i) >
System.out.print( as[i] + " " ); //me to
as2 = null;
}
}


[결과]
3
1 2 3
3
i am boy
2
me to



배열의 배열 ( 다차원 배열 ) 

배열은 또 다른 배열을 포함 할 수 있으며 하위 배열은 모두 다른 크기를 가질 수 있습니다. 이를 자바에서는 배열의배열의 형태로 다룰 수 있습니다. 예를들면 1행은 열이 2개, 2행은 열이 3개,,, 이런게 가능하다는 이야기죠^^;;;

[예제]

class MultiArrays {
public static void main(String[] args) {
String[][] 자동차 = {
{"그랜져","소나타","아반테"},
{"매그너스","누비라"},
{"카니발","세피아"}
};

for(int i=0; i<자동차.length; i++) { >
System.out.print(자동차[i].length + ":");
for(int j=0; j<자동차[i].length; j++) { >
System.out.print(자동차[i][j] + " ");
}
System.out.print("\n");
//System.out.println();
}
}
}


[결과]
3:그랜져 소나타 아반테
2:매그너스 누비라
2:카니발 세피아




배열의 예외 

NegativeArraySizeException : 음수크기를 갖는 배열 객체를 만들고자 할때 발생 합니다.
ArrayStoreException : 배열의 자료형과 틀린 자료값을 저장 할려고 하는 경우에 발생 합니다. 예를들면 int형 배열을 선언하고 3.3 이라는 값등을 넣을때 나는 오류 입니다.
ArrayIndexOutOfBoundsException : 배열의 첨자 범위를 벗어 났을때 발생 합니다. A라는 배열을 방2개짜리로 만들면 인덱스는 0, 1을 가질수 있는데 A[2]라는 형태로 사용하는 경우 나는 오류 입니다.
NullPointException : null 값을 갖는 배열 객체 참조 변수를 참조하려고 할때 발생 합니다.

2013년 8월 6일 화요일

[오라클자바닷넷교육강좌]웹애플리케이션에서의 로깅 , Web Application Logging

웹애플리케이션에서의 로깅 

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  



로그를 남겨 프로그램을 디버깅 하는 일은 대단히 중요한 일입니다. 웹 애플리케이션에서의 로깅은 크게 시스템 로깅과 애플리케이션 로깅으로 나누어 볼 수 있는데 시스템 로깅은 사용자의 데이터 보다 애플리케이션의 내부적인 동작에 대한 기록 입니다. 예를 들면 컨테이너가 시작했을 때의 시스템적인 오류 정보 등을 기록하는 것들이 해당 되며 애플리케이션의 로그는 사용자가 로그인을 하는 경우 인증을 한 정보 등을 기록하는 것이 해당 됩니다.

시스템의 오류는 error로 표현되는 반면에 애플리케이션의 에러는 info로 정의가 가능합니다.

--------------------------------------
서블릿 컨테이너를 이용한 로깅
--------------------------------------

서블릿의 스펙에서 개발자들이 컨테이너의 로그 파일에 이벤트 정보를 로깅 할 수 있도록 지원 합니다. 로그파일의 이름이나 위치는 어떤 컨테이너를 사용 하느냐에 따라 다르지만 기록이 된다는 것은 사실 입니다.

java.servlet.ServletContext는 로그를 남기기 위한 두개의 메소드를 제공 합니다.

ppublic void log(Stirng msg);
public void log(String msg, Throwable throwable);

아래는 이 메소드를 Struts의 Action에서 사용 한 예입니다.

[이전의 DB를 이용한 인증 예제의 LoginAction 입니다.]

//로그를 남기자.
                StringBuffer buf = new StringBuffer("LoginAction : User --> ");
                buf.append(id + " logged in session");
                servlet.log(buf.toString());

위의 소스 코딩에 위해 Tomcat의 Console창에 다음과 같은 기록이 남습니다…

정보: action: LoginAction : User --> jcleelogged in session



------------------------
필터사용
-----------------------

필터는 서블릿2.3에 새로 추가된 기능 입니다. 서블릿의 필터를 이용하면 HTTP요청과 응답객체의 Contents를 검사 할 수 있으며 정적인 Contents뿐 아니라 동적인 Contents에 대해서도 필터기능을 이용하는 것이 가능 합니다.

필터링 기능을 이용하여 아래와 같은 일들이 가능 합니다.

- 클라이언트의 요청이 도달하기 전에 웹 리소스에 대해 접근 가능 합니다.
- 클라이언트의 요청이 리소스에 도달하기 전 요청을 처리 할 수 있습니다.
- 요청헤더나 데이터에 대한 수정이 가능
- 응답헤더나 데이터에 대한 수정 가능
- 어떤 리소스를 수행 한 후 리소스에 대한 메소드 호출을 가로챌 수 있습니다.

이 필터 기능을 로깅만을 위해 쓰기에는 아까운 면도 있지만 시스템에서 사용자의 행위를 추적하기에는 적합한 기술 입니다. 필터를 이용해 암호화, URL 및 기타정보에 대한 캐시, 인증,XML Contents를 변환하기 위한 XSLT 변환 등 다양한 일들을 할 수 있습니다.

필터를 생성 하기 위해서는 세 단계를 거쳐야 합니다.

1.        javax.servlt.Filter 인터페이스를 구현하는 자바 클래스를 만듭니다.
2.        web.xml에 filter 요소를 선언 합니다.
3.        웹애플리케이션의 리소스와 함께 filter class를 packaging 합니다.

Javax.servlet.Filter 인터페이스를 구현하는 클래스에서 반드시 구현해야 하는 세가지 메소드는 다음과 같습니다.

public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
public void destroy( );

[필터 예]


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletContext;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;

public class LoggingFilter implements Filter{
        public final static String LOG_FILE_PARAM = "Login.log";
        private FilterConfig filterConfig = null;
        private ServletContext servletContext = null;

        public void init( FilterConfig config ) throws        ServletException {
                // Initialize any neccessary resources here
                this.filterConfig = config;
                this.servletContext = config.getServletContext( );

                // You can get access to initialization parameters from        web.xml
                // although this example doesn't really use it
                String logFileName = config.getInitParameter( LOG_FILE_PARAM );

                // You can log messages to the servlet log like this
                log( "Logging to file " + logFileName );

                // Maybe initialize a third-party logging framework        like log4j
        }

        public void doFilter( ServletRequest request,ServletResponse response,FilterChain filterChain )       
                              throws IOException, ServletException {
                // Log a message here using the request data
                log( "doFilter called on LoggingFilter" );

                // All request and response headers are available to the filter
                log( "Request received from " +        request.getRemoteHost( ) );

                // Call the next filter in the chain
                filterChain.doFilter( request, response );
        }

        public void destroy( ){
                // Remove any resources to the logging framework here
                log( "LoggingFilter destroyed" );
        }

        protected void log( String message ) {
                getServletContext( ).log("LoggingFilter: " + message );
        }

        protected ServletContext getServletContext( ){
                return this.servletContext;
        }
}


[web.xml]

<filter>
                <filter-name>MyLoggingFilter</filter-name>
                <filter-class>LoggingFilter</filter-class>
                <init-param>
                        <param-name>log_file_name</param-name>
                        <param-value>log.out</param-value>
                </init-param>
        </filter>

        <filter-mapping>
                <filter-name>MyLoggingFilter</filter-name>
                <servlet-name>MyExampleServlet</servlet-name>
        </filter-mapping>

        <filter-mapping>
                <filter-name>MyLoggingFilter</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>



다음은 필터 기능을 이용하여 스트럿츠에서 한글 문제를 해결 한 경우 입니다.

[SetCharacterEncodingFilter.java]

package filters;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;



public class SetCharacterEncodingFilter implements Filter {

    protected String encoding = null;

    protected FilterConfig filterConfig = null;


    /**
    * Should a character encoding specified by the client be ignored?
    */
    protected boolean ignore = true;


    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }


    public void doFilter(ServletRequest request, ServletResponse response,
                        FilterChain chain)
        throws IOException, ServletException {

        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }

        // Pass control on to the next filter
        chain.doFilter(request, response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;

    }


    protected String selectEncoding(ServletRequest request) {

        return (this.encoding);

    }
}


[web.xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>

<!-- Example filter to set character encoding on each request -->
<filter>
 <filter-name>Set Character Encoding</filter-name>
 <filter-class>filters.SetCharacterEncodingFilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>EUC-KR</param-value>
 </init-param>
</filter>

<!-- Define filter mappings for the defined filters -->
<filter-mapping>
 <filter-name>Set Character Encoding</filter-name>
 <servlet-name>action</servlet-name>
</filter-mapping>

    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
       
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>3</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
 
</web-app> 

2013년 8월 1일 목요일

자바 InputStream (JAVA InputStream)

InputStream 클래스는 모든 파일 시스템으로부터 스트림의 한 바이트를 읽는다  

  int available(): 스레드가 대기하고 있는 상태에서 사용할 수 있는 바이트 반환, 실행을 중단하지 않고 입력 스트림에서 읽을 수  있는 바이트의 수를 리턴합니다. InputStream의 available 메소드는 0을 리턴합니다. 이 메소드는 서브클래스로 대체(override)되어야 합니다. 
  void close(): 입력 스트림을 닫는다.
  synchronized void mark(int i): 입력 스트림 상의 위치를 표시한다.
  public abstract int read(): 한 문자를 읽고 반환. 이때 스트림 끝은 -1
  int read(byte b[]): 바이트 배열을 읽는다.
  int read(byte b[], int off, int len): 배열 b의 off 위치에서 len 바이트 읽는다.
  sychronized void reset(): 마지막 표시를 반환하고, 계속 read()로 바이트를  읽을 수 있다.(mark 위치로 돌아감)
  void long skip(long i): 입력 스트림에서 n 바이트를 건너뛴다.
  public boolean markSupported() : 입력 스트림이 mark 및 reset 메소드를 지원하는지 여부를 테스트합니다
  System.in.read()는 표준 입출력 스트림으로부터 요구된 자료가 주어질 때까지 실행을 대기하고 있다가 리턴키가 전송될 때 비로소 진행한다. 읽는 단위는 ASCII의 8비트 문자단위이다.


// 읽은 문자를 정수(int)로 취급하는 경우
import java.io.*;
public class TestFile{
  public static void main (String args[]) throws IOException {
    StringBuffer buf=new StringBuffer();   
    int i; 
    while ((i=System.in.read())!=-1)// -1은 eof에 해당하는 코드
        buf.append((char)i); // ctrl+z은 -1에 해당한다.
    System.out.println();
    System.out.print(buf.toString());//StringBuffer를 string으로 변환
  }
}




//system.in.read()를 char로 형변환
import java.io.*;
public class TestFile1{
  public static void main (String args[]) throws IOException {
    StringBuffer buf=new StringBuffer(); 
    char c;
    while ((c=(char)System.in.read())!='\n')
        buf.append(c);
    // 여기서는 ctrl+z이 필요없다. 왜냐면 문자로 읽기 때문이다.
    System.out.print(buf.toString()); //StringBuffer를 string으로 변환
  }
}


------------------------------
BufferedInputStream –  예제
------------------------------
import java.io.*;
public class BufferedStatement {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
System.out.println("Stream 되돌리기 기능......"+bis.markSupported());
bis.mark(1024); //마킹을 해둔곳으로부터 1024 Byte 읽기전까지는 마킹이 유효
for(int i=0;i<10;i++) {
System.out.write(bis.read());
}
bis.reset();
System.out.println("\n reset() 호출");
for(int i=0; i< 20; i++) {
System.out.write(bis.read());
}
}
}


java interface polymorphism(인터페이스를 이용한 다형성)

앞의 예제의 Manager Class는 제외함.
인터페이스를 이용해 메소드를 사용하고 또 더불어 다형성을 제공할 수도 있다. 예를 들어 운전자는 영업팀 직원일 수도 있고 영업팀팀장일 수도 있다. 앞서 클래스의 다형성을 이야기 할 때 설명한 것과 비슷한 내용이지만 결국 운전자는 때에 따라서 여러 형태로 보여질 수 있다는 의미이다. 만약 운전자를 나타내는 인터페이스 SmallDriver 인터페이스가 영업팀직원일 수도 있고 영업팀팀장을 나타낼 수도 있다면 프로그래밍을 하는 사람의 입장에서는 보다 유연한 프로그래밍을 제공받을 수 있을 것이다. 


//인터페이스 선언
interface SmallDriver { 
  void driveSmallCar(); // 메소드 선언 
}

abstract class Employee {
    String name;
    String id;

  //생성자
    public Employee(String name1, String id1) { 
  name = name1;  id = id1; 
    }
    public void gotoOffice() {    System.out.println(name+"님 출근하였습니다...");  }
    public void gotoHome() {      System.out.println(name+"님 퇴근하였습니다...");  }
    public String toString() {    return "직원의 이름은 " + name + "이다.";  }
    abstract public void startJob();
}


//직원클래스를 상속한 영업팀직원 클래스
class SalesEmployee extends Employee implements SmallDriver{
    //영업담당지역, 메소드내에서만 변수에 접근이 가능하다.
    private String chargeArea;   
public String carName="소나타";
    public SalesEmployee(String newName,String newID,String newArea) {
        super(newName, newID);   
this.chargeArea = newArea;
    }
// SmallDrive 인터페이스의 메소드 구현 
    public void driveSmallCar() { 
          System.out.println("영업팀 직원 " + name + "은 " + carName + "를 운전한다.");
    }
    public void startJob() {
        System.out.println(super.name + "님이 " + this.chargeArea + " 지역으로 영업업무를 나갑니다...");
    }
}


//영업팀직원 클래스를 상속한 영업팀장 클래스
class SalesChief extends SalesEmployee implements SmallDriver{
      int salesTarget;  //영업팀 목표 매출액
  public String carName="그랜져";
      public SalesChief(String newName,String newID,String newArea, int newSalesTarget) {
          super(newName, newID, newArea); 
          this.salesTarget = newSalesTarget;
      }
  // SmallDrive 인터페이스의 메소드 구현 
      public void driveSmallCar() { 
          System.out.println("영업팀 팀장 " + name + "은 " + carName + "를 운전한다.");
      }
      //영업팀장의 업무는 더이상 확장이 안된다는 의미, 상속할수가 없다는 의미
      final public void startJob() {
          System.out.println(super.name + "님이 영업팀 직원을 관리한다...");
          System.out.println(super.name + "님이 관리하는 영업팀의 매출목표는 "+ this.salesTarget + "만원 입니다...");
      }
}


//Main Class
class InterfaceSample2 {
    public static void main(String[] args) {
        // 인터페이스가 클래스의 객체를 참조하도록...
        SmallDriver sm1 = new SalesEmployee("홍길동", "11111","서울");
        SmallDriver sm2 = new SalesChief("이순신", "22222", "개발부", 100000000);
        sm1.driveSmallCar();
sm2.driveSmallCar();

SalesEmployee se = new SalesEmployee("차두리","23456","독일");
se.gotoOffice();
se.startJob();
se.carName="티코";
se.driveSmallCar();
    }
}


추상메소드를 가지고 있고 이를 상속받거나 구현하는 클래스는 이 추상 메소드를 재정의하고 구현해야 한다는 점, 그리고 다형성을 구현하는 방법이라는 점, 메소드들이 동적으로 바인딩 된다는 점들은 비슷하다.
차이점
      - 인터페이스는 서로 연관성이 없는 클래스들에 의해 구현될 수 있고 따라서 수평적인 구현이 가능하지만 추상클래스의 경우 단일 상속 개념 하에 수직적인 구조로 상속을 해야만 한다.
    - 인터페이스에서는 메소드를 선언만 할 수 있으며 구현할 수 없다. 그리고 이 구현은 인터페이스를 구현하도록 설정된 클래스에서 가능하다. 하지만 추상클래스의 경우에는 추상 클래스 내부에서 메소드의 선언과 구현이 모두 가능하며 또한 이를 상속 받은 클래스에서도 재정의가 가능하다.

2013년 7월 28일 일요일

(오라클자바개발자실무교육,오엔제이프로그래밍실무교육센터)JAVA OOP OverL oading과 Overriding

슈퍼클래스로부터 메소드를 상속받을 때, 서브클래스 내에 같은 이름의 메소드가 있는 경우에  시그네췌(Segnature)가 다르면 중복(overloading)이 되고 시그네췌 (Segnature) 가 같으면 재정의(overriding)가 된다.  



오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷  실무전문 강의)




오버라이딩
  상속관계에 있는 클래스들간에 같은 이름의 메소드를 정의하는 행위 
  기존 클래스의 메소드 구현 부분만 약간 변화시켜 새로운 클래스를 생성할 수 있다 
  매개변수의 개수와 타입이 같아야 한다. 

오버로딩
  같은 클래스 내에 같은 이름의 생성자나 메소드를 사용하는 행위 
  매개변수의 개수와 타입이 달라야 한다 


[오버라이딩 예제]

class A {
int i=10; 
int f() { return i; }
static char g() { return 'A'; }
}
class B extends A{
int i=20;            //AAC i°¡ °¡·AAo´A°IAI´U. 
int f() { return -i; }//AcA¤AC
static char g() { return 'B'; }
}
public class OverrideTest {
public static void main(String[] args) {
B b = new B();
System.out.println(b.i);  //20
System.out.println(b.f()); //-20
System.out.println(b.g()); //B
System.out.println(B.g()); //B

A a = b;  //A a = (B) bμμ °¡´E
System.out.println(a.i);  //10
System.out.println(a.f()); //-20
System.out.println(a.g()); //A
System.out.println(A.g()); //A
}
}


[오버로딩 예제]
class OverLoadingTest {
public void say() {
System.out.println("default...");
}

public void say(String msg) {
System.out.println(msg);
}

  public static void main(String args[]) {
    OverLoadingTest ol = new OverLoadingTest();
ol.say();
ol.say("안녕하세요~ 반갑습니다...");
}