기본 틀
출력하기
public class 클래스이름 {
public static void main(String[] args) {
System.out.println("출력할 말");
}
}
1. public class 클래스이름 {
- 🔤 뜻: "Study"라는 이름의 클래스를 만든다.
- 📘 클래스: 자바는 모든 코드를 "클래스" 안에 넣어야 함. 클래스는 코드의 틀, 집이라고 생각하면 됨.
2. public static void main(String[] args) {
- 이건 자바 프로그램이 시작되는 입구.
- 자바는 이 문장을 찾아서 실행을 시작함
- 🧠 외우기: "public static void main(String[] args)" ← 무조건 이대로 써야 자바가 실행됨!
1단계: 변수와 자료형 (데이터 저장하기)
🧠 외우기:
자료형 변수이름 = 값;
int age = 20; // 정수형 변수
double height = 175.5; // 실수형 변수
String name = "Alice"; // 문자열 변수
boolean isStudent = true; // 참/거짓
2단계: 연산자 (계산하기)
| + | 더하기 | 3 + 2 = 5 |
| - | 빼기 | 3 - 2 = 1 |
| * | 곱하기 | 3 * 2 = 6 |
| / | 나누기 | 6 / 3 = 2 |
| % | 나머지 | 7 % 3 = 1 |
int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1 (10 나누기 3의 나머지)
3단계: 조건문 (if / else)
🧠 외우기:
if (조건) {
// 조건이 맞으면 실행
} else {
// 아니면 실행
}
예시문
int score = 85;
if (score >= 90) {
System.out.println("A 학점");
} else if (score >= 80) {
System.out.println("B 학점");
} else {
System.out.println("C 학점");
}
public class GradeCheck {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("A 학점");
} else if (score >= 80) {
System.out.println("B 학점");
} else if (score >= 70) {
System.out.println("C 학점");
} else if (score >= 60) {
System.out.println("D 학점");
} else {
System.out.println("F 학점");
}
}
}
4단계: 반복문 (for / while)
🧠 외우기:
for (초기값; 조건; 변화) {
반복할 코드;
}
예시문
for (int i = 1; i <= 5; i++) {
System.out.println("반복: " + i);
}
public class CountToTen {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
🧠 외우기:
while (조건) {
반복할 코드;
}
예시문
int i = 1;
while (i <= 5) {
System.out.println("while 반복: " + i);
i++;
}
public class HelloRepeat {
public static void main(String[] args) {
sayHello(); // 함수 호출
}
public static void sayHello() {
for (int i = 0; i < 3; i++) {
System.out.println("Hello");
}
}
}
5단계: 메서드 (함수)
자주 쓰는 코드를 따로 묶어두는 방법
필요할 때 불러다 쓰기만 하면 됨!
🧠 외우기:
public static void 메서드이름() {
// 실행할 코드
}
예시문
public class Study {
public static void main(String[] args) {
sayHello(); // 메서드 호출 (실행)
}
public static void sayHello() {
System.out.println("안녕하세요!");
}
}
이 코드의 작동 순서
- main() 함수부터 실행됨 ← 자바 프로그램의 시작점
- sayHello();를 만나면 → sayHello 함수로 이동
- for문으로 "Hello"를 3번 출력
- 끝나면 다시 main()으로 돌아옴
'Java > java 공부' 카테고리의 다른 글
| [java study 4] 문자열 자르기 (1) | 2025.07.18 |
|---|---|
| [java study 4] 객체 생성 (1) | 2025.07.07 |
| [java study 3] (0) | 2025.07.06 |
| [java study 2] (0) | 2025.07.04 |