본문 바로가기
■ 프로그래밍, 개발

자바의 특징, 요약, 정리

by 토크맨 2016. 7. 27.
반응형

# 자바의 특징 

 

- javac.exe : 자바 컬파일러 - 자바소스코드를 바이트코드로 컴파일한다.

c:\javac Hello.java

 

 

- java.exe  : 자바 인터프러터 - 컴파일러가 생성한 바이트코드를 해석하고 실행한다.

c:\java Hello

 

 

- appletviewer.exe : 애플릿 뷰어 : HTML문서에 삽입되어 있는 애플릿을 실행시킨다.

c:\appletviewer Hello.html

 

 

- javadoc.exe : 자동문서생성기 

c:\javadoc Hello.java

 

 

- jar.exe : 압축프로그램 클래스파일과 프로그램의 실행에 관련된 파일을 하나의 jar파일로 압축하거나 해제.

압축 >> c:\jar cvf Hello.jar Hello1.class Hello2.class

해제 >> c:\jar xvf Hello.jar

 

 

- java 파일과 클래스 

 

- 소스파일의 이름은 public class의 이름과 일치해야 한다.

- 하나의 소스파일에 둘 이상의 class가 존재할 수 있으나 public class는 하나만 존재하여야 한다.

- 대소문자를 구분하므로 대소문자까지 일치해야한다. 

 

 

- char 형의 크기 

자바에서는 유니코드로 캐릭터가 처리되어 char 가 2 byte 로 처리 되어진다.

 

 

- long 타입의 리터럴에는 접미사 L을 붙여야 한다.

long big = 100000000000L;

 

 

- 문자열은 String 클래스을 사용한다.

 

String name = "Ja" + "va";

ex)) "" + 7   => "" + "7"  결과=>  "7"

7  + "" => "7" + ""  결과=>  "7"

7  + 7 + ""   => 14 + ""   결과=>  "14"

"" + 7 + 7 => "7" + 7   결과=>  "77" 

 

 

- 이름 붙인 반복문 

 

Loop1 : for (int i=0; i<3; i++) {

for (int j=0; j<3; j++) {

if (j==5)

break Loop1;

else 

break;

 

continue Loop1;

continue;

}

}

 

 

- 배열 선언 

 

int[] score = new int[5];

score[0] = 100;

score[1] = 200;

 

String[] name = new String[3];

name[0] = new String("AAA");

name[1] = new String("BBB");

 

 

- 배열 초기화 

 

int[] score = { 1, 2, 3, 4, 5 };

int[] score;

score = new int[] { 1, 2, 3, 4, 5 };

     

String[] name = { new String("AAA"), new String("BBB"), new String("CCC") };

String[] name = { "AAA", "BBB", "CCC" };

String[] name;

name = new String[] { new String("AAA"), new String("BBB"), new String("CCC") };

 

 

- 가변 배열 

 

int[][] score = new int[5][];

score[0] = new int[4];

score[1] = new int[3];

score[2] = new int[2];

score[3] = new int[2];

score[4] = new int[3];

 

- 배열 복사 

 

System.arraycopy(소스배열, 번지, 대상배열, 번지, 개수);

ex)) System.arraycopy(arr1, 0, arr2, 0, arr1.length);

 

 

- 클래스 선언위치에 따른 변수의 종류

 

class Test

{

int nT; // 인스턴스변수 

static int nS; // 클래스변수

 

void funcTest()

{

int nF = 3; // 지역변수 

}

}

 

 

- 클래스 생성자에서 다른 생성자 호출하기 

 

- 생성자의 이름으로 클래스이름 대신 this 를 사용한다.

- 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫 줄에서만 호출이 가능하다. 

 

ex)) class Car{

String color;

String gearType;

int door;

 

Car() {

this ("red", "auto", 3);

}

 

Car(String color, String gearType, int door) {

this.color = color;

this.gearType = gearType;

this.door = door;

}

}

 

 

- 멤버변수의 초기화 시기와 순서 

 

* 클래스변수의 초기화순서 : 기본값 -> 명시적초기화 -> 클래스 초기화 블럭

* 인스턴스변수의 초기화순서 : 기본값 -> 명시적초기화 -> 인스턴스 초기화 블럭 -> 생성자 

 

 

- 상속  ( 다중상속 허용 안됨. ) 

 

class Child extends Parent {

.......

}

 

 

- super 

* super는 자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수 이다.

 

* super() : 조상클래스의 생성자.

 

 

- package

 

* 클래스의 묶음이다. 클래스 또는 인터페이스를 포함 시킬 수 있다.

* 같은 이름의 클래스 일지라도 서로 다른 패키지에 존재할 수 있다.

* 하나의 소스파일에는 첫 번째 문장으로 단 한번의 패키지 선언만을 허용한다.

* 모든 클래스는 반드시 하나의 패키지에 속해야 한다.

* 패키지를 지정하지 않은 클래스는 자동으로 모두 "이름없는패키지' 에 속한다.

        * 클래스가 물리적으로 하나의 크래스파일(.class)인 것과 같이 

            패키지는 물리적으로 하나의 디렉토리이다.

 

 

- 패키지 선언 

 

* 패키지명을 지정하지 않으면 '이름없는패키지' 에 속하게 된다.

 

package 패키지명;

 

* javac -d [루트디렉토리] [파일파일명] 

ex)) c:\javac -d . PackageTest.java

 

: -d 옵션은 소스파일에 지정된 경로(패키지명)를 통해 패키지의 위치를 찾아서 클래스파일을 생성한다.

 

* 루트디렉토리는 자바 클래스패스에 추가해 주어야 한다.

:  [윈도우즈]

 

  [윈도우즈 cmd] autoexec.bat 파일에 

SET CLASSPATH=.;C:\JDK1.5\work;

 

  [윈도우즈 classpath 확인]

c:\> echo %classpath%

 

 

- import 

 

패키지 사용시, 사용할 패키지명 생략가능.

* 는 하위패키지의 클래스까지 포함하지는 않는다.

 

ex)) import 패키지명.클래스명;

    import 패키지명.*;

 

 

- final 

 

변수   : 값을 변경할 수 없다.  (선언시 또는 생성자에서 단 한번 초기화 될 수 있다.)

메서드 : 오버라이딩 할 수 없다.

클래스 : 상속을 할 수 없다. 

 

 

- abstract 

 

메서드 : 선언부만 있는 메서드 

클래스 : 추상메서드를 포함하고 있는 클래스 

 

 

- 접근제어자

 

private   : 같은 클래스 내에서만 접근 가능

default   : 같은 패키지 내에서만 접근 가능

protected : 같은 패키지 내에서, 다른 패키지의 자손클래스에서 접근 가능.

public    : 모든곳

 

 

- instanceof 연산자

 

인스턴스의 실제 타입을 알아보기 위해 사용한다.

 

  ex)) if ( CTool instanceof CRect )

 

 

- interface 

 

: 오직 추상메서드와 상수만을 멤버로 가질 수 있다.

 

interface 인터페이스이름 {

public static final 타입 상수이름 = 값;

public abstract 메서드이름(매개변수목록,,,);

}

 

- 모든 멤버변수는 public static final 이어야 하며, 이를 생략할 수 있다. (자동설정)

- 모든 메서드는 public abstract 이어야 하며, 이를 생략할 수 있다. (자동설정)

 

ex)) interface IMyRoom {

int nRoom = 1;     // public static final int nRoom = 1;

String GetRoomName();   // public abstract String GetRoomName(); 

      }

 

 

- 인터페이스는 인터페이스부터만 상속받을 수 있다. 

- 다중상속이 가능하다.

 

ex)) interface House extends Room, Door, Window { }

 

 

- interface 구현 

 

: 추상메서드의 몸통을 만들어주는 클래스를 작성해야 한다.

 키워드 'implements' 를 사용한다.

 

ex)) class City extends Load implements IRoom {

public void OpenDoor(int nIdx) { /* 내용 생략 */ }

public void CloseDoor() { /*내용 생략 */ }

    }

 

 

- exception

 

try {

...

 

} catch ( Exception e ) {

... 

}

 

 

- 예외 발생 

 

ex1)) Exception e = new Exception("TEST");

throw e;  // 예외발생 

 

ex2))   throw new Exception("TEST");

 

* Exception :: printStackTrace() : 예외발생 당시의 호출스택에 있었던 메서드의 정보와 예외 메시지를 화면에 출력한다.

* Exception :: getMessage()      : 발생한 예외클래스의 인스턴스에 저장된 메시지를 얻을 수 있다.

 

 

- 예외 메시지 처리 1

 

* PrintStream 클래스 사용 : 에러 메시지 내용을 파일에 기록하여 준다.

 

ex)) PrintStream ps = null;

    try {

ps = new PrintStream("error.log");

 

int i = 0/0;  // 예외발생 

 

     } catch (Exception e) {

e.printStackTrace(ps);

ps.println("예외메시지: " + e.getMessage());

     } 

 

 

- 예외 메시지 처리 2

 

* System.err

 

ex)) PrintStream ps = null;

    FileOutputStream fos = null;

    try{

for = new FileOutputStream("error.log", true);

ps = new PrintStream(for);

System.setErr(ps);   // err의 출력을 화면이 아닌, error.log파일로 변경한다.

 

} catch (Exception e) {

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

System.err.println("예외발생시간:" +  new Date()); 

e.printStackTrace(System.err);

System.err.println("예외메시지:" + e.getMessge());

 

}

 

 

- finally 

 

: 예외의 발생여부에 상관없이 실행되어야할 코드를 포함시킬 목적으로 사용된다.

 

* try 또는 catch 블럭내에 return문이 있어도 finally문이 실행되어진 후에 return된다.

 

ex)) try{

} catch (Exception e) {

} finally {

}

 

 

- 메서드에 예외 선언 (throws)

 

: 메서드내에서 발생할 수 있는 예외를 선언해둔다.

 메서드내에서 해당 예외가 발생될때 상위 메서드로 해당 예외가 넘겨진다.

 

  ex)) void method() throws Exception1, Exception2, .... {

.....

}

 

 

- 사용자정의 예외 

 

ex)) class MyException extends Exception {

private final int ERR_CODE;

 

MyException(String msg, int errCode) {

super(msg);

ERR_CODE = errCode;

}

 

MyException(String msg) {

this(msg, 100);

}

 

public int getErrCode() {

return ERR_CODE;

}

}

 

 

- String 

* String 클래스는 문자열을 저장하기 위하여 문자형 배열 변수(char[]) value를 인스턴스변수로 정의해놓고 있다.

* String인스턴스가 갖고 있는 문자열은 읽어 올 수만 있고, 변경 할 수는 없다. 

* '+'연사자를 이용해서 문자열을 겹합하는 경우 인스턴스내의 문자열이 바뀌는 것이 아니라

새로운 문자열이 담긴 String인스턴스가 생성되는 것이다.

 

* 문자열을 만들때는 두가지 방법 

1. 문자열 리터럴을 지정하는 방법   : String str = "AAA";

2. String 클래스의 생성자를 이용하는 방법 : String str = new String("AAA");

 

 

* 정수형 -> 문자열 

String String.valueOf(int i);

String String.valueOf(float f);

 

* 문자열 -> 정수형

boolean Boolean.getBoolean(String s);

int Integer.parseInt(String s);

long Long.parseLong(String s);

 

 

- StringBuffer 

* 문자열 변경이 가능하다. 

* 기본 문자열 길이 값은 16 이다.

* 기본으로 16보다 긴 문자열을 셋팅하면, +16한 길이만큼 버퍼가 생성된다.

 

StringBuffer sb = new StringBuffer(100);

sb.append("abcd");

 

* StringBuffer 변수들간의 비교는 toString()을 이용하여 비교한다.

 

StringBuffer sb = new StringBuffer("abc");

StringBuffer sb2 = new StringBuffer("abc");

 

if (sb.toString() == sb2.toString())

....

 

 

- wrapper클래스 

Boolean, Character, Byte, Short, Integer, Long, Float, Double

 

 

- inner class 

* 내부 클래스에서 외부 클래스의 멤버들을 쉽게 접근할 수 있다.

* 코드의 복잡성을 줄일 수 있다(캡슐화)

 

<종류>

1. 인스턴스 클래스

2. 스태틱 클래스 

3. 지역 클래스 

4. 익명 클래스 

 

 

- 내부클래스의 선언 

 

class Outer {

class InstanceInner {}

static class StaticInner {}

 

void myMethod() {

class LocalInner {}

}

}

 

 

 

 

 

 

- 컬렉션 프레임웍 : 다수의 데이터를 쉽게 처리할 수 있는 표준화된 방법을 제공하는 클래스들

 

* Vector 보단 ArrayList 를, Hashtable 보다는 HashMap을 사용하는 것이 바람직하다.

* Vector와 ArrayList 같이 배열을 이용한 자료구조는 데이터를 읽어오고 저장하는 데는 효율이 좋지만,

용량을 변경해야할 때는 새로운 배열을 생성한 후 기존의 배열로부터 새로 생성된 배열로 

데이터를 복사해야하기 때문에 상당히 효율이 떨어진다는 단점을 가지고 있다.

 

List인터페이스  - ArrayList, 

 Vector : 기본크기 10, 부족할경우 자동적으로 기존의 크기보다 2배의 크기로 증가된다.

 LinkedList, 

 Stack 

 

Set인터페이스  - HashSet, TreeSet

 

Map인터페이스  - Hashtable, HashMap, LinkedHashMap, SortedMap, TreeMap

 

 

- 컬렉션 프레임웍 동기화 

 

: ArrayList 와 HashMap 과 같은 컬렉션은 동기화를 자체적으로 처리하지 않고 필요한 경우에만 

java.util.Collections클래스의 동기화 메서드를 이용해서 동기화처리가 가능하도록 변경하였다.

 

static Collection sysnchronizedCollection(Collection c)

static List syschronizedList(List list)

static Map sysnchronizedMap(Map m)

static Set sysnchronizedSet(Set s)

static SortedMap synchronizedSortedMap(SortedMap m)

static SortedSet synchronizedSortedSet(SortedSet s)

 

List list = Collections.synchronizeList(new ArrayList(...));

 

 

- Iterator 

 

* ArrayList 

 

List list = new ArrayList();

Iterator it = list.iterator();

while( it.hasNext() ) {

System.out.println(it.next());

}

 

* Map 

Map map = new HashMap();

...

Iterator it = map.keySet().iterator();

 

* Set 

Set eSet = map.entrySet();

Iterator it = eSet.iterator();

 

 

- 컬렉션 클래스 정리 & 요약 

 

* ArrayList : 배열기반, 데이터의 추가와 삭제에 불리, 순차적인 추가삭제는 제일 빠름.

임의의 요소에 대한 접근성이 뛰어남.

 

* LinkedList : 연결기반, 데이터의 추가와 삭제에 유리.

임의의 요소에 대한 접근성이 좋지않다.

 

* HashMap : 배열과 연결이 결합된 형태. 

추가, 삭제, 검색, 접근성이 모두 뛰어남. 검색에는 최고성능을 보인다.

 

* TreeMap : 연결기반. 정렬과 검색에 적합.

검색성능은 HashMap보다 떨어짐. 

 

* Stack : Vector를 상속받아 구현

 

* Queue : LinkedList가 Queue인터페이스를 구현

 

* Properties : Hashtable을 상속받아 구현 

 

* HashSet : HashMap을 이용해서 구현 

 

* TreeSet : TreeMap을 이용해서 구현 

 

* LinkedHashMap : HashMap과 HashSet에 저장순서유지기능을 추가하였음.

* LinkedHashSet :       HashMap과 HashSet에 저장순서유지기능을 추가하였음.

 

 

- 유용한 클래스   : 알아두면 좋은 자주 쓰이는 클래스들

 

* Calendar / Date

 

Calendar cal = Calendar.getInstance();

...

Date d = new Date(cal.getTimeInMillis()); // Date(long date)

 

Date d = new Date();

 

Calendar cal = Calendar.getInstance();

cal.setTime(d);

 

 

Calendar today = Calendar.getInstance();

System.out.println("년:", today.get(Calander.YEAR));

System.out.println("월:", today.get(Calander.MONTH));

System.out.println("일:", today.get(Calander.DAY_OF_MONTH));

System.out.println("시:", today.get(Calander.HOUR_OF_DAY));

System.out.println("분:", today.get(Calander.MINUTE));

System.out.println("초:", today.get(Calander.SECOND));

System.out.println("밀:", today.get(Calander.MILLISECOND));

 

 

- int dayDiff(int y1,int m1, int d1, int y2, int m2, int d2);  

: 두 날짜간의 차이를 일단위로 반환한다.

 

- String convertDayToDate(int day)

: 일단위의 값을 년월일의 형태의 문자열로 변환하여 반환한다.

 

- intconvertDateToDay(int year, int month, int day)

: 년월일을 입력받아서 일단위로 변환한다.

 

 

* Random

 

Random rand = new Random();

int nR = rand.nextInt(100);  // 0부터 99까지의 난수 발생.

 

- Math.random()  // 랜덤수 발생.

 

 

* Scanner 

 

Scanner(String source)

Scanner(File source)

Scanner(File source, String charsetName)

Scanner(InputStream source)

Scanner(Readable source)

 

// JDK1.5이전

 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String input = br.readLine();

 

// JDK1.5이후

 

Scanner s = new Scanner(System.in);

String input = s.nextLine();

 

 

ex))

import java.util.Scanner;

import java.io.File;

 

class ScannerEx {

public static void main (String[] args) throws Exception

{

Scanner sc = new Scanner(new File("data.txt"));

int sum = 0;

int cnt = 0;

 

while(sc.hasNextInt()) {

sum += sc.nextInt();

cnt++;

}

}

}

 

* 문자열분리 

 

1. String[] result = "10,20,30,40,50".split(",");

 

2. Scanner sc = new Scanner("10,20,30,40,50").useDelimiter(","); 

 

3. StringTokenizer 

 

String source = "10,20,30,40,50";

StringTokenizer st = new StringTokenizer(source, ",");

 

while(st.hasMoreTokens()) {

Syetem.out.println(st.nextToken());

}

 

 

 

 

- 형식화 클래스   : 데이터를 표준화된 형식으로 출력하는데 도움을 주는 클래스들 

 

- JDK1.5 이상 printf 추가됨.

 

String str = String.Format("%d %d", 10, 10);

System.out.format("%d %d", 10, 10);

System.out.printf("%d %d", 10, 10);

 

 

* DecimalFormat

 

* SimpleDateFormat : 날짜형식 지정 및 출력 

 

Ex))

Date today = Date();

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

String result = df.format(today);

 

Ex))

DateFormat df = new SimpleDateFormat("yyyy/MM/dd");

Date d = df.parse("2016년 8월 12일");

System.out.println(df.format(d));

 

- 기호 

y 년도 2016

M 1~12

d 1~31

H 시간 0~23

m 0~59

s 0~59

S milsec 0~999

 

 

* ChoiceFormat : 특정 범위에 속하는 값을 문자열로 변환

 

Ex))

double[] limits = {60,70,80,90};     // 낮은 값부터 큰 값의 순서로 적어야 한다.

String[] grades = {"D","C","B","A"}; // 순서와 개수를 맞추어야 한다.

 

int[] scores = {100,95,88,75,52,60,70};

 

ChoiceFormat form = new ChoiceFormat(limits, grades);

 

for(int i=0; i<scores.length;i++)

System.out.println(score[i] + ":" + form.format(scores[i]));

 

 

* MessageFormat : 데이터를 정해진 양식에 맞게 출력할 수 있도록 도와준다.

 

 

Ex))

import java.util.*;

import java.text.*;

 

String tableName = "CUST_INFO";

String msg = "INSERT INFO " + tableName + " VALUES (''{0}'',''{1}'',''{2}'',''{3}'');";

 

Object[][] arguments = {

{"이자바", "02-123-1234", "24", "03-04"},

{"김길동", "02-321-4321", "32", "08-32"}

};

 

for (int i=0; i<arguments.length; i++) {

String result = MessageFormat.format(msg, arguments[i]);

System.out.printfln(result);

}

 

- 제네릭스 (Generics)

: 다룰 객체의 타입을 미리 명시해줌으로써 형변환을 하지 않아도 되게 하는 것이다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

댓글