JAVA 기초 _1

정혜지·2023년 4월 18일
0

변수

public class Main {

	public static void main(String[] args) {
    
      int intType = 100;
      double doubleType = 150.5;
      String stringType = "내팔자";
      
      System.out.println(intType);
      System.out.println(doubleType);
      System.out.println(stringType);
      
    }
    
}
  • static : 클래스 변수 선언 키워드
    • 모든 인스턴스가 같이 공유하는 하나의 변수


상수 final

public class Main {

  final static double PI = 3.141592;
  
  public static void main(String[] args){
     
     int r = 30;
     System.out.println(r * r * PI);
     
  }

}
  • final : 한번 선언이 되면 절대로 바뀔 수 없다 => ⭐상수
    상수는 메인 함수 바깥에서 선언이 된다.


overflow

각각의 자료형에 따른 모든 변수들은 나타낼 수 있는 값의 한계점이 존재
-> 정해진 범위안에서만 출력

public class Main {

  final static int INT_MAX = 2147483647;	// int 자료형이 가질 수 있는 가장 큰 값 (최대값)
  
  public static void main(String[] args){
    
    int a = INT_MAX;
    System.out.println(a);	// 2147483647
    System.out.println(a + 1);	// -2147483647
    // int 자료형이 가질 수 있는 최저의 값 (최소값)
    
  }

}

overflow
자료형에서 나타낼 수 있는 최대값을 초과하면 최소값으로 돌아간다.
순환구조



반올림

public class Main {
  
  public static void main(String[] args) {
    
    int b = 0.5;
    int a = (int) (b + 0.5);		// 실수형을 정수형으로 형 변환
    System.out.println(b);	// 1

}

}
  • 실수를 정수형으로 형 변환 -> 정수부분만 출력(소수점 자리 제거)
  • 실수 값을 반올림할 때는 변수에 0.5를 더한 뒤에 정수형으로 형변환
    • 반올림 값 = (int) (실수 + 0.5);
    • 어떠한 실수 값이든 항상 0.5 더하고 int형으로 바꿔주기 때문에 항상 반올림이 된 값만 출력됨




사칙연산

public class Main{
 
  public static void main(String[] args) {
     
     int a = 1;
     int b = 2;
     
     System.out.println("a + b = " + (a + b));
     System.out.println("a - b = " + (a - b));
     System.out.println("a * b = " + (a * b));
     System.out.println("a / b = " + (a / b));
  }
 
}


profile
오히려 좋아

0개의 댓글