본문 바로가기
Java

[Java] 기본 문법 정리 - 자료형과 변수, 연산자, 조건문

by clolee 2025. 3. 19.

자바 코딩테스트에 자주 등장하는 핵심 문법 정리. 

📌 자바 코딩테스트 필수 문법 목록

  1. 자료형과 변수
  2. 연산자
  3. 조건문 (if, switch)
  4. 반복문 (for, while, do-while)
  5. 배열과 리스트 (Array, ArrayList)
  6. 문자열 다루기 (String, StringBuilder)
  7. 컬렉션 프레임워크 (List, Set, Map)
  8. 정렬 (Arrays.sort, Collections.sort, Comparator)
  9. 스택과 큐 (Stack, Queue, Deque)
  10. 해시맵과 해시셋 (HashMap, HashSet)
  11. 이진 탐색 (Binary Search)
  12. 우선순위 큐 (PriorityQueue)
  13. 재귀함수
  14. DFS & BFS
  15. 동적 프로그래밍 (DP)
  16. 비트 연산
  17. 수학 관련 라이브러리 (Math 클래스 활용)
  18. 시간 복잡도 개념

1. 자료형과 변수

📍 기본 자료형

자바의 기본 자료형(Primitive Type)은 총 8가지.

 

자료형  크기  기본값  설명
byte 1 byte 0 작은 정수를 저장할 때 사용 (범위: -128 ~ 127)
short 2 byte 0 byte보다 큰 정수 (범위: -32,768 ~ 32,767)
int 4 byte 0 기본적인 정수형 (범위: -21억 ~ 21억)
long 8 byte 0L 더 큰 정수 저장 (범위: 어마어마하게 큼)
float 4 byte 0.0f 실수 저장 (정확도 낮음)
double 8 byte 0.0d 실수 저장 (정확도 높음)
char 2 byte '\u0000' 한 글자를 저장 (예: 'A')
boolean 1 bit false 참(true) 또는 거짓(false)

📍 기본 자료형 예제


  
public class DataTypeExample {
public static void main(String[] args) {
int num = 100; // 정수형
long bigNum = 10000000000L; // long형은 끝에 L을 붙여야 함
double pi = 3.14159; // 실수형
char letter = 'A'; // 문자형
boolean flag = true; // 논리형
System.out.println("int 값: " + num);
System.out.println("long 값: " + bigNum);
System.out.println("double 값: " + pi);
System.out.println("char 값: " + letter);
System.out.println("boolean 값: " + flag);
}
}

📌 long을 사용할 때 L을 붙이는 걸 기억하자.


2. 연산자

자바의 연산자는 크게 산술, 비교, 논리, 비트, 대입, 삼항, instanceof 연산자 등이 있음.

📌 1. 산술 연산자 (Arithmetic Operators)

기본적인 사칙연산을 수행하는 연산자
정수 연산 시 몫만 반환 (/ 연산)
우선순위: * = / = % > + = -

연산자  설명  예제 (a = 10, b = 3)  결과
+ 덧셈 a + b 13
- 뺄셈 a - b 7
* 곱셈 a * b 30
/ 나눗셈 (몫) a / b 3 (정수 나눗셈)
% 나머지 연산 a % b 1

📍 예제: 산술 연산자


  
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("덧셈: " + (a + b)); // 13
System.out.println("나눗셈: " + (a / b)); // 3 (정수 나눗셈)
System.out.println("나머지: " + (a % b)); // 1
}
}

 

📌 2. 증가/감소 연산자 (Increment & Decrement)

변수 값을 1씩 증가 또는 감소
전위(++a, --a)와 후위(a++, a--) 연산 방식이 다름
후위 연산은 기존 값을 사용 후 증가/감소, 전위 연산은 먼저 증가/감소 후 사용

연산자  설명  예제 (a = 5)  결과
++a 전위 증가 ++a 6 (먼저 증가)
a++ 후위 증가 a++ 5 (사용 후 증가)
--a 전위 감소 --a 4 (먼저 감소)
a-- 후위 감소 a-- 5 (사용 후 감소)

📍 예제: 증가/감소 연산자


  
public class IncrementDecrement {
public static void main(String[] args) {
int x = 5;
System.out.println(++x); // 6 (먼저 증가)
System.out.println(x++); // 6 (사용 후 증가)
System.out.println(x); // 7
}
}

 

📌 3. 비교 연산자 (Comparison Operators)

두 값을 비교하여 true 또는 false 반환
==과 !=는 기본 데이터 타입에서만 값 비교 (객체 비교 시 equals() 사용)

연산자  설명  예제 (a = 10, b = 3)  결과
== 같음 a == b false
!= 다름 a != b true
> 초과 a > b true
< 미만 a < b false
>= 이상 a >= 10 true
<= 이하 b <= 3 true

📍 예제: 비교 연산자


  
public class ComparisonOperators {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a > b); // true
System.out.println(a == b); // false
}
}

 

📌 4. 논리 연산자 (Logical Operators)

논리값(true 또는 false)을 결합하여 논리 연산 수행
단축 평가(Short-Circuit Evaluation) 적용 → 결과가 확정되면 나머지 연산을 실행하지 않음

연산자 설명 
실행 조건  예제 (a = 10, b = 3)  결과
&& AND 연산 (둘 다 true여야 true) 앞이 false면 뒤를 실행 안 함 a > 5 && b < 5 true
|| OR 연산 (하나라도 true면 true) 앞이 true면 뒤를 실행 안 함 a > 5 || b < 5 true
! NOT 연산 (논리 반전) 항상 실행 !(a > b) false

 

📍 논리 연산자 예제


  
public class LogicalOperators {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("AND 연산: " + (a > 5 && b < 5)); // true
System.out.println("OR 연산: " + (a > 10 || b < 5)); // true
System.out.println("NOT 연산: " + !(a > b)); // false
}
}

📌 단축 평가 (Short-Circuit Evaluation)

&&와 || 연산자는 앞쪽 연산 결과가 확정되면 뒤쪽 연산을 실행하지 않음

 

예제: &&에서 첫 번째 조건이 false이면 두 번째 조건 실행 안 함


  
public class ShortCircuitExample {
public static void main(String[] args) {
int x = 5;
boolean result = (x > 10) && (++x > 5); // x > 10이 false라 두 번째 연산 실행 안 함
System.out.println("x: " + x); // 5 (x 증가 안 됨)
System.out.println("결과: " + result); // false
}
}

 

예제: ||에서 첫 번째 조건이 true이면 두 번째 조건 실행 안 함


  
public class ShortCircuitExample2 {
public static void main(String[] args) {
int y = 3;
boolean result = (y < 5) || (++y > 5); // y < 5가 true이므로 두 번째 연산 실행 안 함
System.out.println("y: " + y); // 3 (y 증가 안 됨)
System.out.println("결과: " + result); // true
}
}

 

📌 5. 비트 연산자 (Bitwise Operators)

비트 단위 연산을 수행하는 연산자
&, |, ^는 boolean 값에서도 사용 가능
<<, >>는 비트 이동 연산 (시프트 연산)

연산자 설명 예제 (a = 5 (0101), b = 3 (0011)) 결과
& 비트 AND (둘 다 1이면 1, 아니면 0) a & b → 0101 & 0011 0001 (1)
| 비트 OR (둘 중 하나라도 1이면 1) a | b → 0101 | 0011 0111 (7)
^ 비트 XOR (다르면 1, 같으면 0) a ^ b → 0101 ^ 0011 0110 (6)
~ 비트 NOT (비트를 반전, 0 ↔ 1) ~a → ~0101 1010 (-6, 2의 보수)
<< 왼쪽 시프트 (n << k → n × 2^k) a << 1 → 0101 << 1 1010 (10)
>> 오른쪽 시프트 (n >> k → n ÷ 2^k) a >> 1 → 0101 >> 1 0010 (2)
>>> 오른쪽 시프트 (부호 비트 포함) a >>> 1 0010 (2)

📍 예제: 비트 연산자


  
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5, b = 3;
System.out.println(a & b); // 1
System.out.println(a | b); // 7
System.out.println(a ^ b); // 6
}
}

 

📌 6. 대입 연산자 (Assignment Operators)

변수에 값을 저장하는 연산자
산술 연산자와 결합 가능 (+=, -=, *=, /= 등)

연산자 설명  예제 (a = 5) 결과
= 값 대입 a = 10 10
+= 덧셈 후 대입 a += 3 8
-= 뺄셈 후 대입 a -= 2 3

 

📌 7. 삼항 연산자 (Ternary Operator)

조건문을 간결하게 표현하는 연산자 (조건 ? 참값 : 거짓값)


  
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // 20

 

📌 8. instanceof 연산자

instanceof 연산자란?
✔ 객체가 특정 클래스의 인스턴스인지 확인하는 연산자
객체가 해당 클래스 또는 그 하위 클래스의 인스턴스이면 true 반환
객체가 null이면 항상 false 반환
다운캐스팅(Upcasting 후 다시 원래 타입으로 변환)할 때 필수적으로 사용됨

 

📌 1. instanceof 연산자 기본 문법


  
객체 instanceof 클래스

객체가 해당 클래스의 인스턴스이면 true
객체가 null이면 false

 

📌 2. instanceof 연산자 예제

📍 (1) 기본 사용 예제


  
class Animal {}
class Dog extends Animal {}
public class InstanceofExample {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
Animal a2 = new Dog(); // 업캐스팅
System.out.println(a instanceof Animal); // true
System.out.println(d instanceof Animal); // true (자식 클래스도 부모 타입 포함)
System.out.println(a instanceof Dog); // false (부모 객체는 자식 타입이 아님)
System.out.println(a2 instanceof Dog); // true (업캐스팅된 객체는 실제 객체 타입 기준)
}
}

 

Dog 객체는 Animal을 상속받았으므로 Animal 타입으로도 인식됨
하지만 Animal 객체는 Dog 타입이 아니므로 false 반환

 

📍 (2) null 체크


  
public class InstanceofNullExample {
public static void main(String[] args) {
Dog d = null;
System.out.println(d instanceof Dog); // false (null은 어떤 클래스에도 속하지 않음)
}
}

 

객체가 null이면 instanceof 연산 결과는 항상 false

 

📌 3. 업캐스팅(Upcasting) & 다운캐스팅(Downcasting)과 instanceof

📍 (1) 업캐스팅 후 다운캐스팅 시 instanceof 활용


  
class Parent {}
class Child extends Parent {
void childMethod() {
System.out.println("자식 클래스의 메서드");
}
}
public class UpcastingDowncasting {
public static void main(String[] args) {
Parent p = new Child(); // 업캐스팅
System.out.println(p instanceof Parent); // true
System.out.println(p instanceof Child); // true (실제 객체는 Child)
// 안전한 다운캐스팅 (instanceof로 확인 후 변환)
if (p instanceof Child) {
Child c = (Child) p;
c.childMethod(); // 정상 실행
}
}
}

📌 출력 결과


  
true
true
자식 클래스의 메서드

업캐스팅된 객체라도 실제 객체가 Child이므로 true
다운캐스팅 전 instanceof로 체크하면 ClassCastException 방지 가능

 

📍 (2) instanceof를 사용하지 않고 다운캐스팅하면 오류 발생


  
public class UnsafeDowncasting {
public static void main(String[] args) {
Parent p = new Parent();
Child c = (Child) p; // 런타임 오류 발생 (ClassCastException)
}
}

📌 출력 결과 (런타임 오류 발생!)


  
Exception in thread "main" java.lang.ClassCastException: Parent cannot be cast to Child

부모 클래스 객체를 자식 클래스로 강제 형변환하면 ClassCastException 발생!
항상 instanceof로 확인 후 다운캐스팅해야 안전함

 

📌 4. instanceof와 인터페이스

객체가 특정 인터페이스를 구현했는지 확인할 때도 사용 가능


  
interface Animal {}
class Dog implements Animal {}
public class InstanceofInterface {
public static void main(String[] args) {
Dog d = new Dog();
System.out.println(d instanceof Animal); // true
}
}

인터페이스를 구현한 클래스 객체도 instanceof로 확인 가능!

 


3. 조건문 (if, switch)

📍 if 문


  
public class IfExample {
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 {
System.out.println("C 학점");
}
}
}

📍 switch-case 문

  • 조건이 여러 개일 때, switch 문을 쓰면 깔끔함
  • break를 넣지 않으면 아래 case들도 실행됨 (fall-through)
  • default는 모든 case에 해당하지 않을 때 실행됨

  
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("월요일");
break;
case 2:
System.out.println("화요일");
break;
case 3:
System.out.println("수요일");
break;
default:
System.out.println("기타 요일");
}
}
}

📌 break를 안 쓰면 다음 case로 넘어감 → 조심!

 

댓글