Java 시리즈 4
[Java] #2 변수
[Java] #2 변수
#java#코드트리#trail0

참고: codetree Trail 0의 Chapter 1 - Lesson 2~3
1. 변수
데이터를 저장할 수 있는 메모리 공간의 이름
(자료형) (변수명) = (담을 값);
int age = 25;
double height = 175.5;
char ch = 'A';
String name = "Teddy";
boolean isStudent = true;
Array arr = {1, 3, 5}
1-1. 대입 연산자 =
- 변수를 선언하고 값을 할당할 때 사용
- 좌변에 변수의 자료형과 변수명을, 우변에 값을 할당
int a = 3; // 변수 a에 값 3을 대입
System.out.println(a); // 출력: 3
a = 10; // 변수 a에 새로운 값 10을 대입하여 이전 값 3을 변경
System.out.println(a); // 출력: 10
1-2. 변수 명명 규칙
알파벳,숫자,밑줄(_)사용 가능 O- 숫자로 시작 불가
- 대소문자 구분
1-3. 자료형
데이터의 종류와 종류마다의 데이터 처리 방법 정의
1-3-1. 정수 (int)
- 양수, 음수, 0
int num = 12;
System.out.println(num); // 12
1-3-2. 실수 (double)
- 과학적 표기법 사용하여 매우 큰 수나 매우 작은 수 표현 가능 O
- 메모리 크기에 따라 표현 가능한 정밀도와 범위가 다름
double e = 1.5e2;
double f = 2.5e-3;
System.out.println(e); // 출력: 150.0
System.out.println(f); // 출력: 0.0025
1-3-3. 불리언 (boolean)
true와false두 가지 값만 가짐- 주로 논리 연산과 조건문, 반복문에서 사용
boolean isStudent = true;
System.out.println(isStudent); // true
1-3-4. 문자 (char)
- 단일 문자 저장
- 작은따옴표('')로 감싸서 표현
특수기호도 저장 가능
char a = 'A';
char b = '!';
char c = '0';
System.out.println(a); // 출력: A
System.out.println(b); // 출력: !
System.out.println(c); // 출력: 0
1-3-5. 문자열 (String)
String fruit = "banana";
System.out.println(fruit); // banana
1-4. 변수 중복 선언
- 같은
블록({})안에서 동일한 이름을 가진 변수를 두 번 이상 선언 불가 - 이미 선언된 변수에 새로운 값을 재할당할 때는 앞에 데이터 타입을 붙이지 않고, 변수 이름만 사용해야 함.
public class Main {
public static void main(String[] args) {
// 1. 변수 a를 선언하고 'C'를 대입
char a = 'C';
// 2. 이미 존재하는 변수 a에 'T'를 다시 대입 (char 생략)
a = 'T';
System.out.println(a);
}
}
1-5. 형 변환
1-5-1. int <-> double
소수점 이하값을 반올림되지 않고 단순버림됨
(1) double -> int
- 소수점 이하 버림
System.out.println((int) 3.14); // 출력: 3
System.out.println((int) -2.99); // 출력: -2
System.out.println((int) 0.0); // 출력: 0
System.out.println((int) 7.999); // 출력: 7
(2) int -> double
System.out.println((double) 5); // 출력: 5.0
System.out.println((double) -1); // 출력: -1.0
System.out.println((double) 0); // 출력: 0.0
System.out.println((double) 42); // 출력: 42.0
[코드트리 추천 링크] https://www.codetree.ai/ko/trail-info?referralCode=th2gr22n
댓글 0
아직 댓글이 없습니다.