├─ 자료형
├─ 기본 자료형: 실제 데이터 값을 저장
└─ int, long, float, double, boolean, char, ...
└─ 참조 자료형: 데이터가 저장된 메모리 주소 값을 저장
└─ 클래스, 인터페이스, 배열, 열거형, ...(String)
자료형 | 데이터 | 크기(byte) | 표현범위 |
---|---|---|---|
int | 정수 | 4 | -2,147,483,648 ~ 2,147,483,647 |
long | 정수 | 8 | -9,223,372,854,775,808 ~ 9,223,372,854,775,807 |
float | 실수 | 4 | (정밀도 기준) 6~7자리 |
double | 실수 | 8 | (정밀도 기준) 15자리 |
boolean | 참/거짓 | 1 | true, false |
char | 문자 | 2 | 하나의 문자 |
자료형 변수명 = 값;
// 선언과 동시에 초기화
String name ="자바";
int hour = 15;
double score = 90.5;
char grade = 'A';
boolean pass = true;
자료형 변수명;
변수명 = 값;
// 선언 따로,값 저장 따로
int hour;
hour = 15;
//
어떤 문장 1; // 주석
// 어떤 문장2;
int hour = 15; // 현재시각(15시)
// double score = 90.5;
/* 어떤 문장 1; 어떤 문장 2; */
/* int hour = 15;
double score = 90.5; */
변수명: 값을 가장 잘 표현하는 이름
1. 밑줄(_), 문자(abc), 숫자(123) 사용 가능! (공백 사용 불가)
2. 밑줄 또는 문자로 시작 가능
3. 한 단어 또는 2개 이상 단어의 연속
4. 소문자로 시작, 각 단어의 시작 글자는 대문자(첫 단어 제외)
5. 예약어 사용 불가 ex) public, static, void, int, ...
6. 대소문자 구분 ex) myName과 myname은 다른 변수
final 자료형 변수명 = 값;
final int hour = 15;
hour = 20; // 값 변경 불가(에러 발생)
(자료형) 변수명 or 값;
int
-> long
-> float
-> double
int score = 93;
// 실수로 변환
float score_f = (float)score; // 변수명
double score_d = (double)93;
// (float), (double) 생략 가능
double
-> float
-> long
-> int
dobule score_d = 98.8;
int score = (int) score_d;
// (int) 생략 불가
+
(더하기), -
(빼기), *
(곱하기), /
(나누기), %
(나머지), ++
(증가), --
(감소)
=
: 오른쪽에 있는 값 또는 식을 왼쪽에 있는 변수에 대입
+=
: (왼쪽 + 오른쪽) 결과를 왼쪽에 대입
-=
: (왼쪽 - 오른쪽) 결과를 왼쪽에 대입
*=
: (왼쪽 * 오른쪽) 결과를 왼쪽에 대입
/=
: (왼쪽 / 오른쪽) 결과를 왼쪽에 대입
%=
: (왼쪽 % 오른쪽) 결과를 왼쪽에 대입
>
: 왼쪽이 오른쪽보다 큰가?
>=
: 왼쪽이 오른쪽보다 크거나 같은가?
<
: 왼쪽이 오른쪽보다 작은가?
<=
: 왼쪽이 오른쪽보다 작거나 같은가?
==
: 왼쪽과 오른쪽이 같은가?
!=
: 왼쪽과 오른쪽이 다른가?
&&
: 왼쪽과 오른쪽이 모두 참인가?
||
: 왼쪽 또는 오른쪽이 하나라도 참인가?
!
: (참 ㄸ도는 거짓)의 반대
조건?참일때:거짓일때
: 물음표 왼쪽의 조건이 참이면 왼쪽, 거짓이면 오른쪽
String s = "I like Java";
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
length | 길이 | s.length(); | 11 |
toUpperCase | 대문자로 | s.toUpperCase(); | I LIKE JAVA |
toLowerCase | 소문자로 | s.toLowerCase(); | i like java |
contains | 포함 여부 | s.contains("Java"); | true |
indexOf | 위치 정보 | s.indexOf("Java"); | 7 |
lastIndexOf | 마지막 위치 정보 | s.lastIndexOf("a") | 10 |
startsWith | 문자열로 시작하는가? | s.startsWith("I like") | true |
endsWith | 문자열로 끝나는가? | s.endsWith(".") | false |
replace | 문자열 변환 | s.replace("like", "love") | I love Java |
substring | 문자열 자르기 | s.substring(7) | Java |
trim | 앞뒤 공백 제거 | s.trim() | I like Java |
concat | 문자열 결합 | s.concat(" and Python") | I like Java and Python |
int num1 = 3;
int num2 = 3;
System.out.println(num1 == num2); // true
String s1 = "Java";
String s2 = "Java"
System.out.println(s1 == s2); // true
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); // false
⭐️ 따라서, 문자열 비교는 equals
이용
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2)); // true(문자열 내용이 같다)
특수문자 | 설명 | 예시 | 결과 |
---|---|---|---|
\n | 줄바꿈 | System.out.println("A\nB); | A B |
\t | 탭 | System.out.println("A\tB); | A B |
\ | 역슬래시 | System.out.println("C:\Java); | C:\Java |
\" | 큰따옴표 | System.out.println("A\"B\"C"); | A"B"C |
\' | 작은 따옴표 | System.out.println("A\'B\'C"); | A'B'C |
if(조건) 명령문;
또는
if(조건) { 명령문1; 명령문2; ...}
if(조건)
명령문;
else
명령문;
또는
if(조건) {
명령문;
} else{
명령문;
}
if(조건1)
명령문;
else if(조건2)
명령문;
if(조건1) {
명령문;
} else if(조건2){
명령문;
}
switch(조건) {
case 값1: 명령문
break;
case 값2: 명령문
breka;
...
default: 명령문
}
for(선언;조건;증감)
명령문;
또는
for(선언;조건;증감) {
명령문 1;
명령문 2;
}
while(조건)
명령문;
또는
while(조건) {
명령문1;
명령문2;
}
do {
명령문1;
명령문2;
} while(조건)
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
System.out.println("안녕?");
}
}
// 총 6번 반복 2x3
for(int i=0;i<5;i++){
if(i==3) break;
System.out.println("안녕?");
}
/*
안녕?
안녕?
안녕?
*/
for(int i=0;i<5;i++){
if(i==3) continue;
System.out.println("안녕?");
}
/*
안녕?
안녕?
(3번째는 건너뜀)
안녕?
안녕?
*/
자료형[] 변수명 = new 자료형[크기];
자료형 변수명[] = new 자료형[크기];
int[] numbers = new int[5];
String[] names = new String[3];
또는
int numbers[] = new int[5];
String names[] = new String[3];
변수명[인덱스] = 값;
: 배열에 값 넣기
→ 인덱스는 항상 0부터 시작
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 5;
numbers[2] = 10;
자료형[] 변수명 = new 자료형[]{값1, 값2, ...};
자료형[] 변수명 = {값1, 값2, ...};
int[] numbers = new int[]{1, 2, 3, 4, 5};
String[] names = new String[]{"A", "B", "C"};
또는
int numbers[] = {1, 2, 3, 4, 5};
String names[] = {"A", "B", "C"};
for(int i=0;i<배열.length;i++){
... // 배열[i]
}
또는
for(int i : 배열) {
... // i
}
ex)
int[] numbers = {1,2,3,4,5};
for(int i=0;i<numbers.length;i++){
System.out.println(numbers[i]);
}
for(int i:numbers){
System.out.println(i);
}
자료형[][] 변수명 = new 자료형[세로][가로];
int[][] numbers = new int[2][5];
numbers[0][2] = 3;
int[][] numbers = new int[][] {
{1,2,3,4,5},
{6,7,8,9,10}
};
for(int i=0;i<세로;i++){
for(int j=0;j<가로;j++){
... // 배열[i][j]
}
}
int[][] numbers = new int[][] {
{1,2,3,4,5},
{6,7,8,9,10}
};
for(int i=0;i<numbers.length;i++){
for(int j=0;j<numbers[i].length;j++){
System.out.println(numbers[i][j]);
}
}
접근제어자 반환형 메소드명(전달값){
명령문1;
명령문2;
...
// return 반환값;
}
public static void print(){
System.out.println("안녕");
}
public static void main(String[] args){
print(); // 메소드 호출
}
public static void main(String[] args){
print(); // 안녕
printA(3); // 3
printB(1,2); // 3
}
// 전달값이 없는 메소드
public static void print(){
System.out.println("안녕");
}
// 전달값(1개)이 있는 메소드
public static void printA(int a){
System.out.println(a);
}
// 전달값(2개)이 있는 메소드
public static void printB(int a, int b){
System.out.println(a+b);
}
public static void main(String[] args){
int num = getMaxLottoNumber();
System.out.println(num); // 45
}
public static int getMaxLottoNumber(){
return 45; // 반환 값
}
public static void main(String[] args){
int result = add(1, 2);
System.out.println("1+2="+ result);
}
public static int add(int a, int b){
return a+b; // 반환 값
}
접근제어자 반환형 메소드명(정수 전달값){}
접근제어자 반환형 메소드명(정수 전달값1, 정수 전달값2){}
접근제어자 반환형 메소드명(실수 전달값){}
public static void main(String[] args){
System.out.println(add(1,2));
System.out.println(add(1,2,3));
System.out.println(add(5.2, 3.2));
}
public static int add(int a, int b){
return a+b;
}
public static int add(int a, int b, int c){
return a+b+c;
}
public static double add(double a, double b){
return a+b;
}
public static void main(String[] args){
int a = 10; // a는 main 함수 내에서만 사용 가능
System.out.println(a); // 10
}
public static void scope(){
System.out.println(a); // error → a 사용 불가
}
public static void main(String[] args){
System.out.println(b); // 에러 발생 b 사용 불가
}
public static void scope(){
int b = 20; // scope 메서드 내에서만 사용 가능!
System.out.println(b); // 20
}
public static void main(String[] args){
int c= 30;
if(c>10){
int d = 40; // d는 if 조건문 내에서만 사용 가능
System.out.println(d);
}
System.out.println(d); // 에러 발생 d 사용 불가
}
class 클래스명 {
}
ex) Person 클래스 만들기
class Person {
}
public static void main(String[] args){
// 객체 만들기
// 클래스명 객체이름 = new 클래스명();
Person person = new Person();
}
class 클래스명 {
인스턴스 변수1
인스턴스 변수2
...
}
ex) Person 객체에 인스턴스 변수에 값 정의하기
class Person {
// 인스턴스 변수
String name;
int age;
}
public static void main(String[] args){
// 인스턴스 변수에 값 정의
Person person = new Person();
// 객체이름.인스턴스변수명
person.name = "철수";
person.age = 20;
}
class 클래스명 {
static 클래스 변수1
static 클래스 변수2
...
}
ex) Person 클래스에 사람 수 카운트하는 클래스 변수만들기
class Person {
// 인스턴스 변수
String name;
int age;
// 클래스 변수
static int personCount = 0;
}
public static void main(String[] args){
// 클래스 변수 사용하기
// 클래스명.클래스변수
Person.personCount = 10;
System.out.println(Person.personCount); // 10
}
class 클래스명 {
인스턴스 메소드1
인스턴스 메소드2
...
}
ex) Person 클래스에 인스턴스 메소드 만들기
class Person {
// 인스턴스 변수
String name;
int age;
// 클래스 변수
static int personCount = 0;
// 인스턴스 메소드
public void introduce(){
System.out.println("이름:"+name);
System.out.println("나이:"+age);
}
}
public static void main(String[] args){
// 인스턴스 메소드 호출하기
// 객체명.메소드명();
Person person = new Person();
person.name = "철수";
person.age = 20;
person.introduce(); // 메소드 호출
}
class 클래스명 {
static 클래스 메소드1
static 클래스 메소드2
...
}
ex) Person 클래스에 클래스 메소드 만들기
class Person {
// 인스턴스 변수
String name;
int age;
// 클래스 변수
static int personCount = 0;
// 클래스 메소드
public static void printPersonCount(){
System.out.println(personCount);
}
}
public static void main(String[] args){
// 클래스 메소드 호출하기
// 클래스명.클래스메소드
Person.personCount = 10;
Person.printPersonCount(); // 10
}
this.인스턴스변수
public static void main(String[] args){
Person person = new Person();
person.setName("철수");
System.out.println(person.name); // 철수
}
class Person {
String name;
public void setName(String name){
this.name = name;
}
}
클래스명(전달값){
초기화 명령문
}
public static void main(String[] args){
Person person = new Person("철수", 20);
}
class Person {
String name;
int age;
// 생성자
Person(String name, int age){
// 초기화 작업
this.name = name;
this.age = age;
}
}
반환형 get이름() {
return 반환값;
}
void set이름(전달값) {
}
public static void main(String[] args){
Person person = new Person();
person.setAge(20); // 값 설정
System.out.println(person.getAge()); // 값 가져오기
}
class Person {
String name;
int age;
// Getter
public int getAge(){
return age;
}
// Setter
public void setAge(int age){
this.age = age;
}
}
접근제어자 class 클래스명 {
접근제어자 인스턴스 변수
접근제어자 인스턴스 메소드
}
접근 제어자 | 접근 가능 범위 |
---|---|
private | 해당 클래스 내에서만 |
public | 모든 클래스에서 |
default | 같은 패키지 내에서만(아무것도 적지 않았을 때) |
protected | 같은 패키지 내에, 다른 패키지인 경우 자식 클래스에서 |
public static void main(String[] args){
Person person = new Person();
System.out.println(person.age); // error
person.setAge(20); // 값 설정
}
class Person {
private int age; // 클래스 외부에서 사용 불가
// Setter
public void setAge(int age){
this.age = age;
}
}
package 패키지명;
import 패키지명.클래스명;
class 자식클래스명 extends 부모클래스명 {
}
public class Exam {
public static void main(String[] args){
Student student = new Student("aa", 10);
student.whereInfo();
}
}
class Person {
public int age;
public static int n = 10;
public Person(int age){
this.age = age;
}
public void setAge(int age){
this.age = age;
}
}
class Student extends Person {
String school;
// 부모 클래스의 인스턴스 변수나 메소드가 private일 경우 getter, setter 이용해야함
public Student(String school, int age) {
super(age);
this.school = school;
}
public void whereInfo() {
System.out.println(this.school+" "+this.age+" "+n);
}
}
class Person {
public void introduce(){
System.out.println("사람입니다.");
}
}
class Student extends Person {
@Override
public void introduce() {
System.out.println("학생입니다.");
}
}
public class Exam {
public static void main(String[] args){
// 서로 다른 객체를 만들고, 부모 클래스로 똑같이 참조 가능
Person person = new Person();
Person student = new Student();
person.introduce(); // 사람입니다.
student.introduce(); // 학생입니다.
}
}
class Person {
public void introduce(){
System.out.println("사람입니다.");
}
}
class Student extends Person {
@Override
public void introduce() {
System.out.println("학생입니다.");
}
}
super.부모 클래스 변수;
super.부모 클래스 메소드();
super();
class Person {
int age;
Person(int age){
this.age = age;
}
}
class Student extends Person {
String school;
Student(int age, String school){
super(age); //this.age = age;
this.school = school;
}
}
int a = 10;
int b = 20;
a = b; // b의 값을 a에 복사
String s1 = "사과";
String s2 = "바나나";
s1 = s2; // s2의 값을 s1에 복사
class Person {
final String name = "철수";
// final로 정의된 메소드는 재정의 불가!
public final void introduce() {
System.out.println("사람입니다.");
}
}
class Student extends Person {
// error 오버라이딩 불가
public void introduce() {
System.out.println("학생입니다.");
}
}
enum 열거형명 {
상수명1
상수명2
...
}
public class Exam {
public static void main(String[] args){
Person person = new Person();
person.setGender(Gender.MALE); // MALE, FEMALE
person.setGender("DD"); // Error(Gender 타입이 와야함)
}
}
enum Gender {
MALE,
FEMALE
}
class Person {
Gender gender;
public void setGender(Gender gender) {
this.gender = gender;
}
}
abstract class 클래스명 {
}
// 추상 클래스 생성
abstract class Shape {
abstract double calculateArea();
}
// 자식 클래스에서 메서드 완성시키기
class Square extends Shape{
private double s;
public Square(double s){
this.s = s;
}
@Override
double calculateArea() {
return s*s;
}
}
class Circle extends Shape{
private double r;
public Circle(double r){
this.r = r;
}
@Override
double calculateArea() {
return Math.PI*r*r;
}
}
interface 인터페이스명{
}
// 인터페이스 생성
interface Shape {
double calculateArea(); // 인터페이스를 구현하는 클래스에서 반드시 정의해주어야 함
}
// 자식 클래스에서 인터페이스 내 메서드 완성시키기
class Square implements Shape{
private double s;
public Square(double s){
this.s = s;
}
@Override
public double calculateArea() {
return s*s;
}
}
class Circle implements Shape{
private double r;
public Circle(double r){
this.r = r;
}
@Override
public double calculateArea() {
return Math.PI*r*r;
}
}
T 변수명
public class Exam {
public static void main(String[] args){
int intValue = 3;
double doubleValue = 3.14;
String stringValue = "안녕";
printValue(intValue);
printValue(doubleValue);
printValue(stringValue);
}
// 원래는 이런식으로 오버로딩 이용해야 했음
public static void printValue(int value){
System.out.println(value);
}
public static void printValue(double value){
System.out.println(value);
}
public static void printValue(String value){
System.out.println(value);
}
}
public class Exam {
public static void main(String[] args){
int intValue = 3;
double doubleValue = 3.14;
String stringValue = "안녕";
printValue(intValue);
printValue(doubleValue);
printValue(stringValue);
}
// 제네릭스 이용하면 여러개 만들지 않아도됨
public static <T> void printValue(T value){
System.out.println(value);
}
}
class 클래스명<T> {
}
public class Exam {
public static void main(String[] args){
BoxInteger iBox = new BoxInteger();
iBox.setData(3); // 정수 담기
BoxString sBox = new BoxString();
sBox.setData("안녕"); // 문자열 담기
}
}
class BoxInteger {
int data;
public void setData(int data){
this.data = data;
}
}
class BoxString {
String data;
public void setData(String data){
this.data = data;
}
}
public class Exam {
public static void main(String[] args){
Box<Integer> iBox = new Box<>();
iBox.setData(3); // 정수 담기
Box<String> sBox = new Box<>();
sBox.setData("안녕"); // 문자열 담기
}
}
class Box<T> {
T data;
public void setData(T data){
this.data = data;
}
}
Integer i = 1; // int i = 1;
Double d = 1.0; // double d= 1.0;
Character c ='a'; // char c = 'a';
System.out.println(i.intValue()); // 정수로 출력
System.out.println(d.intValue()); // 실수를 정수형태로 변환해서 출력
System.out.println(c.charValue()); // 문자 형태로 출력
ArrayList<T>
ArrayList<String> list = new ArrayList<>();
list.add("철수"); // 리스트에 아이템 추가
list.add("영희");
// 리스트 순회하기
for(String s:list){
System.out.println(s);
}
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
add | 추가 | list.add("철수"); | {"철수"} |
get | 가져오기 | list.get(0); | "철수" |
size | 크기 | list.size() | 1 |
set | 수정 | list.set(0, "영희"); | {"영희"} |
contains | 포함 여부 | list.contains("영희"); | true |
remove | 삭제 | list.remove("영희"); | { } |
clear | 전체 삭제 | list.clear(); | { } |
LinkedList<T>
LinkedList<String> list = new LinkedList<>();
list.add("철수");
list.add("영희");
for(String s: list){
System.out.println(s);
}
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
add | 추가 | list.add("철수"); | {"철수"} |
get | 가져오기 | list.get(0); | "철수" |
getFirst | 처음 요소 가져오기 | list.getFirst() | "철수" |
getLast | 마지막 요소 가져오기 | list.getLast(); | "철수" |
addFirst | 맨 앞에 추가 | list.addFirst("영희"); | {"영희", "철수"} |
addLast | 맨 뒤에 추가 | list.addLast("영철"); | {"영희", "철수", "영철"} |
clear | 전체 삭제 | list.clear(); | { } |
HashSet<T>
HashSet<String> set = new HashSet<>();
set.add("철수"); // {"철수"}
set.add("영희"); // {"철수", "영희"}
set.add("철수"); // {"철수", "영희"}
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
add | 추가 | set.add("철수"); | {"철수"} |
contains | 포함여부 | set.contains("영희"); | false |
size | 크기 | set.size() | 1 |
remove | 삭제 | set.remove("철수"); | { } |
clear | 전체 삭제 | set.clear(); | { } |
HashMap<K, V>
HashMap<String, Integer> map = new HashMap<>();
map.put("철수", 100);
map.put("영희", 90);
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
put | 추가 | map.put("철수", 100); | {"철수":100} |
size | 크기 | map.size(); | 1 |
get | 가져오기 | map.get("철수"); | 100 |
containsKey | Key포함여부 | map.containsKey("영희"); | false |
remove | 삭제 | map.remove("철수"); | { } |
clear | 전체 삭제 | map.clear(); | { } |
Iterator<T>
ArrayList<String> list = new ArrayList<>();
list.add("철수");
list.add("영희");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
기능 | 설명 | 예시 | 결과 |
---|---|---|---|
hasNext | 다음 요소 확인 | it.hasNext(); | true |
next | 다음 요소 가져오기 | it.next(); | "철수" |
remove | 삭제 | it.remove(); | { } |
public class Exam {
public static void main(String[] args){
Person person = new Person();
person.introduce(); // 사람입니다.
// 익명클래스
Person person2 = new Person() {
@Override
public void introduce(){
System.out.println("익명입니다");
}
};
person2.introduce(); // 익명입니다
}
}
class Person {
public void introduce(){
System.out.println("사람입니다.");
}
}
(전달값1, 전달값2, ...) -> {코드}
public int add(int x, int y){
return x+y;
}
// 람다식
(x, y) -> x+y
@FunctionalInterface
interface 인터페이스명 {
// 하나의 추상메소드
}
public class Exam {
public static void main(String[] args){
Calculator add = (x, y) -> x+y; // 람다식
int result = add.calculate(2, 3);
System.out.println(result); // 5
}
}
@FunctionalInterface
interface Calculator {
int calculate(int x, int y); // 하나의 추상메소드
}
List<Integer> numbers = Arrays.asList(1,2,3,4,5);
numbers.stream()
.filter(n -> n%2 ==0) // 짝수만 필터링
.map(n -> n*2) // 각 요소 값을 2배로 변환
.forEach(System.out::println); // 결과 출력
try {
명령문
}catch(변수) {
예외처리
}
int[] numbers = {1,2,3};
int index = 5; // 존재하지 않는 인덱스
try{
int result = numbers[index];
System.out.println("결과: "+result);
}catch (Exception e){
System.out.println("문제 발생");
}
try {
명령문
}catch(변수1) {
예외처리1
}catch(변수2) {
예외처리2
}
int[] numbers = {1,2,3};
int index = 5; // 존재하지 않는 인덱스
try{
int result = numbers[index];
System.out.println("결과: "+result);
}catch (ArrayIndexOutOfBoundsException e){
// 잘못된 인덱스
System.out.println("문제 발생");
}
throw new 예외();
try{
int age = -5;
if(age < 0){
throw new Exception("나이는 음수일 수 없습니다");
}
}catch (Exception e){
System.out.println(e.getMessage());
}
try {
명령문
} catch(변수) {
예외처리
} finally {
명령문
}
try{
int result = 3/0;
}catch (Exception e){
System.out.println("문제 발생");
}finally {
System.out.println("실행 종료");
}
try (자원할당){
명령문
} catch(변수) {
예외처리
}
try(FileWriter writer = new FileWriter("file.txt")){
writer.write("안녕?");
}catch (Exception e){
System.out.println("문제 발생");
}
class 클래스명 extends Exception {
}
public class Exam {
public static void main(String[] args){
try{
int age= -5;
if(age<0){
throw new MyException("나이는 음수일 수 없습니다");
}
}catch(MyException e){
System.out.println("문제발생"+e.getMessage());
}
}
}
class MyException extends Exception{
public MyException(String message){
super(message);
}
}
반환형 메소드명() throws 예외 {
명령문
}
public static void main(String[] args){
try{
divide(3, 0);
}catch(Exception e){
System.out.println("0으로 나눌 수 없어요"); // 예외 처리
}
}
public static int divide(int a, int b) throws Exception{
return a/b;
}
class 클래스명 extends Thread {
public void run() {
}
}
public class Exam {
public static void main(String[] args){
// 쓰레드 실행
MyThread thread = new MyThread();
thread.start();
/**
* Thread: 1
* Thread: 2
* Thread: 3
* Thread: 4
* Thread: 5
*/
}
}
// 쓰레드 생성
class MyThread extends Thread {
@Override
public void run() {
for(int i=1;i<=5;i++){
System.out.println("Thread: "+i);
}
}
}
class 클래스명 implements Runnable {
public void run() {
}
}
public class Exam {
public static void main(String[] args){
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
/**
Runnable: 1
Runnable: 2
Runnable: 3
Runnable: 4
Runnable: 5
*/
}
}
// runnable 생성
class MyRunnable implements Runnable {
@Override
public void run() {
for(int i=1; i<=5;i++){
System.out.println("Runnable: "+i);
}
}
}