자바 Day 2

Hyunsu·2023년 3월 21일
0

Today I Learned

목록 보기
2/37
post-thumbnail

오늘은 Chapter 3 객체부터 Chapter 6 조건문까지 복습을 했다.
한 번 공부했었던 내용이라 빠르게 복습할 수 있었다.

📝 목차

  1. 클래스와 객체
  2. 변수와 자료형
  3. 연산자
  4. 조건문과 반복문

1. 클래스와 객체

클래스는 변수와 메서드와 생성자로 이루어져있다.

public class Car {
	// [1] 변수
	int speed; // 주행 속도
    int distance; // 주행 거리
    String color; // 자동차 색상
    
    // [2] 생성자
    public Car() { }
    
    // [3] 메서드
    public void speedUp() { // 속도 증가
    	speed += 5;
    } 
    
    public void breakDown() { // 속도 감소
    	speed -= 10;
    } 
    
    public int getSpeed() { // getter
    	return speed;
    }
    
    public void setSpeed(int speed) { // setter
    	this.speed = speed;
    }
}

클래스와 객체는 서로 다른 개념이다. 클래스는 설계도라고 할 수 있고 객체는 실제 사물을 나타내기 위한 것이다. 아래는 Car 클래스를 통해서 객체를 생성한 것이다.

public class CarManager {
	public static void main(String[] args) {
    	Car dogCar = new Car(); // 개똥이 차 객체 생성
        dogCar.speedUp();
        dogCar.speedUp();
        System.out.println(dogCar.getSpeed()); // speed == 10
        dogCar.breakDown();
        System.out.println(dogCar.getSpeed()); // speed == 0
    }
}

2. 변수와 자료형

📌 변수의 종류

  • 지역변수 : 중괄호 내에서 선언된 변수
  • 매개변수 : 메소드에 넘겨주는 변수
  • 인스턴스 변수 : 메소드 밖에 클래스 안에 선언된 static 이 붙지 않은 변수
  • 클래스 변수 : 메소드 밖에 클래스 안에 선언된 static 이 붙은 변수
public class VariableTypes {
	int instanceVariable;
    static int classVariable;
    public void method(int parameter) {
    	int localVariable;
    }
}

각 변수의 생명 주기는 다음과 같다.

  • 지역변수 : 지역 변수를 선언한 중괄호 내에서만 유효
  • 매개변수 : 메소드가 호출될 때 생명이 시작되고 메소드가 끝나면 소멸
  • 인스턴스 변수 : 객체가 생성될 때 생명이 시작되고 그 객체를 참조하고 있는 다른 객체가 없으면 소멸
  • 클래스 변수 : 클래스가 처음 호출될 때 생명이 시작되고 자바 프로그램이 끝날 때 소멸

📌 자료형

자료형에는 참조 자료형과 기본 자료형이 존재한다. 참조 자료형은 new 를 통해서 초기화 되는 것이며 기본 자료형은 new 없이 바로 초기화가 가능한 것이다.

단 참조 자료형 중 딱 하나 String 만 new 없이도 객체를 생성할 수 있다.

String bookName1 = "God Of Java";
String bookName2 = new String("God Of Java");

기본 자료형의 종류는 BsilFD 다음과 같다.

  • 정수형 : byte short int long char
  • 소수형 : float double
  • 기타 : boolean

char 는 정수형 중 유일하게 부호가 없는 값이다.


3. 연산자

연산자를 활용한 문제를 풀어보았다.

public class SalaryManager {
	public static void main(String[] args) {
		SalaryManager sal = new SalaryManager();
		System.out.println("최종 결과 : " + sal.getMonthlySalary(20000000));
	}
	
	public double getMonthlySalary(int yearlySalary) {
		double monthSalary = (double)yearlySalary/12.0;
		double total = monthSalary - (calculaterTax(monthSalary) + calculaterNationalPension(monthSalary) + calculaterHealthInsurance(monthSalary));
		return total;
	}
	
	public double calculaterTax(double monthSalary) {
		double tax = monthSalary * 0.125;
		System.out.println("근로 소득세 : " + tax);
		return tax;
	}
	
	public double calculaterNationalPension(double monthSalary) {
		double national = monthSalary * 0.081;
		System.out.println("연금 : " + national);
		return national;
	}
	
	public double calculaterHealthInsurance(double monthSalary) {
		double health = monthSalary * 0.135;
		System.out.println("건강 보험료 : " + health);
		return health;
	}
}

참고로 연산자의 우선순위는 괄호가 가장 높다.


4. 조건문과 반복문

if 문은 true 일 경우에만 실행하고 모든 조건을 검사한다.
반면 if else if 문은 앞의 조건을 만족하면 뒤의 조건은 검사하지 않고 넘어간다.

public class InterestManager {
	public static void main(String[] args) {
		InterestManager manager = new InterestManager();
		int day = 1;
		double amount = 0.0;
		
		while(day <= 375) {
			manager.getInterestRate(day);
			amount = manager.calculateAmount(day, 1000000);
			System.out.println(day + "일 : " + amount);
			day +=10;
		}
	}
	
	public double getInterestRate(int day) {
		double rate = 0.0;
		
		if (day >= 1 && day <= 90) {
			rate = 0.5;
		} else if (day >= 91 && day <= 180) {
			rate = 1;
		} else if (day >= 181 && day <= 365) {
			rate = 2;
		} else if (day >= 365) {
			rate = 5.6;
		}
		
		return rate;
	}
	
	public double calculateAmount(int day, long amount) {
		double amountResult = 0.0;
		double rate = amount * getInterestRate(day) / 100.0;
		amountResult = amount + rate;
		return amountResult;
	}
}

Reference

profile
현수의 개발 저장소

0개의 댓글