DEVLOG

변수와 상수 본문

Java

변수와 상수

BINTHEWORLD 2022. 1. 31. 12:30

1. 변수 : 정수형 / 실수형 / 문자열

public class Main {
	
	public static void main(String[] args) {

		int intType = 100; //정수형
		double doubleType = 150.5; //실수형
		String stringType = "Park"; //문자열형
		
		System.out.println(intType); //출력 후 한 줄 띄어라
		System.out.println(doubleType);
		System.out.println(stringType);
	}

}

 

2. 상수

public class Main {
	final static double PI = 3.141592; //상수는 메인함수 밖에서 선언
	
	public static void main(String[] args) {
		
		int r = 30;
		System.out.println(r*r*PI);
		
	}

}

 

3. 정수형의 최댓값 최솟값

public class Main {
	final static int INT_MAX = 2147483647; //int형의 최댓값 21억
	
	public static void main(String[] args) {
		
		int a  = INT_MAX;
		System.out.println(a+1); //오버플로 int형의 최솟값 -21억이 되어버린다.
		
	}

}

 

4. 사칙연산 구현

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)); //몫만을 출력
		
	}

}

 

5. 실수형 -> 정수형 변환

public class Main {
	
	public static void main(String[] args) {
		double b = 0.5; 
		int a = (int) (b+0.5); 
		//(int) : 실수형을 정수형으로 변환 
		//실수형 반올림 : 실수에 0.5 더한 후, 정수형으로 변환 
		System.out.println(a);
		
	}

}

'Java' 카테고리의 다른 글

이중 for문으로 로또번호 추출 (중복제거)  (0) 2022.02.14
while문  (0) 2022.02.14
조건문 / 반복문  (0) 2022.01.31
연산자  (0) 2022.01.31
자료형  (0) 2022.01.31
Comments