4.  Wrapper클래스

- 기본자료형(int,char,double,..)을 클래스로 포장해 놓은 것

 

- 기본자료형과 관련된 속성과 메소드를 갖는다.

예)
    int    ==> Integer
    char   ==> Character
    long   ==> Long
    double ==> Double
    ...

 

ex>

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

 

        Integer in=new Integer("100");
        System.out.println("in:" + in);

 

        //public int intValue()
        //Integer객체를 int형으로 반환
        int n1=in.intValue();
        System.out.println("n1:"+n1);

 

        //가능(jdk1.5이상),오토박싱
        Integer in1=200;

        //가능,언박싱
        int n2=in1;
        System.out.println("in1:"+in1 +",n2:"+n2);

 

        //public static int parseInt(String s)
        //s를 int형으로 바꿔보세요!
        String s="300";
        int n3=Integer.parseInt(s);
        System.out.println("n3:" + n3);

 

        //public static String toBinaryString(int i)
        String s1=Integer.toBinaryString(100);
        System.out.println(100+"을 2진수로 표현하면:" + s1);

 

        //public static double parseDouble(String s)
        String s2="123.34";
        double d=Double.parseDouble(s2);
        System.out.println("d:"+d);

 

    }
}

 

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

 

        String str="Hello World 2012";
        int letter=0,digit=0,space=0;

        for(int i=0;i<str.length();i++){
            char ch=str.charAt(i);

 

            //public static boolean isLetter(char ch)
            //ch가 문자면 true
            if(Character.isLetter(ch)){
                letter++;
            }

 

            //ch가 숫자면 true
            if(Character.isDigit(ch)){
                digit++;
            }

 

            //ch가 공백이면 true
            if(Character.isWhitespace(ch)){
                space++;
            }
        }


        System.out.println("문자갯수:"+letter);
        System.out.println("숫자갯수:"+digit);
        System.out.println("공백갯수:"+space);
    }
}

 

import java.util.Random;
class Test07_Random{
    public static void main(String[] args){

 

        //public static double random()
        //        :0.0~1.0사이
        for(int i=0;i<10;i++){
            //1부터 10사이의 난수 얻어오기
            int a= (int)(Math.random()*10)+1;
            System.out.print(a+" ");
        }

 

        System.out.println();

 

        Random rnd=new Random();
        for(int i=0;i<10;i++){
            //public int nextInt()
            int b=rnd.nextInt(10);
            System.out.print(b+" ");
        }


    }
}

 

 

'JAVA' 카테고리의 다른 글

자료구조 API - Vector 클래스  (0) 2014.09.12
자료구조 API - ArrayList  (0) 2014.09.12
String클래스와 StringBuffer클래스의 차이  (0) 2014.09.12
lang 패키지  (0) 2014.09.12
패키지  (0) 2014.09.12

 

3. String클래스와 StringBuffer클래스와의 차이

- String클래스는 원본문자열이 변하지 않는 불변의 클래스이고 문자열이 변경될때마다 계속 새로운 변경된 문자열이 만들어진다.->용량이커짐

 

- StringBuffer는 문자열이 변경될때 원본 문자열 자체가 변경되어진다.

 

ex>

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

 

        String str1=new String("123");

        //문자열 연결하기
        String str2=str1+"456";
        System.out.println(str1+","+str2);

 

        StringBuffer sb1=new StringBuffer("123");
        //문자열 연결하기
        StringBuffer sb2=sb1.append("456");
        System.out.println(sb1+","+sb2);

    }
}





 

 

 

 

'JAVA' 카테고리의 다른 글

자료구조 API - ArrayList  (0) 2014.09.12
Wrapper클래스  (0) 2014.09.12
lang 패키지  (0) 2014.09.12
패키지  (0) 2014.09.12
추상 클래스 - 메소드 / 인터페이스 / Object  (0) 2014.09.12

 

lang 패키지

 

class Test02_String{
    public static void main(String[] args){
        String str1="안녕";
        //동일한 문자열상수가 이미 존재하면 그 주소값을 참조한다.
        String str2="안녕";

 

        //두 변수가 참조하는 주소값은 같다.
        if(str1==str2){
            System.out.println("1.두문자열은 같아요!");
        }

        if(str1.equals(str2)){
            System.out.println("2.두문자열은 같아요!");
        }

 

 

        String str3=new String("hello");

        //동일한 문자라도 new로 새로 생성됨
        String str4=new String("hello");

 

        //두 변수가 참조하는 주소값은 다르다.
        if(str3==str4){
            System.out.println("3.두문자열은 같아요!");
        }
        if(str3.equals(str4)){
            System.out.println("4.두문자열은 같아요!");
        }

    }
}







 

 

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

 

        //public String(byte[] bytes)
        byte[] b={65,66,67,68};
        String str1=new String(b);
        System.out.println("str1:"+str1);

 

        //public String(byte[] bytes,int offset,int length)
        String str2=new String(b,0,2);
        System.out.println("str2:"+str2);

 

        //public String(char[] value)
        char[] c={'A','B','C','D'};
        String str3=new String(c);
        System.out.println("str3:"+str3);

 

        //public char charAt(int index)
        System.out.println("ch:"+ch);

 

        // str4의 문자열의 길이를 구해 보세요.
        // public int length()
        int n=str4.length();
        System.out.println("str4의 길이:"+n);

 

        //public String substring(int beginIndex,int endIndex)
        String st=str4.substring(1,4);//1번째인덱스에서 4-1번째 인덱스까지의 문자열 꺼내오기
        System.out.println("st:"+st);
        String str5="hello";

 

        //public String toUpperCase()
        //str5를 대문자로 변환해서 출력해보세요.
        String st1=str5.toUpperCase();
        System.out.println("st1:"+st1 +",str5:"+ str5);     

 

        //public int indexOf(String str)
        String str6="song@daum.net";       

 

       //@문자의 위치값 얻어오기
        int n1=str6.indexOf("@");
        System.out.println("n1:"+n1);

 

        //@문자가 없으면 indexOf메소드는 -1리턴
        if(n1==-1){
            System.out.println("이메일 형식이 잘못되었어요!");
        }else{
            System.out.println("이메일 형식이 잘 되었어요!");
        }

 

       //public String[] split(String regex)
        String str7="홍길동,김철수,이영희";

 

        //str7을 ,를 기준으로 분리해서 배열로 얻어옴
        String[] ar=str7.split(",");
        for(int i=0;i<ar.length;i++){
            System.out.println(ar[i]);
        }

 

        int a=100;
        //public static String valueOf(int i)
        //a를 valueOf메소드를 이용해 String타입의 값을 출력해 보세요.
        String aa=String.valueOf(a);
        System.out.println("aa:"+a);

    }

}

 

 

 

 

'JAVA' 카테고리의 다른 글

Wrapper클래스  (0) 2014.09.12
String클래스와 StringBuffer클래스의 차이  (0) 2014.09.12
패키지  (0) 2014.09.12
추상 클래스 - 메소드 / 인터페이스 / Object  (0) 2014.09.12
클래스간 형변환 / 다형성  (0) 2014.09.12

 

1. 패키지

 

- 관련성 있는 클래스들을 묶어 놓은 꾸러미

 

- 클래스간에 이름 충돌을 방지하기 위한 목적으로도 사용

 

- 만드는 방법

1) 클래스를 정의할때 가장 윗줄에 패키지명(경로) 지정

 package 패키지경로;
 import 구문;
 class AA{
    ..
 }

 

2) 컴파일시 패키지를 생성해준다.

형식

javac -d 생성디렉토리 클래스명.java

 

3) 패키지의 클래스를 사용할때는 import를 사용한다.

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

 

 [참고]-라이브러리만들기
  c:\java\9일차>jar -cvf per.jar aa

 

import aa.bb.Person;
class  Test01_package
{
    public static void main(String[] args){
        Person per=new Person("홍길동","8012122223445");

        //System.out.println(per.toString());
        System.out.println(per);
    }
}

 

 

 

 

1. 추상클래스, 추상메소드

 

추상클래스

- 추상메소드를 포함하는 클래스

-객체를 생성할 수 없고 오로지 상속의 목적으로 만든다.

- 만드는 형식:클래스명 앞에 abstract를 붙여 만든다.

 

추상메소드

- body(몸체)를 갖지 않는 메소드

- 추상메소드는 자식클래스에서 반드시 오버라이딩해야 한다.

- 만드는 형식:메소드명앞에 abstract를 붙이고 body부분을 만들지 않는다.

 

예)

//추상클래스
abstract class MyParent
{
     //추상메소드
     public abstract void print();
        ...
}

- 만드는 이유:자식클래스에서 공통으로 구현해야 할 기능의 메소드를 가져야 하는 경우에 추상메소드를 사용한다.
 (자식에게 강제적으로 메소드를 오버라이딩하도록 제약을 줄 수 있다.)

 

ex>

//추상클래스
abstract class MyShape
{
    private String color;

    public MyShape(String color){
        this.color=color;
    }
    public String getColor(){
        return color;
    }

    //추상메소드
    public abstract void draw();
}
class MyRect extends MyShape
{
    public MyRect(String color){
        super(color);
    }

    //추상메소드를 반드시 오버라이딩 해야 한다!
    public void draw(){
        System.out.println("사각형 그리기");
    }
}
class MyCircle extends MyShape
{
    public MyCircle(String color){
        super(color);
    }

    //추상메소드를 반드시 오버라이딩 해야 한다!
    public void draw(){
        System.out.println("타원 그리기");
    }
}
class Test03_abstract
{
    public static void main(String[] args)
    {
        //new MyShape();
         //==> 오류발생:객체를 생성할 수 없다.
        MyRect mr=new MyRect("빨강");

        mr.draw();

        MyShape ms=mr;    //가능!
    }
}

 

 

 

2.  인터페이스(**)

 

- 자식클래스들이 가져야 기능들의 목록을 갖음(메뉴판)

 

- 상수와 추상메소드들로만 이루어진다. (인터페이스는 빈껍데기)

 

- 만드는 형식
      interface 인터페이스명{
          상수;
          ..
          추상메소드();
          ..
      }

 

- 인터페이스는 객체를 생성할 수는 없지만 자식객체를 참조할 수는 있다.

 

- 사용이유
1) 자식클래스들이 가져야 할 기능들의 뼈대를 제공한다.

2) 클래스에서는 다중상속이 지원되지 않지만 인터페이스는 다중상속이 가능하다.

3) 인터페이스를 적절히 사용하므로써 유지보수가 수월해 진다.

 

 

ex>

//도형이 구현해야 할 기능들의 목록을 지정
interface Shape        
{      
    public static final int RED=1;

    //public static final 이 생략됨
    int BLUE=2;

    public abstract void draw();

    //public abstract 이 생략됨
    void paint();
    void resize();
}
//인터페이스를 상속받을때 implements를 사용!
class Rectangle implements Shape
{   
    public void draw(){
        System.out.println("사각형그리기");
    }

    public void paint(){
        System.out.println("사각형칠하기");
    }
    public void resize(){
        System.out.println("사각형 크기 바꾸기");
    }
}
class Test04_interface{

    public static void main(String[] args)    
    {
        //Shape sh=new Shape();
        Shape sh=new Rectangle();
        sh.draw();
        sh.paint();
        System.out.println("RED:"+Shape.RED);
    }
}

 

 

ex> 중요!! 여러번 눈에 익히자.

interface MyDbms{
    //db접속기능
    void connect();

    //db접속해제
    void disconnect();

    //sql명령어 실행
    void execute(String sql);
}
class Oracle implements MyDbms{

    public void connect(){
        System.out.println("오라클 DBMS와 연결됨!");
    }
    public void disconnect(){
        System.out.println("오라클 DBMS와 연결이 해제됨!");
    }
    public void execute(String sql){
        System.out.println("오라클 명령어를 사용해 " + sql +"을 실행함");
    }
}
class MySQL implements MyDbms{

    public void connect(){
        System.out.println("MySQL DBMS와 연결됨!");
    }
    public void disconnect(){
        System.out.println("MySQL DBMS와 연결이 해제됨!");
    }
    public void execute(String sql){
        System.out.println("MySQL 명령어를 사용해 " + sql +"을 실행함");
    }
}
class  Test05_interface{
    public static void main(String[] args)
    {
        MyDbms db=new Oracle();
        db.connect();
        db.execute("회원추가");
        db.disconnect();
    }
}

 

 

ex> //인터페이스는 다중상속이 가능하다.

interface Shape{
    void draw();
    void paint();
}
interface Point{

    void setPoint(int x,int y);
}

//인터페이스끼리는 extends를 사용한다.
interface Rect extends Shape,Point       
{
    void resize();
}
class MyRect implements Rect
{
    private int x,y;

    public void draw(){
        System.out.println(x+","+y+"의 좌표에 사각형 그리기");
    }
    public void paint(){
        System.out.println("사각형칠하기");
    }
    public void setPoint(int x,int y){
        this.x=x;
        this.y=y;
    }
    public void resize(){
        System.out.println("사각형크기 바꾸기");
    }
}
class Test06_interface
{
    public static void main(String[] args)
    {
        MyRect mr=new MyRect();
        mr.setPoint(100,200);
        mr.paint();
        mr.draw();
    }
}

 

 


3.  Object : 모든 클래스의 부모클래스

 

class Person{

    private String name;
    private int age;
   
    public Person(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public String toString()
    {
        String aa="name:"+name +",age:"+age;
        return aa;
    }
}
class Test07_Object
{
    public static void main(String[] args)
    {
        Object ob1=new Object();
        //Object ob2=new Object();
        Object ob2=ob1;

        if(ob1==ob2)
        {
            System.out.println("두객체는 같아요1");
        }
        if(ob1.equals(ob2))
        {
            System.out.println("두객체는 같아요2");
        }
        //public String toString()
        String aa=ob1.toString();
        System.out.println(aa);

        Person per=new Person("홍길동",10);
        //String bb=per.toString();

        //name:홍길동,age:10
        System.out.println(per);

        String cc="안녕하세요";
       
        Integer in=new Integer(100);
        //String클래스는 toString메소드를 xxx했다.
        System.out.println("cc:" + cc + ",in:"+ in);
    }
}

 

 

ex>

class Person{

    private String name;
    private int age;

    public Person(String name,int age)
    {
        this.name=name;    this.age=age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public boolean equals(Object obj)
    {
        Person pp=(Person)obj;

        if(name.equals(pp.name) && age==pp.age)
        {
            return true;
        }else{
            return false;
        }
    }
}
class Test08_Object{

    public static void main(String[] args)
    {
        Person per=new Person("홍길동",10);
        Person per1=new Person("홍길동",10);

        if(per.equals(per1)){
            System.out.println("두사람은 같아요!");
        }else{
            System.out.println("두사람은 달라요!");
        }

        String str=new String("안녕");
        String str1=new String("안녕");

        if(str==str1)
        {
            System.out.println("두문자열은 같아요1!");
        }
        if(str.equals(str1))
        {
            System.out.println("두문자열은 같아요2!");
        }
    }
}

 

 

 

 

 

'JAVA' 카테고리의 다른 글

lang 패키지  (0) 2014.09.12
패키지  (0) 2014.09.12
클래스간 형변환 / 다형성  (0) 2014.09.12
오버라이딩 / final의 용도  (0) 2014.09.12
상속  (0) 2014.09.12

+ Recent posts