Java 기본 문법 정리
2022. 12. 27. 12:05
- 상수 표현
final int y = 30;
- 데이터 타입
//정수
long l = 30L;
int x = 30;
short s = 30;
byte b = 30;
//실수
double dd = 30.0;
float ff = 30.0f;
boolean isMarried = true;
isMarried = false;
char c ='a'; // 거의 잘 안씀
char cc = '한';
String str = "여러 글자";
- 문자열 출력
System.out.printf("저는 %s입니다. 나이는 %d살이고요, 키는 %f cm 입니다. \n", "홍길동",20,180.5f);
String str2 = String.format("저는 %s입니다. 나이는 %d살이고요, 키는 %f cm 입니다. \n", "홍길동",20,180.5f);
System.out.println(str2);
- stirng int 변환
//string -> int 변환
String str = "100";
int i = Integer.parseInt(str);
//int -> string 변환
String str = String.valueOf(i);
- random
Random random = new Random();
int rand = random.nextInt(10);
// 0 ~ 9
int rand = random.nextInt(4) + 5;
// 5 ~ 9
- 입력
Scanner scanner = new Scanner(System.in);
// 변수에 넣기도 가능
String str = scanner.next();
int i = scanner.nextInt();
long l = scanner.nextLong();
- if문
if / else if / else
switch도 가능
String str;
boolean isMarried ? "결혼 했다" : "결혼 안 했다";
if (isMarried) {
str = "결혼 했다";
}else{
str = " 결혼 안했다";
}
System.out.println(str);
- 반복문
for / while / do while
break : 반복문 탈출 원할 때
continue : 반복문 안에 밑에껀 건너띄고 다음 반복문 실행
- 배열
int[] score = new int[5]; // 처음 초기화는 0으로 됨
int[] score2 = new int[] { 10 , 20 , 30 , 40 , 50};
//int[] score2 = { 10 , 20 , 30 , 40 , 50}; 도 가능
System.out.println(score.length); // 배열의 길이
System.out.println(score2[score2.length - 1]); // 배열 마지막 원소 출력
String[] names = {"홍길동", "이순신"}; // String은 초기화 하지 않으면 null 값 들어감
System.out.println(names[0].length());
- 리스트
배열보다 편한 기능이 많다.
ArrayList<Integer> scoreList = new ArrayList<>();
scoreList.add(10);
scoreList.add(20);
scoreList.add(30);
scoreList.add(40);
scoreList.add(50);
scoreList.add(2, 200); // 2번째 인덱스에 200 넣기
scoreList.remove(2); // 2번째 인덱스 삭제
System.out.println(scoreList.size()); // 리스트 사이즈 출력
System.out.println(scoreList.get(0)); // 0번째 원소 출력
System.out.println(scoreList); // 리스트 전체 출력
- 메소드
public class Main {
public static void main(String[] args) {
add(10,20);
System.out.println(add2(20,30));
}
public static void add(int x, int y){
System.out.println(x+y);
}
public static int add2(int x, int y){
return x + y;
}
}
- 메소드 오버로드
메소드 이름 같지만 매개변수 타입이나 갯수가 다름
public class Main {
public static void main(String[] args) {
System.out.println(add(20,30));
System.out.println(add(20,30,40);
System.out.println(add(20,30,40, 50,60,70);
}
public static int add(int x, int y){
return x + y;
}
public static int add(int x, int y, int z){
return x + y + z;
}
public static int add(int ... numbers){ // 배열로 들어감
int sum = 0;
for (int i = 0 ; i < numbers.length; i ++){
sum = sum + i;
}
return sum;
}
}
- 클래스
클래스는 따로 패키지를 만들어 import로 사용
public class Main {
public static void main(String[] args) {
Person person = new Person();
Person person2 = new Person("홍길동" , 10);
System.out.println(person);
System.out.println(person2);
}
}
class Person { // 보통 변수를 private로 하고 getter setter로 사용
private String name;
private int age;
Person(){
}
Person(String name, int age){
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 상속
package models;
public class Hero extends Person{
public Hero(String name){
super(name, 0);
}
private boolean isFlying;
public boolean isFlying() {
return isFlying;
}
public void setFlying(boolean flying) {
isFlying = flying;
}
public void attack(Hero hero){
System.out.println(this.getName() + "은 " + hero.getName() + "과 싸움을 했다.")ㅣ
}
}
public class Main {
public static void main(String[] args) {
Hero hero = new Hero("슈퍼맨");
Hero hero2 = new Hero("배트맨");
hero.attack(hero2);
}
}
- 추상 메소드 (abstract)
해당 abstract class를 상속받으면 그 클래스에 속한 abstract method는 반드시 오버라이드를 통해 구현해야 한다.
추상 클래스를 구현할 수는 없음.
public abstract class Charater extends Person{
public abstract void attack(Hero hero);
}
public class Hero extends Charater{
public Hero(String name){
setName(name);
}
private boolean isFlying;
public boolean isFlying() {
return isFlying;
}
public void setFlying(boolean flying) {
isFlying = flying;
}
@Override
public void attack(Hero hero){
System.out.println(this.getName() + "은 " + hero.getName() + "과 싸움을 했다.");
}
}
- 인터페이스(interface)
추상 메소드랑 비슷
자바는 상속을 단일 상속만 지원을 하지만 인터페이스를 통해 여러 개의 특징을 사용할 수 있음. (다중 상속의 효)
즉, 좀 더 유연한 확장 가능
interface ICharacter {
void attack(Person person);
}
public class Magician extends Charater implements ICharacter {
@Override
public void attack(Person person) {
}
@Override
public void attack(Hero hero) {
}
}
Charater charater = new Hero("슈퍼맨2");
Magician magician = new Magician();
Charater magician2 = new Magician();
이런 식으로 사용이 가능하다.
+ instanceof 활용
if(magician2 instanceof Magician){ }
+ ArrayList 활용
여러가지 타입을 하나의 상위 개념으로 담을 수 있다 - 다형성의 장점
ArrayList<Charater> characterArrayList = new ArrayList<>();
characterArrayList.add(magician);
characterArrayList.add(magician2);
- 제네릭
public class Main {
public static void main(String[] args) {
print("안녕");
print(1);
print(3L);
print(true);
}
// 제네릭
public static <T> void print(T type) {
System.out.println(type);
}
}
- 스레드(thread)
여러가지 일 동시에 처리 가능
new Thread 부분 복붙해서 스레드 여러 도 돌릴 수 있음.
public static void main(String[] args) {
System.out.println("1");
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0 ; i< 5 ; i++){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + " : " + i);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
System.out.println("2");
}
thread 하나 돌리는 것은 람다식으로 간단하게 표현이 가능하다.
-람다식
추상메소드를 하나만 가지는 인터페이스는 간단하게 람다식으로 표현 가능
new Thread(() -> {
for (int i = 0 ; i < 5 ; i++){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + " : " + i);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
'코테뿌수기 - java > 이론 정리' 카테고리의 다른 글
Java 코테 핵심이론 (그리디, 정수론) (0) | 2022.12.28 |
---|---|
Java 코테 핵심이론 (DFS, BFS, 이진탐색) (0) | 2022.12.28 |
Java 코테 핵심이론 (버블정렬, 선택정렬) (0) | 2022.12.28 |
Java 코테 핵심이론 (배열, 리스트, 구간 합, 스택, 큐) (0) | 2022.12.27 |
Java 코테 핵심이론 (시간복잡도, 디버깅) (0) | 2022.12.27 |