Java_문법뽀개기 01

5w31892p·2022년 11월 14일
0

Java

목록 보기
1/17

📜 Java

✍ 자바 문법 뽀개기

Java란? 객체 지향적 프로그래밍 언어

:: 변수와 상수

  • 변수

    • 어떠한 데이터를 저장하기 위한 메모리 공간
    • 지속적으로 변수의 값 변경 가능
    • 변수 선언 : [접근제어자][변수자료형] [변수명] = [값]
    • 접근제어자는 있을 수도 없을 수도 있음
  • 상수

    • 중간에 값을 변경할 수 없으며 초기 값을 끝까지 사용해야 함
public class Main {
    public static void main(String[] args) {

        int number = 5; // 정수형 변수 선언
        System.out.println(number);

        String sparta = "Hello Sparta!"; // 문자형 변수 선언
        System.out.println(sparta);

        final int finalNumber = 1; // 상수 선언
        System.out.println(finalNumber);
        // final(접근제어자) int(변수의 자료명) finalNumber(변수명)
        // 접근제어자는 있을 수도 있고, 없을 수도 있음
        
        finalNumber = 2; 
		System.out.println(finalNumber); // error(상수는 값을 변경할 수 없기 때문)

		sparta =Good bye Sparta!// 변수 재할당
		System.out.println(sparta);
	}
}

Java에서는 변수명을 적을 때 캐멀케이스 형식으로 적음

  • 캐멀케이스란?
    낙타의 등 모양을 한다는 의미로 첫문자는 소문자, 그 다음 의미 단어 첫글자는 대문자
    ex) finalNumber

:: 자료형의 종류

1. 기본 자료형 (Primitive Type)

  1. 숫자형

    • short : 2바이트 표현
    • int : 4바이트 표현
    • long : 8바이트 표현
    • float : 실수, 실수 뒤 F 붙혀야 표현 가능
    • double : float보다 더 큰 표현
  2. 문자형

    • char : 글자 하나만 표현, 여러개 담을 수 없음
  3. 논리형

    • boolean : true or false 만 가져올 수 있음
  4. 바이트

    • 모든 데이터는 바이트로 표현 가능
public class Main {
    public static void main(String[] args) {
    
        short s = 1;
        System.out.println(s); // 1
        System.out.println(Short.MAX_VALUE);  // 32767
        System.out.println(Short.MIN_VALUE); // -32767

        int a = 3;
        System.out.println(a); // 3
        System.out.println(Integer.MAX_VALUE); // 2147483647
        System.out.println(Integer.MIN_VALUE); // -2147483647

        long b = 4;
        System.out.println(b); // 4
        System.out.println(Long.MAX_VALUE); // 9223372036854775807
        System.out.println(Long.MIN_VALUE); // -9223372036854775807

        float f = 5.5F; or  float f = (float) 2.1;
        System.out.println(f); // 5.5
        System.out.println(Float.MAX_VALUE); // 3.4028235E38
        System.out.println(Float.MIN_VALUE); // 1.4E-45

        double d = 5.5;
        System.out.println(d); // 5.5
        System.out.println(Double.MAX_VALUE); // 1.7976931348623157E308
        System.out.println(Double.MIN_VALUE); // 4.9E-324 
        
        char c= 'A';
        System.out.println(c);

        boolean fact = true;
        fact = false;
        System.out.println(fact);

        byte date = 'd';
        System.out.println(date); // 알파벳 d는 ASCII code 에서 십진법으로 100
    }
}

2. 참조 자료형 (Reference Type)

  • 자바의 인스턴스 객체를 가르킬 수 있는 자료형
  • 클래스로 정의된 타입을 사용
public class Main {
    public static void main(String[] args) {
    
        String sparta = "Hello sparta!";
        System.out.println(sparta);
        // Ctrl 누르고 String 누르면 String이 선언된 구현체로 넘어감

        int[] intArray = new int[] {1,2,3,4,5};
        System.out.println(Arrays.toString(intArray)); 
        //  System.out.println(intArray); 치고 alt + Enter
    }
}

3. 배열

자료형[] 변수 = new 자료형[배열의 크기]
  • 동일한 자료형의 데이터를 연속된 공간에 저장하기 위한 자료구조
  • 인덱스는 0부터 시작
  • 배열은 선언만 하고, 초기화를 하지 않으면 해당하는 타입의 초기화되는 값을 디폴트값을 가져옴
  • 마지막 값 출력 : 배열은 인덱스 번호를 0부터 세기 때문에 -1을 해줘야함
public class Main {
    public static void main(String[] args) {
    
        int[] intEmptyArray = new int[5]; // int의 5자리 배열 선언
        intEmptyArray[0] = 7; // 인덱스 통해 배열에 값 입력
        intEmptyArray[1] = 5;
        System.out.println(Arrays.toString(intEmptyArray)); // 값 입력이 없다면 int의 default 값 0으로 채워짐

        int[] intArray = new int[]{1, 2, 3, 4, 5}; // int 배열을 선언과 동시에 초기화
        System.out.println(Arrays.toString(intArray));

        String[] stringEmptyArray = new String[5]; // 참조자료형 String의 5자리 배열 선언
        System.out.println(Arrays.toString(stringEmptyArray)); // 참조자료형은 값이 없을 경우 null로 표시

        String[] season = {"봄", "여름", "가을", "겨울"};
        System.out.println(Arrays.toString(season));

        String[] months = {"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"};
        System.out.println(Arrays.toString(months));
        System.out.println(months[7]); // 8월

        System.out.println(season[season.length -1]); // 겨울
        // 마지막 값 출력, 배열은 인데스 번호를 0부터 세기 때문에 -1을 해줘야함

        int[][] arr = new int[4][3]; // 2차원적 배열 생성가능 
        System.out.println(Arrays.deepToString(arr)); // [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
    }
}

1. 문자 변수 'S' , 정수형 변수 10 를 선언 및 출력
2. 크기가 3인 정수형 배열 선언 및 주어진 숫자 할당 (10, 20, 30)
3. 배열의 마지막 값 출력

public class Main {
    public static void main(String[] args) {
    
        char a = 'S'; // 쌍따옴표안됨
        int b = 10;
        System.out.println(a);
        System.out.println(b);
        System.out.println(a + "" + b); // S10 이어져서 나옴
        System.out.println(a + "\n" +b); // \n : 줄바꿈
        
        int[] c = new int[] {10, 20, 30};
        System.out.println(Arrays.toString(c)); // alt + enter
        System.out.println(c[c.length -1]);
    }
}

:: 연산자

수식을 계산 및 비교하는 기호

1. 산술 연산자

public class Main {
    public static void main(String[] args) {
    
        int num1 = 10;
        int num2 = 5;

        System.out.println(num1+num2); // 15
        System.out.println(num1-num2); // 10
        System.out.println(num1*num2); // 50
        System.out.println(num1/num2); // 2
        System.out.println(num1%num2); // 0
    }
}

2. 대입 연산자

public class Main {
    public static void main(String[] args) {
    
        int num1 = 10;
        int num2 = 5;
        System.out.println(num1); // 10

        num1 += num2;
        System.out.println(num1); // 15

        num1 -= num2;
        System.out.println(num1); // 10

        num1 *= num2;
        System.out.println(num1); // 50

        num1 /= num2;
        System.out.println(num1); // 10

        num1 %= num2;
        System.out.println(num1); // 0
    }
}

3. 관계 연산자

public class Main {
    public static void main(String[] args) {
    
        int num1 = 10;
        int num2 = 5;
        int num3 = 10;

        System.out.println(num1 > num2); // true
        System.out.println(num1 >= num3); // true
        System.out.println(num1 < num2); // false
        System.out.println(num1 < num3); // false
        System.out.println(num1 == num3); // true
        System.out.println(num1 != num2); // true
    }
}

4. 논리 연산자

  • && : and
  • || : or
  • ! : not
public class Main {
    public static void main(String[] args) {
    
        boolean a = true;
        boolean b = false;
        System.out.println(a && b); // false // a그리고 b 둘다  true면 true, 둘중 하나라도 ture 가 아니라면 false
        System.out.println(a || b); // true // 둘중 하나라도 true면 true
        System.out.println(!b); // true 
    }
}

1. 출력 결과 추측

public class Main {
    public static void main(String[] args) {
    
        int num1 = 10;
        int num2 = 3;
        boolean bool1 = true;
        boolean bool2 = false;
        num1 += num1; // 10+10
        num2 *= num1; // 3*20 (위에서 num1이 20으로 정의됐으므로)
        System.out.println(num1); // 20
        System.out.println(num2); // 60
        System.out.println(bool1 && bool2); // false
    }
}

:: 조건문

1. if문

public class Main {
    public static void main(String[] args) {
    
        int check = 100;
        int num1 = 51;
        if (num1 > check) {
            System.out.println("100보다 큰 수 입니다.");
        } else if (num1 > 50){
            System.out.println("50보다 작은 수 이고, 100보다 작거나 같습니다.");
        }
    }
}

2. switch문

  • 미리 계층적으로 선언
  • break 안하면 다음 case 실행됨
  • break는 해당되는 case 실행 후, switch문 밖으로 나가게 해주는 역할
public class Main {
    public static void main(String[] args) {
    
        char score = 'A';
        switch (score) {
            case 'A':
                System.out.println("A등급");
                break;
            case 'B':
                System.out.println("B등급");
                break;
            case 'C':
                System.out.println("C등급");
            default:
                System.out.println("C보다 아래 등급");
        }
    }
}

3. 삼항 연산자

  • ? 기준
public class Main {
    public static void main(String[] args) {
        // write your code here
        int a = 5;
        String result = (a < 10) ? "10보다 작음" : "10보다 큼";
        // (a < 10)에서 괄호는 없어도 됨
        System.out.println(result);
    }
}

1. 100~91: A등급 , 90~81: B등급 , 80~71: C등급 , 그 외의 점수 : F등급

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int score = sc.nextInt();
        
        if (score<=100 && score >90) {
            System.out.println("A등급");
        } else if (score<=90 && score > 80) {
            System.out.println("B등급");
        } else if (score<=80 && score > 70) {
            System.out.println("C등급");
        } else {
            System.out.println("F등급");
        }
    }
}

:: 반복문

1. for문

public class Main {
    public static void main(String[] args) {
    
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            sum += (i + 1);
        }
        System.out.println(sum); // 55
    }
}

2. for-each문

  • 배열의 값들을 하나하나 변수에 담아서 출력
public class Main {
    public static void main(String[] args) {
    
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        for (String day : days) {
            System.out.println(day); // 순서대로 쫘락 나옴
        }
    }
}

3. while문

  • i+=1; 코드가 없다면 벗어나지 못하고 계속 반복 = 무한 루프
public class Main {
    public static void main(String[] args) {
    
        int i = 0;
        int sum = 0;
        while (i < 10) {
            sum += i + 1;
            i += 1;
        }
        System.out.println(sum); // 55
    }
}

  • break : 중간에 빠져 나오고 싶을 때 사용
public class Main {
    public static void main(String[] args) {
    
        int i = 0;
        int sum = 0;
        while (i < 10) {
            sum += (i + 1);
            i++;
            if (i == 5) {
                break;
            }
        }
        System.out.println(sum); // 15 1~5까지만 더한 값
    }
}

  • continue : 해당 하는 것만 빼고 더하고 싶을 때
public class Main {
    public static void main(String[] args) {
    
        int i = 0;
        int sum = 0;
        while (i < 10) {
            if (i == 4) {
                i++;
                continue; // 나를 감싸고 있는 반복문 밑 부분 한번 스킵하고 진행하라는 의미

            }
            sum += (i + 1);
            i++;
        }
        System.out.println(sum); // 50 5만 제외하고 더한 수
    }
}

4. do-while문

  • 조건 확인하지 않고 수행 먼저
public class Main {
    public static void main(String[] args) {
    
        int i = 0;
        int sum = 0;

        do {
            sum += (i + 1);
            i++;
        } while (i < 10);
        System.out.println(sum); // 55
    }
}

1. 1부터 100까지의 합

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += (i+1);
        }
        System.out.println(sum);
    }

2. 5초부터 시작하는 카운트다운

public class Main {
    public static void main(String[] args) {
        for (int i =5; i >= 0; i--) {
            System.out.println("카운트 다운 : " + i );
        }
    }
}

3. 1부터 30까지 홀수의 합과 짝수의 합 각각 출력

public class Main {
    public static void main(String[] args) {
        int sumOdd = 0;
        int sumEven = 0;
        for (int i = 0; i < 30; i++) {
            int value = i + 1;
            if (value % 2 == 0) {
                sumEven += value;
            } else {
                sumOdd += value;
            }
        }
        System.out.println("odd : " + sumOdd);
        System.out.println("even : " + sumEven);
    }
}

:: 객체지향언어

1. 클래스, 인스턴스, 메소드

  1. 클래스

    • 붕어빵 틀
    • 어떤 속성을 갖는지, 어떤 모양을 갖는지 정해져 있음
    • 클래스 내부 정보 : 멤버 변수
  2. 인스턴스

    • 틀을 통해 만들어진 실제 붕어빵
    • 클래스로부터 만들어진 객체
    • 한입 베어 먹은 것처럼 생성되고나면 그 자체의 상태를 가지고 그 자체로 변화됨
    • 멤버변수 접근할 때 : [생성된 인스턴스.멤버변수]
class Phone {
    String model;
    String color;
    int price;
}
// 붕어빵 틀

public class Main {
    public static void main(String[] args) {
        Phone galaxy = new Phone();
        galaxy.model = "Galaxy10"; // 선언한 이름 뒤에 .멤버변수에 해당하는 변수 선언
        galaxy.color = "Black"; // 이렇게 =을 하면 값을 할당하는 것이고,
        galaxy.price = 100;

        Phone iphone =new Phone();
        iphone.model = "iPhoneX";
        iphone.color = "Black";
        iphone.price = 200;


        System.out.println("철수는 이번에 " + galaxy.model + galaxy.color + " + 색상을 " + galaxy.price + "만원에 샀다."); 
        System.out.println("영희는 이번에 " + iphone.model + iphone.color + " + 색상을 " + iphone.price + "만원에 샀다.");
        // 값을 호출 하는 것
    }
}
  1. 메소드

    • 어떤 작업을 수행하는 코드를 하나로 묶은 것

    • 메소드 필요한 이유 : 재사용성 || 중복된 코드 제거 || 프로그램 구조화

    • 메소드 선언시 암묵적 룰 : 동사로 시작 || 카멜케이스로 시작

      class Phone {
          String model;
          String color;
          int price;
      }
      
      public class Main {
          public static void main(String[] args) {
              int[] heights = new int[]{10, 20, 30, 40, 50};
      
              initHeight(heights); // 1. 키에 대한 초기화
              sortHeight(heights); // 2. 키를 오름차순으로 정렬
              printHeight(heights); // 3. 정렬된 키를 출력
          }
          int add (int x, int y) { 
          // 괄호 안을 parameter 라고 함
          //파라미터는 내가 원하는 만큼 선언해서 쓸 수 있음
          // (타입 변수이름, 타입 변수이름) 이렇게 선언
            return x + y ;
        }
        int minus (int x, int y) { // 위 x,y 와는 상관없음
            return x - y;
        }
      }
      class Calculation {
          int add(int x, int y) {
              return x + y;
          }
          int subtract(int x, int y) {
              return x - y;
          }
      }
      
      public class Main {
          public static void main(String[] args) {
              Calculation calculation = new Calculation();
              int addResult = calculation.add(1, 2);
              int subResult = calculation.subtract(5,3);
              System.out.println(addResult); // 3
              System.out.println(subResult); // 2
          }
      }
      

2. 생성자

클래스이름 (타입 변수명, 타입 변수명, ...){
    인스턴스 생성 될 때에 수행하여할 코드
    변수의 초기화 코드
}
  • new를 통해 인스턴스가 생성될 때 사용되는 인스턴스 초기화 메소드
  • new를 할 때만 불림
  • 생성자 이름은 클래스의 이름과 같아야 함
  • 리턴 값 없음
  • this는 생성된 객체 자신
  • 생성자의 매개변수의 값을 객체에 해당하는 데이터에 넣어줌
class Phone {
    String model;
    String color;
    int price;

    public Phone(String model, String color, int price) { // Alt + ins
        this.model = model;
        this.color = color;
        this.price = price;
    }
}

public class Main {
    public static void main(String[] args) {
        Phone galaxy = new Phone("galaxy", "black", 100);
        Phone iphone =new Phone("iphone", "black", 200);

        System.out.println("철수는 이번에 " + galaxy.model + galaxy.color + " + 색상을 " + galaxy.price + "만원에 샀다.");
        System.out.println("영희는 이번에 " + iphone.model + iphone.color + " + 색상을 " + iphone.price + "만원에 샀다.");
    }
}

3. 상속

  • 오직 하나의 클래스만 상속 받을 수 있음
  • 기존 클래스의 재사용 방식 중 하나
  • 특징
    • 부모클래스에서 정의된 필드, 메소드 물려받음
    • 새로운 필드, 메소드 추가 가능
    • 부모 클래스에서 물려받은 메소드 수정 가능 (overriding)
  • 형식
    • 상속은 extends를 이용하여 사용
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class Animal {
    String name;

    public void cry() {
        System.out.println(name + " is crying.");
    }
}

class Dog extends Animal {

    Dog(String name) {
        this.name = name;
    }

    public void swim() {
        System.out.println(name + " is swimming!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("코코");
        dog.cry();
        dog.swim();

        Animal dog2 = new Dog("미미");
        dog2.cry();
//        dog2.swim(); // compile error : swim은 자식타입에 있는 함수이기 때문
    }
}

4. 오버로딩(overloading) 과 오버라이딩(overriding)

  1. 오버로딩 : 한 클래스 내 동일한 이름의 메소드 여러 개 정의
    • 조건 : 메소드 이름 동일 || 매개변수 개수 혹은 타입 달라야함
1. 리턴타입만 다르고 자료형과 개수가 같은 것 오버로딩 아님
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    long add(int a, int b, int c) {
        return a + b + c;
    }
}

2. 이름 같고,  매개변수의 개수가 다름 오버로딩
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    int add(int a, int b) {
        return a + b;
    }
}

3. 개수는 같은데 타입이 다른 경우 오버로딩
public class Main {
    public static void main(String[] args) {
    }

    int add(int x, int y, int z) {
        return x + y + z;
    }
    long add(int a, int b, long c) {
        return a + b + c;
    }
}
  1. 오버라이딩 : 부모로부터 받은 메소드 내용 변경하는 것
    • 조건 : 부모와 메스도명 같아야함 || 부모 메소드와 매개변수, 반환타입 같아야함
class Animal {
    String name;
    String color;

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

    public void cry() {
        System.out.println(name + " is crying");
    }
}

class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

    @Override
    public void cry() {
        System.out.println(name + " is barking!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog("코코");
        dog.cry();
    }
}

// 코코 is barking!


:: ✍ 정리

  • short, int, long, float, double
  • char : 작은따옴표
  • boolean : 진실 혹은 거짓
  • 배열 : 자료형[] 변수 = new 자료형[배열의 크기]
  • % : 나누고 난 나머지
  • a += b : a = a+b
  • != : 같지않음 / == : 같음
  • && : and
  • || : or
  • ! : not
  • if문
if (조건식){
    실행 코드
} else if (조건식) {
	실행 코드
}
  • switch문
switch (입력 변수){
    case 입력값1 : 실행 구문
        break;
    case 입력값2 : 실행 구문
        break;
    case 입력값3 : 실행 구문
        break;
    default: 기본 실행 구문
        break;
}
  • 삼항 연상자
(조건식) ? A : B
  • for문
for(초기값 ; 조건식 ; 증감식){ // (i = 0; i < 10; i++)
    실행 코드 블럭
}
  • while문
while(조건식){
    실행 코드 블럭
}
  • 클래스 : 붕어빵 틀
  • 인스턴스 : 만들어진 붕어빵
  • 메소드 : 작업을 수행하는 코드를 하나로 묶은 것
  • 생성자 : 인스턴스 초기화 메소드
  • 상속 : 오직 하나의 클래스만 상속
  • 오버로딩 : 기존에 없는 새로운 메소드를 정의하는 것
  • 오버라이딩 : 상속받은 메소드의 내용을 변경하는 것

0개의 댓글