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

2014년 9월 10일 수요일

Thread

Process : 할당된 메모리공간을 기반으로 실행 중에 있는 P/G. Thread : Process내에서 P/G흐름을 형성하는 주체. Thread는 자신만의 메모리 공간을 할당 받아서 별도의 실행흐름을 형성. 즉, 별도의 실행흐름을 형성하기 위해서 자바 가상머신에 의해 만들어지는(또는 준비되는) 모든 리소스와 각종 정보들을 총칭해서 Thread라 한다. main메서드가 종료되어도 실행 중에 있는 Thread가 있다면, P/G은 종료되지 않는다. Thread는 자신만의 메모리 공간을 할당 받아서 별도의 실행흐름을 형성한다. 자바 가상머신은 start메서드의 호출을 요구하는 것이다. 메모리 공간의 할당 등 Thread의 실행을 위한 기반을 마련한 다음에 run메서드를 대신 호출해주기 위해서 말이다. 이는 우리가 main메서드를 직접 호출하지 않는 것과 비슷한 이치이다.

2014년 9월 8일 월요일

Enum

Enum은 method내에 위치할 수 없다.

interface and abstract class

interface는 interface를 implements할 수 없다. class는 interface를 extends할 수 없다. interface를 implements한 클래스는 interface의 메서드를 overriding하되 타입은 public이어야한다. abstract클래스는 abstract 메서드를 가지고 있거나, public 메서드를 구현한 상태여야한다. interface는 interface를 extends할 수 있다.

Boxing, UnBoxing, promotion, casting

boxing : 기본형 타입의 데이터를 참조형 타입으로 바꿔주는 것.
unboxing : boxing의 반대개념.

promotion : 작은 값을 큰 그릇에 대입하는 경우, 묵시적으로 형변환이 발생. 이를 promotion이라 한다.
casting : 큰 값을 작은 그릇에 대입하는 경우, 강제적으로 형변환 명시하여 사용한다. 데이터유실이 발생할 수 있다. (*참고로 boolean자료형은 형변환을 할 수 없다.)
promotion/casting관련 참조



method의 argument에서는 기본타입의 promotion이 일어나지 않는다.

 public static void go(short n){System.out.println("short");}
 public static void go(Short n){System.out.println("Short");}
 public static void go(Long n){System.out.println("Long");}
 
 public static void main(String[] args) {
  Short y=6;
  int z=7;
  long l=z;
  go(y);
  go(z);  //compile error. method의 argument에서는 기본타입의 promotion이 일어나지 않는다.
  go((long)z); //강제 casting을 통해 boxing이 발생하고 정상출력된다.
 }

2014년 9월 7일 일요일

다형성

메서드 위주로 간략화한 클래스 다이어그램



class안에서 class를 정의할 수 있으며, method안에서 class를 재정의 할 수 도 있다.
interface 내에서의 변수 은닉타입 지정의 범위: final, static, public

compare & compareTo

자바에서 객체간의 정렬을 위해서는 Comparator 인터페이스를 구현하고, compare메서드를 오버라이드해야한다.


 @Override
 public int compare(Object o1, Object o2) {
  Student snum1 = ((Student)o1);
  Student snum2 = ((Student)o2);
  
  if(snum1.getNum() > snum2.getNum()){
   return 1;  //순차정렬
  }else if(snum1.getNum() == snum2.getNum()){
   return 0;
  }else{
   return -1;
  }
 }

compare메서드의 두인자간의 비교결과에서 첫번째 결과값이 두번째 결과값보다 클 경우, 1을 리턴하면 순차정렬을 하고, -1을 리턴하면 역순으로 정렬을 한다.


문자열의 정렬을 구현할 경우 (기준:사전적정의에서의 순서), compareTo메서드를 구현한다.

 @Override
 public int compare(Object o1, Object o2) {
  String sc1 = ((Student)o1).getName();
  String sc2 = ((Student)o2).getName();
  
  return sc2.compareTo(sc1);  //역순, 순차정렬인 경우, sc1.compareTo(sc2)
 }

java collection framework(JCF)

Set : 순서 없고, 중복하여 객체삽입할 수 없음.
List : 순서 있고, 중복하여 객체삽입할 수 있음.
Map : 순서 없고, Key - Value를 한쌍으로 함. key에 대해 중복을 허용하지 않는다.



2014년 7월 13일 일요일


package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String execute() {
    name = "Hello, " + name + "!"; 
    return SUCCESS;
  }
}

2013년 7월 30일 화요일

Java compile 및 클래스 파일 실행 배치파일

compile 하는 시점에서의 현재 디렉토리 위치가 클래스파일에 대한 루트 디렉토리여야한다.
cp : classpath의 단축 명령어

set JAVA_HOME=C:\Java\jdk1.6.0_45
set lib=C:\Java\excelLib\

set SRC_HOME=C:\workspace\Admin\src\
set BIN_HOME=C:\workspace\Admin\bin\
set CLASSPATH=.;%lib%dom4j-1.6.1.jar
set CLASSPATH=%CLASSPATH%;%lib%poi-3.9-20121203.jar
set CLASSPATH=%CLASSPATH%;%lib%poi-ooxml-3.9-20121203.jar
set CLASSPATH=%CLASSPATH%;%lib%poi-ooxml-schemas-3.9-20121203.jar
set CLASSPATH=%CLASSPATH%;%lib%xmlbeans-2.3.0.jar

rem Move root directory for classes
cd C:\workspace\Admin\classes\

rem compile at root directory for classes and set classpath for external libarary
javac -d %BIN_HOME% -cp %CLASSPATH%;. %SRC_HOME%util\SXSSFExcelTest.java
java -cp %CLASSPATH%;. util.SXSSFExcelTest

rem close command windows
exit

2013년 7월 3일 수요일

생성자가 존재하는 이유

생성자를 이용하면 인스턴스 변수의 초기화를 한결 수월하게 진행할 수 있다.

생성자를 통해서 인스턴스 변수를 초기화하면, 인스턴스를 생성과 동시에 초기화할 수 있다. 뿐만 아니라, 이는 딱 한번만 호출되는 메서드이니, final로 선언된 인스턴스 변수의 초기화에도 사용이 가능하다.

메소드 매개변수의 전달시 연산처리

메서드명(변수A++) ==> 메서드의 매개변수에 변수A가 전달되지만, 메서드의 처리과정으로 들어왔을 때 연산(++)처리가 되지 않는다.

이럴 경우, 메서드명(변수++A)으로 처리하여 메서드의 매개변수에 이미 연산(++)이 처리된 변수를 넘겨줘야 원하는 작동을 실행할 수 있다.


2013년 6월 1일 토요일

커맨드창(CMD)에서 자바 입출력하기.

이클립스에서 Java main함수를 실행하는 Run as -> Java Application 기능 및 console의 입출력을 커맨드창(cmd)에서 실행하는 방법

- 개요
이클립스 사용시 자동 컴파일이 되며, 실행시 편리하게 입출력을 할 수 있다.
하지만 커맨드창 사용시 클래스 파일 실행해야한다. 이때 실행할 클래스파일명 앞에 패키지명도 입력해야한다. 또한 명령어실행시 커맨드라인의 경로는 클래스파일의 루트디렉토리가 아니면 ClassNotFoundException이 발생한다.

- 정리
1. 클래스 파일에 대한 루트디렉토리(예를 들면, C:\Java\Algorithm\bin)로 이동
2. java [패키지명].[클래스명]



- 예외발생(경로가 클래스파일의 루트가 아닌경우)



* CMD에서 JAVA 컴파일 및 실행에 관한 좀 더 자세한 정보는 다음 블로그를 참조
http://blog.daum.net/hamyy37/38

2013년 5월 27일 월요일

컬렉션 toArray

범위 : Collection<E>을 구현하는 인터페이스(BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>)를 구현한 클래스(예를 들어, ArrayList)
즉, 컬렉션 계통의 클래스는 toArray()가 구현되어 있다.

기능 : toArray(T[] a)는 컬렉션 형태로 저장되어 있는 것을 배열로 반환해준다.

사용예 : List<E> list = new ArrayList<E>();
toArray(new String[list.size()])    return => String[]
toArray(new int[list.size()])       return => int[]
toArray(new int[list.size()][])     return => int[][]

2013년 5월 25일 토요일

Scanner

Java console의 입출력시 C언어의 scanf에 해당하는 util이 있다. 그것은 Scanner이다.

사용법은 아래와 같다.

Scanner sc = new Scanner(System.in);  //선언 및 생성 초기화

String line = "";
while((line = sc.nextLine()) != null || !(line = sc.nextLine()).equals("")){
            // logic
            // 특정상황 시 break;
}
과 같이 사용하면 break문에 걸릴 때까지 계속해서 입력값을 받을 수 있다.

또는

while(sc.hasNext()){
            line = sc.nextLine();
            // logic
            // 특정상황 시 break;
}

과 같이 사용하면 break문에 걸릴 때까지 계속해서 입력값을 받을 수 있다.

2013년 5월 8일 수요일

ENUM

What is Enum in Java 
Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. Java Enum as type is more suitable on certain cases for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other language. One of the common use of Enum which emerges is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety, Serialization automatically.

자바에서 Enum이란.
자바에서 Enum은 자바에서 잘 알려진 값의 고정 숫자를 대표하는데 사용하는 키워드, 기능이다. 예를 들어, 한주의 일에 대한 숫자, 태양계 시스템에서 행성의 숫자와 같은/. Enumeration(Enum)은 JDK1.5에서 소개되었고, J2SE 5에서 오토박싱/언박싱, 제네릭, varargs, static import와 더불어 나의 좋아하는 기능중에 하나이다. 타입으로서 자바 Enum은 [예를 들어, NEW, PARTIAL FILL, FILL 또는 CLOSED와 같은 순서상태를 대표하는] 특정 케이스에 좀 더 적합하다. 원래 Enum은 자바에서 사용할 수 없었다./비록 C나 C++에서는 이용가능했지만/ 그러나 점차적으로 자바는 깨달았고 JDK5에서 Enum을 소개했다. 이 자바 Enum tutorial에서 우리는 자바의 다양한 Enum 예제를 볼 것이고, 사용법을 배울 것이다. 이 자바 Enum 튜토리얼은 [Enum에 의해 제공되는 다양한 기능과 그 기능의 사용법에] 초점을 맞출 것이다. 만일 당신이 이전에 C 또는 C++에서 Enumeration을 사용한 적이 있다면 당신은 자바의 Enum에 대하여 익숙할 것이다/ 그러나 개인적으로 봤을 때 자바의 Enum은 다른 언어의 그것보다 좀 더 풍부하고 다양하다. Enum의 일반적인 사용중의 하나는 자바에서 싱글톤을 쓰는데 Enum 을 사용하는 것이다/ 그리고 그것은 여태것 싱글톤을 구현하는 가장 쉬운 방법이다/ 그리고 다루는 것이다/ 쓰레드 안전성, 시리얼라이제이션과 관련된 이슈를 자동으로 다루는/.




How to represent enumerable value without Java enum

java enum example, enum in java tutorialSince Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can serve our purpose it has some serious limitations:


가산의 값을 자바 enum 없이 표현하는 방법

자바의 Enum은 자바 1.5버전 이상에서 이용가능하기 때문에, 논의할 필요가 있다/ 우리가 가산의 값들을 자바1.5 이전 버젼에서 Enum없이 어떻게 표현하는 지를/. 나는 public static final 상수값을 사용한다/ enum을 따라하기 위해/. 자바의 Enum 예제를 살펴보자/ 개념을 더 잘 이해하기 위해/. 이 예제에서 우리는 US통화 동전을 사용할 것이다/ [PENNY(1) NICKLE(5), DIME(10), QUARTER(25)와 같은 값들을 가진] 가산으로서

CODE ...
         ..
         .
이 코드는 우리의 목적을 이루지만, 몇몇 심각한 한계를 가지고 있다.


*가산 (可算)
[명사] <수학> 자연수의 집합과 일대일의 대응을 만들 수 있음을 이르는 말. 짝수 전체의 집합, 정수 전체의 집합, 유리수 전체의 집합 따위가 지니고 있는 특성이다.

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
  
Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.


1) 타입에 안전하지 않다: 무엇보다 그것은 type-safe하지 않다.; 당신은 통화에 유효한 어떠한 int값도 할당할 수 있다. 예를 들어, 99, 비록 그 값을 나타내는 동전이 없지만.
2) 의미없는 출력: 어떤 상수값을 출력하는 것은 숫자값을 출력할 것이다/ 동전의 의미있는 이름 대신에/ 예를 들어, 당신이 NICKLE을 출력하고자 한다면, NICKLE 대신 숫자5가 출력될 것이다.
3) 이름공간의 없음.


Enum을 이용하여 String을 switch문에 사용하는 예제.
public class EnumTest {
 private enum ServiceName{
   samsung
  ,apple;
 }
 
 public static void main(String[] args) {
  printEnumTest("samsung");
 }
 
 public static void printEnumTest(String serviceName){
  switch (ServiceName.valueOf(serviceName)){
  case  samsung:
   System.out.println("samsung");
   break;
  case apple:
   System.out.println("apple");
   break;
  }
 }
}



Read more: 자바Enum