Java 기본 문법

방혁·2024년 1월 20일

Java

목록 보기
1/4

1. 자바 기본

Variable이란?

  • 자료를 저장하기 위한 메모리 공간으로 타입에 따라 크기가 달라짐
  • 메모리 공간에 값을 할당 후 사용

Type이란?

  • 데이터 타입에 따른 데이터의 종류
기본형참조형
미리 정해진 크기의 데이터 표현크기가 미리 정해질 수 없는 데이터의 표현
변수 자체에 값 저장변수에는 실제 값을 참조할 수 있는 주소만 저장

기본형의 갯수(8개)
논리형(Boolean)
정수형(byte, short, int, long(끝에L))
실수형(float(끝에 F), double)
문자형(char)
Q. byte는 8비트인데 2^7까지만 처리하는 이유?
A. 맨 앞 비트는 부호비트 !

다음 코드의 실행 결과?

public static void main(String[] args) {
	int i1 = Integer.MAX_VALUE;
    int i2 = i1 + 1;
    System.out.println(i2);
}

-> overflow발생 ! (정수 계산 시 주의)
따라서, -2147483648가 출력

public static void main(String[] args) {
	float f1 = 2.0f
    float f2 = 1.1f
    float f3 = f1 - f2;
    System.out.println(f3);
    
    double d1 = 2.0;
    double d2 = 1.1;
    double d3 = d1 - d2;
    System.out.println(d3)
    
        // 정확한 값 계산하기
    System.out.println(((int) (d1 * 100) - (int) (d2 * 100)) / 100.0);
    BigDecimal b1 = new BigDecimal("2.0");
    BigDecimal b2 = new BigDecimal("1.1");
    System.out.println("BigDecimal을 이용한 빼기 : " + b1.subtract(b2));
}

-> 실수의 연산은 정확하지 않다. - 유효 자리수를 이용한 반올림 처리

형변환

형변환이란?

  • 변수의 형을 다른 형으로 변환하는 것
  • primitice는 primitive끼리, reference는 reference끼리
    • 기본형과 참조형의 형 변환을 위해서는 Wrapper클래스 사용 !
    • 총 8개

형 변환 방법

  • 묵시적 형 변환 : 형 변환 연산자(괄호)사용
    • 값 손실 주의
  • 명시적 형 변환

타입의 표현 범위가 커지는 방향으로 할당할 경우는 묵시적 형 변환 발생
ex) long(64비트) -> float(32비트)
추가로 short(16비트) <-> char(16비트)는 불가
why? short는 부호비트를 사용하지만 char는 모든 비트를 사용하므로

public class Main {
    public static void main(String[] args) {
        int i1 = Integer.MAX_VALUE;
        int i2 = i1 + 1;		// overflow
        System.out.println(i2);	// -2147483648

        long l1 = i1 + 1;		// overflow
        System.out.println(l1);	// -2147483648

        long l2 = (long) (i1 + 1);	// overflow 먼저 계산하므로
        System.out.println(l2);		// -2147483648

        long l3 = (long) i1 + 1;	
        System.out.println(l3);		// 2147483648

        int i3 = 1000000 * 1000000 / 100000;	// 깨지고 나눔
        int i4 = 1000000 / 100000 * 100000;	
        System.out.println(i3 + " : " + i4);	// -7273 : 1000000
    }
}
public class Main {

    public static void main(String[] args) {
        byte b1 = 10;
        byte b2 = 20;
        byte b3 = b1 + b2;	// 에러발생 int이하이므로

        int i1 = 10;
        long l1 = 20;		// 자동 형변환
        int i2 = i1 + l1;	// 큰 타입 long으로

        float f1 = 10.0;		// 기본 double이므로 F로 !
        float f2 = f1 + 20.0;	// 큰 타입 double로
    }
}
  • 자바에서는 연산 전에 피 연산자의 타입을 일치시킨다.
  • 피연산자의 크기가 int(4바이트)미만이면 int로 변경한 후 연산 진행
  • 두 개의 피 연산자 중 큰 타입으로 형 변환 후 연산 진행
public class Main {
    public static void main(String[] args) {

        int a = 10;
        int b = 20;
        System.out.println((a > b) & (b > 0));	// false

        System.out.println((a += 10) > 15 | (b -= 10) > 15);	// true
        System.out.println("a = " + a + ", b = " + b);	// 20, 10

        a = 10;
        b = 20;
        System.out.println((a += 10) > 15 || (b -= 10) > 15);	// true
        System.out.println("a = " + a + ", b = " + b);	// 20, 20
    }
}

why? ||연산은 앞이 true이면 뒤의 연산을 실행하지않음. but |연산은 두개의 연산 모두 실행.

조건문

  1. if문에 들어갈 수 있는 type?
    boolean, Boolean, boolean getResult()
  2. switch문에 들어갈 수 있는 type?
    byte, short, char, int, String, int getNumber()
    - long타입은 안됨. 또한 정수형의 모든 타입 x
public class Main {
    public static void main(String[] args) {
        int num = 3;

        switch (num) {
        case 1:
            System.out.println(num);
        case 2:
            System.out.println(num);
        case 3:
            System.out.println(num);	// 실행
        case 4:
            System.out.println(num);	// 실행
        case 5:
            break;						// 중단
        case 6:
            break;
        default:
            System.out.println(num);
        }

        int month = 3;
        int day = -1;
        switch (month) {
        case 2:
            day = 29;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        default:
            day = 31;
            break;
        }
        System.out.printf("%d월은 %d까지 있다.%n", month, day);
    }
}

반복문(for, while)

반복문의 4가지 구성요소

  • 변수 초기화
  • 반복 조건
  • 증감식
  • 실행문
public static void byFor() {
        int sum = 0;
        int cnt = 100;
        double avg = 0;
        Random rand = new Random();
		for (int i = 0; i < cnt; i++) {
        	sum += rand.nextInt(6) + 1;
        }
    }
public static void byWhile() {
        int sum = 0;
        int cnt = 100;
        double avg = 0;
        Random rand = new Random();
        
        int i = 0;
		while (i < cnt) {
        	sum += rand.nextInt(6) + 1;
            i++;
        }
    }

2. 배열, 다차원 배열

배열

배열이란 ? 동일한 타입의 데이터 0개 이상을 하나의 연속된 메모리 공간에서 관리하는 것

Array만들기#1

타입[] 변수명; or 타입 변수명[]
ex) int a; int[] arr
- a의 타입 ? int
- arr의 타입 ? int[] (참조형 타입)
- arr이 저장하는 데이터의 타입 ? int

배열의 생성과 초기화

  • new 키워드와 함께 저장하려는 데이터의 타입 및 길이 지정
  • 배열의 생성과 동시에 저장 대상 자료형에 대한 기본값으로 default초기화 진행
  • 메모리의 연속된 공간 차지 -> 크기 변경 불가 !!
  • 자료형기본값
    booleanfalse
    char공백문자
    byte, short, int0
    long0L
    flaot0.0f
    double0.0
    참조형 변수null

출력을 편하게 하는 법
Arrays.toString()

String org = "Hello";
char[] chars = new char[org.length()];
for (int i = 0; i < chars.length; i++) {
	chars[i] = org.charAt(i);
}
for (int i = 0; i < chars.length; i++) {
	System.out.print(chars[i]);
}

// -> API
chars = org.toCharArray();
for (int i = 0; i < chars.length; i++) {
	System.out.print(chars[i]);
}

Array만들기#2

  • 생성과 동시에 할당한 값으로 초기화
    - int[] a = new int[] {1,2,3,4,5};
    - int[] b = {1,2,3,4,5};
  • 선언과 생성을 따로 처리할 경우 초기화 주의
    - int[] c; c = {1,2,3,4,5}; // 컴파일 오류
    - 꼭 new를 사용 즉, int[] c; c = new int[]{1,2,3,4,5};로 사용

for-each

  • 가독성이 개선된 반복문으로, 배열 및 Collections에서 사용
for (int i : arr) {
	//~~~
}

Array는 변경불가 !

  • 배열은 최초 메모리 할당이후, 변경할 수 없음
  • 배열이 바뀌는 것이 아니라 새로운 배열을 선언하고 참조하는 것.
public static void main(String[] args) {
        int[] scores = { 90, 80, 100 };

        // TODO: 95점을 추가로 관리하기 부적절한 코드는?
        // scores[3] = 95; // #1

        // scores = new int[] {90, 80, 100, 95}; // #2

        // scores = {90, 80,100, 95 }; // #3

        // scores = Arrays.copyOf(scores, 5); // #4
        // scores[3]=95;

        // int[] scores2 = new int[4]; // #5
        // System.arraycopy(scores, 0, scores2, 0, scores.length);
        // scores2[3] = 95;

    }

->
1: 넘치는 idex
3: new int[] 선언

2차원 배열

  1. 2차원 배열 만들기#1
  • int[][] intArray;
  • int intArray[][];
  • int[] intArray[];
    2차원 배열은 1차원 배열을 저장하는 배열이다.
  1. 2차원 배열 만들기#2
  • 선언과 생성, 할당을 동시에
  • int[][] intArray = {{0, 1, 2}, {0, 1, 2}, {0, 1, 2}};
  1. 2차원 배열 만들기#3
  • 4x? 배열 만들기
  • int[][] intArray = new int[4][]
profile
반갑습니다 👋

0개의 댓글