1-3 식별자
(1) 식별자란?
자바코드 내에서 개발자가 사용한 이름을 식별자라고 한다. 클래스이름, 변수이름, 메서드이름 등을 지정할 때 사용
(2) 식별자 명명규칙
1) 영문자(A~Z, a~z)와 숫자(0~9)와 '_','$'의 조합
2) 첫글자는 반드시 영문자나 '_'로 시작. 숫자로 시작 불허
3) 식별자는 대소문자를 철저히 구분
4) 자바에서 사용되는 예약어는 식별자로 사용할 수 없다.
5) 상수 값을 표현하는 단어 true, false, null은 식별자로 사용할 수 없다.
(3) 세부 식별자 정의 규칙
| 구분 | 정의 규칙 | 사용 예 |
| 클래스 | - 첫 문자는 항상 대문자로 표현 - 하나 이상의 단어가 합쳐질 때는 각 단어의 첫 문자들만 대문자로 표현 |
class JavaTest{ } |
| 변수와 메서드 | - 첫 문자는 항상 소문자로 표현 - 하나 이상의 단어가 합쳐질 때는 두번째부터 오는 단어의 첫 문자들만 대문자로 표현 |
String itLand; public void getTest(){ } |
| 상수 | - 모든 문자를 대문자로 표현 - 하나 이상의 단어가 합쳐질 때 공백 필요 시 under score(_)를 사용하여 연결한다. |
final int JAVATEST =10; final int JAVA_TEST=20; |
(4) 예약어
- 자바 프로그래밍을 하는데 있어 특정한 의미가 부여되어 이미 만들어진 식별자를 말한다.
- 예약어에 등록되어 있는 것을 프로그래밍에서 식별자로 사용할 수 없다.
(const와 goto는 예약어로 등록만 되어 있을 뿐 사용되지 않는 예약어이다.)
| abstract | continue | goto | package | this |
| assert | default | if | private | throw |
| boolean | do | implements | protected | throws |
| break | double | import | public | transient |
| byte | else | instanceof | return | try |
| case | extends | int | short | void |
| catch | final | interface | static | while |
| char | finally | long | super | |
| class | float | native | switch | |
| const | for | new | synchronized |
1-4 변수
- 값을 담아두는 기억 공간(메모리 공간)
- 하나의 데이터 값을 저장할 수 있음
- 정해진 값은 고정되어 있지 않고 계속 변할 수 있음
- 저장되는 데이터에 따라 변수의 자료형(Data Type)이 결정됨
package kr.s02.variable;
public class VariableMain01 {
public static void main(String[] args) {
//변수(Variable)는 값을 저장할 수 있는 메모리의 공간
//변수 선언
int num;
//변수의 초기화
num = 17;
//변수의 값 출력
System.out.println(num);
System.out.println("----------------");
//변수 선언, 초기화
int number = 20; //number가 가리키는 공간에 20을 넣어줌
System.out.println(number);
//데이터 변경
number = 40;
System.out.println(number);
System.out.println("----------------");
//주의사항
//동일한 변수명으로 변수를 선언하면 오류 발생
//int number = 30;
//동일한 자료형을 사용하기 때문에 두번째 변수명 앞의 자료형은 생략함.
int a = 10, b = 20;
int result = a + b; //변수에서 값을 호출해서 연산
System.out.printf("result = %d%n",result);
System.out.println("result = " + result);
//주의사항
System.out.println("결과 : " + a + b); //결과:1020 으로 출력됨
System.out.println("결과 : " + (a + b)); //결과: 30 으로 출력됨 //최우선 연산자 사용
int no; //변수 선언
//변수 선언 후 출력 또는 연산하기 전에 반드시 초기화를 해야 함
//System.out.println(no); -> 초기화 안해서 에러남
}
}
+ 연산자
+ : 연산 -> 숫자 + 숫자
+ : 연결 -> 문자열 + 숫자 -> 문자열과 숫자를 연결해서 새로운 문자열
숫자 + 문자열
문자열 + 문자열
[실습 1]
package kr.s02.variable;
public class VariableMain02 {
public static void main(String[] args) {
/*
* [실습]
* 정수를 담을 수 있는 변수를 3개 지정한다.
* 변수명은 각각 a,b,c라고 지정하고 원하는 정수로 초기화한다.
* a + b 연산 후 출력할 때
* (예) "결과 = 50" 형식으로 출력한다.
* c에 저장된 데이터를 80으로 변경해서
* (예) "c = 80" 형식으로 출력하시오.
*/
int a = 10, b = 20, c = 30;
System.out.println("결과 = " + (a+b));
System.out.printf("결과 = %d%n", a+b);
c = 80;
System.out.println("c = " + c);
System.out.printf("c = %d%n",c);
}
}
1-5 자료형
(1) 기본 자료형 (primitive data type)
자바 컴파일러에 의해서 해석되는 자료형
(2) 참조 자료형 (reference data type)
자바 API에서 제공되거나 프로그래머에 의해서 만들어진 클래스를 자료형으로 선언하는 경우
(3) 기본자료형의 종류
- 논리형 : boolean
- 문자형 : char
- 정수형 : byte, short, int long
- 실수형 : float, double
(4) 아스키 코드
package kr.s02.variable;
public class VariableTypeMain01 {
public static void main(String[] args) {
System.out.println("===논리형===");
//논리형 (true, false)
boolean b = true;
System.out.println("b = " + b);
System.out.println("===문자형==="); //문자형 크기 외우기
//문자형, 크기 : 2byte, 표현범위 : 0 ~ 65,535
//다국어 처리를 위한 유니코드(unicode) 방식
char c1 = 'A'; //내부적으로 아스키코드값 65
System.out.println("c1 = " + c1);
char c2 = 65; // A에 해당하는 아스키코드값 65를 직접 대입
System.out.println("c2 = " + c2);
//유니코드는 역슬래시 u 라고 명시하고 16진수로
char c3 = '\u0041'; //A를 유니코드로 표현
System.out.println("c3 = " + c3);
char c4 = '자';
System.out.println("c4 = " + c4); //한글은 아스키코드 없음. 유니코드로 명시 가능
char c5 = '\uc790'; //자를 유니코드로 표현
System.out.println("c5 = " + c5);
System.out.println("===정수형===");
//byte, 크기 : 1byte, 표현범위 : -128 ~ 127
byte b1 = 127;
System.out.println("b1= " + b1);
//short, 크기 : 2byte, 표현범위 : -23,768 ~ 32,767
short s1 = 32767;
System.out.println("s1 = " + s1);
//int, 크기 : 4byte, 표현범위 -20억대~ + 20억대
int in1 = 1234567;
System.out.println("in1 = " + in1);
//long, 크기 : 8byte
long lo1 = 1234567L; //1234567을 넣으면 int로 인식한 뒤 저장할때 long으로 바꿔줌.
//L을 넣으면 처음부터 long형 데이터로 인식 //L은 자료형을 나타냄
System.out.println("lo1 = " + lo1);
System.out.println("===실수형===");
//float, 크기 : 4byte
float f1 = 9.2f; //f는 자료형을 의미
System.out.println("f1 = "+ f1);
//double, 크기 : 8byte
double d1 = 9.8;
System.out.println("d1 = " + d1);
System.out.println("===문자열 표시===");
//문자열 표시(기본자료형이 아님, 참조자료형)
String str = "Hello World!";
System.out.println("str = " + str);
}
}
★ 중요 ★
long lo1 = 1234567L;
L 은 자료형을 나타낸다. 1234567을 넣으면 int로 인식한 뒤 저장할 때 long으로 바꿔준다.
L을 넣으면 처음부터 long형 데이터로 인식한다.
float f1 = 9.2f;
f 는 자료형을 의미한다.
(5) 확장 특수 출력 문자 (escape sequence)
package kr.s02.variable;
public class VariableTypeMain02 {
public static void main(String[] args) {
//확장 특수 출력 문자(escape sequence)
char single = '\'';
System.out.println(single);
String str = "오늘은 \"수요일\"입니다.";
System.out.println(str);
//문자열에 '를 표시하면 자동으로 일반문자로 변환됨
String str2 = "내일은 '목요일'입니다.";
//안에 있는 싱글쿼터는 더블쿼터의 영향을 받아서 출력 가능한 일반 문자로 변환됨.
System.out.println(str2);
String str3 = "C:\\javaWork";
System.out.println(str3);
String str4 = "여기는 서울이고\n저기는 부산입니다."; //줄바꿈 \n
System.out.println(str4);
String str5 = "이름\t나이\t취미";
System.out.println(str5);
}
}
★ 중요 ★
String str = "오늘은 \"수요일\"입니다.";
String str2 = "내일은 '목요일'입니다.";
(6) 형변환
- 데이터나 변수의 자료형을 다른 자료형으로 변환시키는 것
- 자바의 데이터는 서로 같은 자료형일 때 연산이 가능하다
- 서로 다른 자료형들은 같은 타입으로 변경시킨 후 연산 가능하다
- 기본형과 참조형 모두 형변환이 가능하다.
(기본형은 기본형끼리만, 참조형은 참조형끼리만 형변환 가능)
- boolean은 false와 true만을 저장하기 위해 특별히 만들어진 데이터 타입이므로 형변환이 불가능하다.
- 명시적 형변환과 묵시적 형변환으로 나뉜다.
1) 묵시적 형변환(자동 형변환)
- 프로그램 실행 도중 자동으로 일어나는 형변환
- 작은 타입을 큰 타입으로 변수에 할당하면 자동으로 변환된다.
2) 명시적 형변환(강제 형변환)
- 넓은 범위를 표현 가능한 큰 타입의 데이터를 좁은 범위를 표현 가능한 작은 타입으로 형변환 할 때에는
명시적으로 형변환을 해야 한다.
정수 < 실수 : 정수보다 실수가 크다. 그래서 정수에서 실수로 자동형변환이 됨 (데이터의 손실이 없음)
실수에서 정수로 형변환을 하면 4.5가 4로 바뀜(데이터의 손실이 발생)

long 이 비트 수가 float보다 크지만, long은 정수이므로 long은 float으로 자동 형변환이 됨 (실수가 정수보다 큼)
package kr.s03.cast;
public class CastMain01 {
public static void main(String[] args) {
System.out.println("===묵시적 형변환(자동 형변환)===");
//더 큰 자료형으로 승격이 일어나는 형태, 정보의 손실이 전혀 없으며 자동적으로 발생
byte b1 = 127;
byte b2 = 127;
int result = b1 + b2; //32bit 미만의 자료형 즉,
//byte형 데이터들을 연산하면 32bit로 승격됨
System.out.println("result = " + result);
short s1 = 32767;
short s2 = 32767;
int result2 = s1 + s2; //32bit 미만의 자료형 즉,
//short형 데이터들을 연산하면 32bit로 승격
System.out.println("result2= " + result2);
int in2 = 1234;
long lg2 = 2345L;
//in2 : int -> long 자동 형변환
long result3 = in2 + lg2;
System.out.println("result3 = " + result3);
//정수에서 실수로 가는 경우
int in3 =25;
double db = 10.5;
//in3 : int-> double 자동 형변환
double result4 = in3 + db;//25.0 + 10.5
System.out.println("result4 = " + result4); //결과적으로 double로 들어가기 때문에 int를 double로 변환
}
}
package kr.s03.cast;
public class CastMain02 {
public static void main(String[] args) {
System.out.println("===명시적 형변환(강제 형변환)===");
//더 작은 자료형으로 강등이 일어나는 형태, 정보의 손실이 발생할 수 있음.
byte b1 = 127;
byte b2 = 127;
byte result = (byte)(b1 + b2); // (byte) 를 '캐스트 연산자'라고 함
//자동적으로 int로 형변환된 것을 byte로 강제 형변환
System.out.println("result = " + result); //결과값이 -2 가 나옴. 결과값이 손실된 거임.
short s1 = 32767;
short s2 = 32767; //원하는 것은 short 타입이기 떄문에 강제 형변환
short result2 = (short)(s1 + s2); //자동적으로 int로 형변환된 것을 short로 강제 형변환
System.out.println("result2 = " + result2); //결과가 -2 가 나옴. 결과값이 손실됨.
int in1 = 100;
long lg1 = 200L;
int result3 = in1 + (int)lg1; //lg1 : long -> int 강제 형변환
System.out.println("result3 = " + result3); //데이터 손실 없음. 결과값 300
int in2 =26;
float ft = 10.3f;
int result4=in2+(int)ft; //ft: float -> int 강제 형변환
System.out.println("result4 = " + result4); // 결과값 34
}
}
명시적 형변환 일때, (byte) (short) 를 "캐스트 연산자" 라고 부른다.
데이터의 왜곡이 발생할 수 있지만 발생 안할 수도 있음.
2 연산자
연산자란 자료의 가공을 위해 정해진 방식에 따라 계산하고 결과를 얻기 위한 기호
(1) 증감 연산자
| 연산자 | 의미 |
| ++ | 1씩 증가시킴 |
| -- | 1씩 감소시킴 |
package kr.s04.operator;
public class OperatorMain02 {
public static void main(String[] args) {
System.out.println("===산술연산자===");
System.out.println(10 + 10);
System.out.println(20 - 7);
System.out.println(10 * 3);
System.out.println(10 / 3); //나눗셈 (몫 구하기) //3출력
System.out.println(5 % 3); //나머지 구하기 //2 출력
System.out.println("-------------");
System.out.println(10.0 / 3); //3이 자동형변환이 double로 일어남. //3.3333333333333335 출력
}
}
package kr.s04.operator;
public class OperatorMain03 {
public static void main(String[] args) {
/*
* [실습]
* 변수 선언시 자료형은 모두 int
* 변수 korean, english, math를 선언하고 90,95,88로 초기화한다.
* 총점을 구해서 변수 sum에 저장, 평균을 구해서 변수 avg에 저장
* 국어,영어,수학,총점,평균을 출력하시오.
*
* (출력 예시)
* 국어 = 90
*
*/
int korean= 90, english=95, math=88;
int sum, avg;
sum = korean+ english+ math;
avg = sum / 3 ;
System.out.println("국어 = " + korean); //System.out.printf("국어 = %d%n", korean);
System.out.println("영어 = " + english);
System.out.println("수학 = " + math);
System.out.println("총점 = " + sum);
System.out.println("평균 = " + avg);
}
}
[실습 2]
package kr.s04.operator;
public class OperatorMain04 {
public static void main(String[] args) {
/*
* [실습]
* 534자루의 연필을 30명의 학생들에게 똑같은 개수로 나누어 줄때 학생당 몇 개를 가질 수 있고,
* 최종적으로 몇 개가 남는지를 구하시오.
*
* [출력 예시]
* 학생 한 명이 가지는 연필 수 : **
* 남은 연필 수 : **
*
*/
int pencil = 534;
int student = 30;
System.out.println("학생 한명이 가지는 연필 수 : "+ pencil / student);
// +연산자보다 / 연산자 우선순위가 높음.
System.out.println("남은 연필 수 : "+ pencil % student);
}
}
입력 사용 방법 배우기
package kr.s04.operator;
public class OperatorMain05 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in); //입력 작업 시작
System.out.print("국어:");
//입력된 정수를 변수에 대입
int korean = input.nextInt(); //입력하면 nextInt가 korean에 대입해줌.
System.out.print("영어:");
int english = input.nextInt(); //nextInt는 정수만 가능
System.out.print("수학:");
int math = input.nextInt();
//총점 구하기
int sum = korean+ english+ math;
//평균 구하기
//double avg= sum / 3; //int avg= sum / 3; => 2개다 소수점이 0으로 나옴 35.00 이런식으로
//sum과 3이 int 형이기 때문에
//double 데이터로 만들고 싶으면 참여하는 연산 중 하나를 double로 하면 됨
// ex) 10.0 / 3
double avg = sum / 3.0; // 중요 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
System.out.printf("국어 = %d%n", korean);
System.out.printf("영어 = %d%n", english);
System.out.printf("수학 = %d%n", math);
System.out.printf("총점 = %d%n", sum);
//System.out.printf("평균 = %d%n", avg);
System.out.printf("평균 = %.2f%n", avg);
input.close(); //입력 작업 끝
}
}