본문 바로가기
공부/java

13일차

by 샤샤샤샤 2022. 11. 30.

Math 클래스

사실 이 클래스는 굳이 공부해야 하나 싶다. 그냥 대강 이런 기능이 있구나, 하는 것만 알아두고, 그때그때 필요할때 검색하면 되지 않을까 싶다.

//Math 클래스 - 수학적인 계산에 사용.
// java.lang.Math 패키지에 있으므로, import안해도 됨.

public class ex95 {
    public static void main(String[] args) {
        //소숫점 첫째자리 반올림
        double num = 91.789D;
        System.out.println( Math.round( num ) ); //92
        //연습문제 54
        //소수점 둘째자리에서 반올림
        System.out.println( Math.round( num * 10 ) / 10.0 );
        //소숫점 셋째자리에서 반올림
        System.out.println( Math.round( num * 100 ) / 100.0 );
        //올림
        double num2 = 91.128D;
        System.out.println( Math.ceil( num2 ) );
        //버림
        System.out.println( Math.floor( num2) );

        //각도 계산 - sin, cos, tan
        //단위 2가지
        //1. 일상생활 - 360분위 : 0도 180도 360도
        //          : 0도 360도 구분할 수 없다. -회전,+회전을 구분할 수 없다.
        //2. 수학(컴퓨터)적 표현 - 라디안 - 각도를 실수1개로 표현한 것.
        //  360분위를 라디안으로 바꾸고, Math계산한 후에,
        //  360분위로 바꿔서 출력한다.
        // 1 라디안 = 180 도 / PI(3.14) = 약 57.29도이다.
        // 180 도 = PI( 3.14 ) 라디안
        // 360 도 = 2 * PI = 6.28 라디안
        // 1 도 = 0.017 라디언

        //피타고라스 정리로 변의 길이 구하기
        //c = 루트( a*a + b*b )
        //             /|
        //            / |
        //         c /  | b
        //          +---+
        //            a
        double a = 10;
        double b = 10;
        double aa = Math.pow( a, 2 ); //a^2, 제곱근을 구하는 메소드 pow()
        double bb = Math.pow( b, 2 );
        double c = Math.sqrt( aa + bb ); //루트근을 구하는 메소드 sqrt()
        System.out.println( c );

        //삼각형의 내각의 합은 180도이다.
        //toRadians() 함수 : 각도(degree)를 라디안으로 변경
        //toDegrees() 함수 : 라디안을 각도로 변경

        // Sin 세타 = b / c;

        //세타각과 대변 c값만 알고 있을때, b변의 길이는?
        //  45도    14.14
        double b2 = c * Math.sin( Math.toRadians( 45 ) );
        System.out.println( b2 );
        //세타각과 대변 c값만 알고 있을때, a변의 길이는?
        double a2 = c * Math.cos( Math.toRadians( 45 ) );
        System.out.println( a2 );

        //절대값 구하기 : 음수값 -> 양수값, 양수값 -> 양수값
        double abs = Math.abs( -123 );
        System.out.println( abs );

        //더 큰 값 가져오기
        double max = Math.max(10, 20);
        System.out.println( max );
        //더 작은 값 가져오기
        double min = Math.min(10, 20);
        System.out.println( min );
        //랜덤값 가져오기 0.0 ~ 0.99999...
        System.out.println( Math.random() );
        //10이상 20이하의 랜덤 정수 가져오기
        //                   0.0 ~ 9.99999...
        //                   0.0 ~ 10.99999...
        //                   0 ~ 10
        //                   10 ~ 20
        System.out.println( (int)(Math.random()*11) + 10 );
    }
}

굳이 하나만 기억하자면, 각도는 라디안이라는 새로운 단위가 존재해서, 다시 알맞은 함수를 통해 우리가 아는 360도 단위로 변경해줘야 한다.

 

 

래퍼클래스

자바에서 모든 객체는 Object를 최상위 상속 클래스로 둔다. 하지만 기본형 8개(int, long, short, byte, char, float, double, blooean)는 래핑 클래스로 감싸야만 Object 클래스를 업캐스팅 할 수 있다.

본래 래핑 클래스 역시 클래스이기에

 Integer intValue1 = new Integer( 10 );

이런식으로 선언해야 하지만, 너무 자주 쓰이는 형태이기에 자바에서 쉽게 선언할수 있게 해놨다.

 Integer intValue2 = 10;

마치 기본형 정수를 선언, 초기화 하는 것처럼 선언할수 있다.

public class ex96 {
    public static void main(String[] args) {
        //래퍼클래스(Wrapper Class)
        //1. 기본자료형 8개를 클래스로 감싸서 기능 추가
        //2. 기본자료형을 클래스(객체)로 만들어서 하나의 타입(Object)로 전달 가능.

        //기본자료형 8개 : int long short byte char  float double  boolean
        //래퍼클래스 : Integer,Long,Short,Byte,Character,Float,Double,Boolean
        //   숫자형 클래스 Number <= int,long,short,byte,float,double
        Integer intValue1 = new Integer( 10 );
        System.out.println( intValue1 );
        System.out.println( intValue1.intValue() );
        System.out.println( intValue1.doubleValue() );

        //Deprecated : 이전버젼에서는 사용되었으나, 현재버젼에서는 사용되지
        //             않는 함수나 클래스를 의미함. 새로운 버젼을 사용하도록
        //             권고한다는 의미.
        Integer intValue2 = 10;
        System.out.println( intValue2 );

        //Number 클래스 : 숫자데이타 - 정수,실수 모두
        Number num1 = 30;
        Number num2 = 3.14D;
        System.out.println( num1.doubleValue() );
        System.out.println( num2.intValue() );

    }
}

 

스레드(Thread)

스레드 : 실, 실타래를 의미한다. 

             프로그램 안에서 작은 또하나의 프로그램을 생성하여 돌리는 것이라고 생각하면 된다. 비록 ui가 없더라도 계속                   백그라운드에서 돌고 있다.

 

스레드 구현하기

1. 추상화 클래스 상속하기 - Thread

2. 인터페이스로 구현하기 - Runnable

 

1. 추상화 클래스로 상속하기

Thread 클래스에 존재하는 run() 함수를 오버라이드 해서 사용한다. 비어있는 run()함수를 가져와서 그곳에 코드를 짜는 개념이라고 생각하면 편하다.

class Man extend Thread{
    int height = 170;
    @Override
    public void run(){
    //super.run 함수는 지워줌
    System.out.println("스레드 작동중");  
    
    
public class ex97 {
    public static void main(String[] args) {
        Man m = new Man();
        m.start()              출력값: "스레드 작동중"

Thread.sleep() : 프로그램의 작동을 잠시 멈추는 함수. 밀리초를 단위로 조절할수 있다. 이 함수를 사용하기 위해선 반드                             시 예외처리를 해줘야만 한다.

try{ Thread.sleep(2000) //2초 정기
    }
    catch(Exception e) {   //Exception e    Exception클래스의 객체 e
    }                     //                Exception을 형식으로 받는 e

 2.인터페이스로 구현하기

다중상속이 가능하기에 인터페이스로 구현하는게 큰 프로그램을 짤때는 유리하다.

이경우 Thread가 아닌 Runnable와 implement 를 사용하고, Thread 클래스를 추가적으로 만들어서 인자로 객체를 넣어줘야 실행된다.

class Woman implement Runnable{
    int height = 160;
    String name = "영희";
    @override
    public void run()
        System.out.println("스레드 실행중");
  }
  
  public class ex98 {
    public static void main(String[] args) {
        Woman w = new Wowman();
        Thread t = new Thread(w);   // 추상화와 달리 스레드 클래스 객체를 한번 더 만들어야함
        t.start();                출력값 : 스레드 실행중
//스레드(Thread) : 실,실타래를 의미함.
//              : 프로그램안의 작은 프로그램을 의미함.
//              : 메인스레드안에서 별도의 스레드를 생성하여 실행하는 것.
// 사용예) 웹브라우저에서 네이버화면을 보면서 다운로드도 함께 실행.
//        백그라운드(UI없는 프로그램)로 돌면서 서비스를 수행한다.

//자바로 스레드를 구현하는 방법 2가지
//1. 추상화 클래스를 상속하는 방법 - Thread
//2. 인터페이스를 구현하는 방법 - Runnable

class Printer extends Thread {
    int count = 0;
    @Override
    public void run() {
        //super.run();  지워준다.
        //run()함수는 1회만 호출되고 종료되므로,
        //무한루프를 만들어서 계속 실행되도록 한다.
        while(true){
            System.out.println("Printer:" + count++ );
            //탈출조건
            if( count > 10 ){
                break;
            }
        }
    }
}

public class ex97 {
    public static void main(String[] args) {
        Printer p = new Printer();
        //Thread 클래스 안의 start()함수 실행 : 스레드를 시작하는 함수
        p.start();
        System.out.println("메인함수 종료!");
    }
}
//스레드를 여러개 만들고, 비동기적으로 실행해 보자.
class Printer2 extends Thread {
    int count = 0;
    String name = "노브랜드";
    //필드가 있는 생성자
    public Printer2(String name) {
        this.name = name;
    }
    //run() 메소드 오버라이드-재정의
    @Override
    public void run() {
        //super.run();
        while(true){
            System.out.println( this.name + (count++) );
            if( count > 10 ){
                break;
            }
            //1초 딜레이
            try {
                if( this.name.equals("우리집 프린터") == true ){
                    Thread.sleep(1000);
                }else{
                    Thread.sleep(500);
                }
            } catch (Exception e) {   }
        }
    }
}
public class ex98 {
    public static void main(String[] args) {
        Printer2 p1 = new Printer2("우리집 프린터");
        p1.start();
        Printer2 p2 = new Printer2("우리학원 프린터");
        p2.start();
    }
}
//자바로 스레드를 구현하는 방법 2가지
//1. 추상화 클래스를 상속하는 방법 - Thread
//2. 인터페이스를 구현하는 방법 - Runnable
class Printer3 implements Runnable {
    int count = 0;
    String name = "노브랜드";

    public Printer3(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        while (true){
            System.out.println( this.name + (count++) );
            if( count > 10 )
                break;
            try {
                Thread.sleep(1000);
            } catch (Exception e) {  }
        }
    }
}
public class ex99 {
    public static void main(String[] args) {
        Printer3 p1 = new Printer3("우리집 프린터");
        Thread t1 = new Thread( p1 );
        t1.start();

        Printer3 p2 = new Printer3("학원 프린터");
        Thread t2 = new Thread( p2 );
        t2.start();
    }
}
//연습문제 55
// 혼자서 온도를 조절하는 보일러(Boiler)를 스레드로 설계해보자.
// Thread 클래스를 상속하여 만드시오.
// 실제 온도 변수 : int realTemp = 23;  초기값
// 설정 온도 변수 : int setTemp = 20; 초기값
//              설정 함수 : setSetTemp(int setTemp)
// 무한루프를 돌면서 : 실제 온도와 설정 온도를 출력하시오.
//                 : 1초마다 내부 온도를 설정온도에 +/- 1도씩 바꿀수있다.
// 출력값 : 실제온도:23, 설정온도:20
//         실제온도:22, 설정온도:20
//         실제온도:21, 설정온도:20
//         실제온도:20, 설정온도:20 빙고!
//  setSetTemp( 22 );
//         실제온도:21, 설정온도:22
//         실제온도:22, 설정온도:22 빙고!

//변수 이름 만드는 법
//1. Camel Case : outTemp
//2. UnderBar Case : out_temp  OUT_TEMP(상수일때)
//3. Dash Case : out-temp (변수이름에는 쓸수없고, 속성이름이나 파일이름)
class Boiler extends Thread {
    int realTemp = 23;
    int setTemp = 20;
    void setSetTemp(int setTemp) {
        this.setTemp = setTemp;         // setTemp 값을 바꿔주는 생성자함수
    }
    @Override
    public void run() {            //Thread의 run오버라이드
        while (true){
            System.out.println("실제온도:"+realTemp+",설정온도:"+setTemp);
            if( realTemp > setTemp ){
                realTemp--;
            } else if( realTemp < setTemp ){
                realTemp++;
            } else {
                System.out.println("빙고!");
                break;
            }
            try{
                Thread.sleep(1000);
            }catch (Exception e) { }
        }
    }
}
public class ex100 {
    public static void main(String[] args) {
        Boiler b = new Boiler();
        b.start();
        while (true){
           try {
               b.join(); //b 스레드가 종료시까지 대기...
               b = new Boiler();
               b.setSetTemp( 25 );
               b.start();
           }catch (Exception e) { }
        }
    }
}

 

예외처리

우리가 코드를 짜서 실행시켜보다 보면 종종 에러가 발생한다. 그럴 경우 프로그램은 강제로 중단되고 끝난다. 그런 상황을 막기 위해 존재하는 것이 바로 예외처리다. 즉, 예측되는 오류가 발생할 시, 미리 지정해둔 행동을 하게끔 강제하는 것이라고 보면 된다.

 

1. try / catch문

System.out.println(10/0);

이경우, 산술 연산 오류가 발생한다.

Exception in thread "main" java.lang.ArithmeticException: / by zero

이 오류가 발생할시, "산술 연산 오류 발생!" 이라는 글자를 출력하고 싶으면 어떻게 해야 할까?

이때 필요한 것이 바로 try/catch문이다.

try {
       System.out.println(10 / 0);
        }catch ( Exception e ){              // 업스케일링
            System.out.println("오류발생!"); // 모든 예외의 부모 클래스인 Exception을 받음
        }

형식은 다음과 같다.

 

try { 오류가 일어나는 실행문

         } catch ( 일어난 예외 형식) {

                             오류가 일어날시 실행될 실행문}

 

그러나 catch 지시문이 같은데도 수십개의 오류문마다 try / catch문을 일일이 적는건 수고스러운 일이다. 자바도 이를 알고 사용자를 위해서 throw 문을 만들었다.

 

 

2. throws 로 던지기

말 그대로 오류가 일어난 문장을 클래스 밖으로 던져서 처리를 미뤄버린다.

throws (처리하고자 하는 예외 형식);

처리 되지 않은 코드에서, 이미 처리된 코드로 떠넘기는 방식이다.

throw 를 이용하면 강제로 예외를 만들수도 있다.

 throw new Exception();
 강제 예외 발생

 

try  catch  finally 문

finally 는 try / catch문 다음, 마지막에 나온다. 예외가 발생하건 말건 마지막에 무조건 실행되는 수행문이다. 사용된 자원(메모리, 포트 등등)을 닫기 위한 용도로 사용한다.

public class ex104 {
    public static void main(String[] args) {
        //try catch finally문

        try{
            //예외가 발생할 수 있는 수행문
        }
        catch (Exception e) {
            //예외가 발생하면 수행하는 수행문
        }
        finally {
            //예외가 발생하든 안하든 무조건 수행하는 수행문
            //용도: 자원(메모리,IO 포트) 닫아주는 역할
        }

        try{
            System.out.println("예외 발생전...");
            //예외 강제 발생
            //throw new Exception();
        }
        catch ( Exception e ){
            System.out.println("예외가 발생함!");
            e.printStackTrace();
        }
        finally {
            System.out.println("finally문 : 정리중...");
        }

    }
}

 

public class ex101 {
    public static void main(String[] args) {
        //예외 Exception : 그외의 경우(예측하지 못한 경우의 수)
        //              : 에러,버그(Bug),오류와 비슷한 단어
        //예외 처리(Exception Handling) : 예측가능한 오류를 최대한 처리하는 것
        //try catch문 (finally문)

        //형식
        // try {
        //    예외가 발생할 수 있는 실행문   예)통신, 파일읽기/쓰기, 스레드
        // }
        // catch( 예외클래스 객체 ) {
        //    예외발생시 처리하는 실행문 - 에러내용 출력 또는 메모리 정리(close)
        // }
        String name = null; //널 : 값이 없다. 존재하는 않음, 연산 불가, 주소값없음.
        String name2 = ""; //널은 아님, 값이 비어있다. empty, 주소값있음.
        System.out.println( name );
        //NullPointerException : 널포인트 예외 발생!
        //Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "name" is null
        //at ex101.main(ex101.java:21)
        //System.out.println( name.equals("Hong") );

        //예외가 발생하면, catch()블럭으로 이동하여 수행한다.
        try {
            System.out.println( name.equals("Hong") );
            System.out.println("아랫쪽 코드...");
        }catch ( Exception e ){
            System.out.println("널포인트 에러 발생!!!");
            e.printStackTrace(); //예외발생 경로를 출력해줌.
        }

    }
}
public class ex102 {
    public static void main(String[] args) {
        //다양한 종류의 예외 처리
        try {
            Thread.sleep(1000);
            //System.out.println( 10 / 0 ); //0으로 나누는 산술오류
            int[] array = new int[3];
            array[3] = 30; //배열인덱스 오류
        }
        catch (InterruptedException e){ //인터렙트 예외발생시
            //인터렙트 : CPU의 제어를 가로채는 행위
            e.printStackTrace();
        }
        catch (ArithmeticException e){//산술처리 예외발생시
            e.printStackTrace();
        }
        catch (ArrayIndexOutOfBoundsException e){ //배열인덱스 예외발생시
            e.printStackTrace();
        }
        catch ( Exception e ){ //모든 경우의 예외처리(다형성)
            //모든 Exception이 Exception을 상속받으므로
            e.printStackTrace();
        }
    }
}
public class ex103 {
    public static void main(String[] args) {
        //예외를 처리하는 방법 2가지
        //1. try catch문을 이용하여 자신이 직접 처리하는 방법
        //2. throws문을 이용하여 자신을 호출한 함수에게 부탁(던지는)하는 방법
        try {
myFunc();
        }catch (Exception e){  }
    }
    static void myFunc() throws Exception {
        System.out.println("myFunc함수 호출됨.");
        //1. 첫번째 방법
        try {
            //System.out.println(10 / 0);
            //강제로 예외 발생시키는 코드
            //throw new Exception();
        } catch( Exception e){
            e.printStackTrace();
        }

        Thread.sleep(1000);

        //2. 두번째 방법 - throws로 던진다.
        throw new Exception();
    }
}

 

제네릭 (Generic)

형식에 따른 데이터 전송(타입선언)을 편하게 하기 위해 사용한다. 따라서 타입의 선언을 상속과 관계없이 가변적으로 할 수 있다.

<>를 사용해서 클래스 타입을 지정해준다.

호출 형식을 정한 순간 반환형도 같이 정해지니 반환 부분에는 있으니 굳이 쓸 필요는 없다.

 

기존의 다운캐스팅을 보자

//제네릭( Generic )
//     : 형(Type)에 따른 데이타전송(타입선언)을 편하기 하기 위해서
//     : 가변적인 타입의 선언을 위해서( 상속과 상관없다. )
//     : JDK 1.5버전부터 지원
//주요 JDK 버전 : 1.8(8버전)  11버전  17버전
//기술면접 : 제네릭의 기능은 무엇인가?

class Keyboard1 { // 제네릭을 사용하지 않은 설계
   
    private Object object;
    //Getter/ Setter 함수 생성
    public Object getObject() {
        return object;
    }
    public void setObject(Object object) {
        this.object = object;
    }
}
public class ex105 {
    public static void main(String[] args) {
        Keyboard1 k1 = new Keyboard1();
     
       //업캐스팅으로 String -> Object 타입으로 변경
        k1.setObject( "키보드1" ); //String은 Object를 상속받음.

        //다운캐스팅으로 Object -> String 타입으로 변경
        String str1 = (String)k1.getObject();
        System.out.println( str1 );

        //k1.setObject( new Integer(10) );
        k1.setObject( 10 ); //Integer -> Object 업캐스팅
        
        //Object -> Integer 다운캐스팅
        Integer intObj = (Integer)k1.getObject();
        System.out.println( intObj );

        //ClassCastException : 클래스타입 맞지 않아서 발생하는 예외!
       // String strObj = (String)k1.getObject();
       // System.out.println( strObj );
       }
   }

기존에는 이런식의 다운캐스팅이 있어야만 하위 클래스에 접근할 수 있었다. 자식 클래스로 직접 형변환을 해줘야만 했고, 그 관계도 한눈에 알아보기 힘들어 클래스 타입 오류가 발생하기 쉬웠다.

이제 제네릭을 사용한 설계를 보자

 

//제네릭을 사용한 클래스 설계
class Keyboard2< MyType > {
            //<MyType>은 가변타입으로 클래스타입 + 래퍼클래스타입이 다 들어감.
            //MyType은 사용자가 지정한 임시이름.
 
 private MyType object;
   // Getter/ Setter 함수 생성
    public MyType getObject() {
        return object;
    }
    
    public void setObject(MyType object) {
        this.object = object;
    }
}
public class ex105 {
    public static void main(String[] args) {
        
        Keyboard2<String> k2 = new Keyboard2<String>(); // k2, k3를 문자열형으로 전환
        Keyboard2<String> k3 = new Keyboard2<>(); //뒤쪽의 제네릭타입은 생략가능
        
        k2.setObject( "키보드2" );
        String str2 = k2.getObject();
        System.out.println( str2 );

        k3.setObject( "키보드3" );
        String str3 = k3.getObject();
        System.out.println( str3 );

        Keyboard2<Integer> k4 = new Keyboard2<>();
        k4.setObject( 30 );  // k4를 정수형으로 전환하고 30을 set했다
        Integer myInt2 = k4.getObject();
        System.out.println( myInt2 );
    }
}

제네릭을 사용하는 가장 큰 장점은 Object 를 사용한 다형성이 강력한 강점인 자바에서 형변환이 쉽고 헷갈리지 않게 된다는데 있다.

//제네릭( Generic )
//     : 형(Type)에 따른 데이타전송(타입선언)을 편하기 하기 위해서
//     : 가변적인 타입의 선언을 위해서( 상속과 상관없다. )
//     : JDK 1.5버전부터 지원
//주요 JDK 버전 : 1.8(8버전)  11버전  17버전
//기술면접 : 제네릭의 기능은 무엇인가?

class Keyboard1 {
    // Object
    //   : 모든 타입의 데이타를 담을 수 있음.(다형성)
    //   : 단점) 다운캐스팅을 꼭 이용해야 하위 클래스에 접근 가능
    private Object object;
    //Getter/Setter 자동생성
    public Object getObject() {
        return object;
    }
    public void setObject(Object object) {
        this.object = object;
    }
}
//제네릭을 사용한 클래스 설계
class Keyboard2< MyType > {
            //<MyType>은 가변타입으로 클래스타입 + 래퍼클래스타입이 다 들어감.
            //MyType은 개발자가 지정한 임시이름.
    private MyType object;

    public MyType getObject() {
        return object;
    }

    public void setObject(MyType object) {
        this.object = object;
    }
}

public class ex105 {
    public static void main(String[] args) {
        Keyboard1 k1 = new Keyboard1();
        //업캐스팅으로 String -> Object 타입으로 변경
        k1.setObject( "키보드1" ); //String은 Object를 상속받음.
        //다운캐스팅으로 Object -> String 타입으로 변경
        String str1 = (String)k1.getObject();
        System.out.println( str1 );

        //k1.setObject( new Integer(10) );
        k1.setObject( 10 ); //Integer -> Object 업캐스팅
        //Object -> Integer 다운캐스팅
        Integer intObj = (Integer)k1.getObject();
        System.out.println( intObj );

        //ClassCastException : 클래스타입 맞지 않아서 발생하는 예외!
       // String strObj = (String)k1.getObject();
       // System.out.println( strObj );

        Keyboard2<String> k2 = new Keyboard2<String>();
        Keyboard2<String> k3 = new Keyboard2<>(); //뒤쪽의 제네릭타입은 생략가능
        k2.setObject( "키보드2" );
        String str2 = k2.getObject();
        System.out.println( str2 );

        k3.setObject( "키보드3" );
        String str3 = k3.getObject();
        System.out.println( str3 );

        Keyboard2<Integer> k4 = new Keyboard2<>();
        k4.setObject( 30 );
        Integer myInt2 = k4.getObject();
        System.out.println( myInt2 );
    }
}

 

람다식

코드를 변수형태로 담아서 전달(매개변수화) 하기 위해 사용한다.

솔직히 너무 복잡하고 가독성도 별로인것 같다.

그냥 이런게 있다는 것만  알아두자.

->가 나오면 람다식이다.

//람다식( Lambda Expression )
//   : JDK 1.8부터 지원하기 시작
//   : 일반 변수는 값을 담는다. 값변수:실제값, 참조변수:주소값
//   : 함수형 변수 = 코드를 담는다. 함수:코드의 선언/호출
//   : 3세대 언어인 JS, 코틀린, 스위프트, Go 언어들에서는 함수형 변수를 지원.
//   : 자바에서 코드를 변수형태로 담아서 전달(매개변수)하기 위해 새롭게 설계.
//   : 억지로 인터페이스 문법을 차용하여 사용한다.
//   : 자바는 클래스와 객체에 변수+함수코드 담고 있기 때문에, 객체를 전달하면
//      코드전달을 할 수 있기에, 람다식은 그다지 유용하지 않다.

//람다식 선언 : 함수형 인터페이스 형태로 선언
//      구현 : -> 화살표연산자를 이용

// @FunctionalInterface : 람다식 선언시에만 사용하는 어노테이션(컴파일 지시어)
@FunctionalInterface
interface MyFunc1 {
    int calc(int x, int y); //가상함수
}
@FunctionalInterface
interface MyFunc2 {
    int calc(int x); //가상함수
}
@FunctionalInterface
interface MyFunc3 {
    void calc(); //가상함수
}

interface MyInterface {
    void paint();
}
public class ex106 {
    public static void main(String[] args) {
        //인터페이스 구현 익명 객체
        MyInterface i1 = new MyInterface() {
            @Override
            public void paint() {
                System.out.println("그림 그린다.");
            }
        };
        i1.paint();
        //형식
        //인터페이스명 객체명 = ( 매개변수1, 매개변수2 ) -> { 코드 };
        MyFunc1 f1 = ( x, y ) -> { return x+y; };
        System.out.println( f1.calc(10,20) );
        //f1은 람다식 구현객체 = 코드를 담고 있는 변수 => 매개변수 전달가능.

        //코드를 변수에 담아서 전달하고 싶다. 비동기적 처리를 위해서.
execFunc(f1);

        MyFunc2 f2 = ( x ) -> { return x*x; };
        System.out.println( f2.calc(3) );

        MyFunc3 f3 = ( ) -> { System.out.println("hello"); };
        f3.calc();


        //JS의 함수형 변수 예)
        //<script>
        //function sum(a,b) {
        // var result = a+b;
        // return result;
        //}
        //
        //var fn = sum; //함수 자체를 fn 변수에 담음 (자료형: function)
        //console.log(fn(3,4)); //7
        //
        //</script>
    }
    static void execFunc( MyFunc1 f1 ){
        System.out.println( f1.calc(30,40) );
    }
}

 

시간 표현

Date 클래스

라이브러리에서 import 해서 사용해야 한다.

import java.util.Date;

public class ex107 {
    public static void main(String[] args) {
        //날짜와 시간 관련된 클래스
        //Date, Calendar 클래스 사용

        //인간이 살아가는 주배경
        //1. 시간 - 년월일시분초밀리초, 정수값(timestamp 1970-1-1 0:0:0)
        //         2022년11월30일16시10분5초023초
        //2. 장소 - 행정주소(서울시 마포구 신촌동), GPS좌표(위도,경도 double값)

        //현재시간을 운영체제(OS - 윈도우즈10 home)에서 가져온다.
        Date date = new Date();
        System.out.println( date );

        //타임스탬프 정수값
        long timestamp = date.getTime();
        System.out.println( "타임스탬프:" + timestamp);
    }
}

'공부 > java' 카테고리의 다른 글

15일차 복습  (0) 2022.12.04
14일차 복습  (0) 2022.12.01
자바(java)의 객체의 다형성  (0) 2022.11.29
자바(java)의 클래스  (1) 2022.11.28
자바(java)의 함수 종류  (0) 2022.11.25