정보처리기사 실기 자바 개념정리

Alchemist·2025년 10월 5일

정보처리기사

목록 보기
97/114

✨ 1장. 클래스(Class)와 객체(Object)

📘 개념 설명

  • 자바에서 클래스는 객체를 생성하기 위한 설계도, 객체는 이 설계도로 만들어진 실체(Instance)이다.
class Car {
    String name;
    int speed;
    void run() { System.out.println(name + "이 달립니다!"); }
}

public class Main {
    public static void main(String[] args){
        Car c = new Car();
        c.name = "소나타";
        c.run();
    }
}

출력:

소나타이 달립니다!
  • class : 객체의 속성(필드)과 동작(메서드)을 정의.
  • new : 객체를 메모리에 생성.
  • this : 현재 객체 자신을 가리킴.
  • 생성자는 클래스 이름과 같고 반환형이 없다.

📝 연습문제

class A {
    int x;
    A(int x){ this.x = x; }
}

public class Main {
    public static void main(String[] args){
        A obj1 = new A(5);
        A obj2 = obj1;
        obj2.x = 10;
        System.out.println(obj1.x);
    }
}

✅ 해설

  • obj1obj2는 같은 객체를 참조한다.
  • obj2.x = 10obj1.x에도 반영된다.

정답:

10

✨ 2장. 상속(Inheritance)과 오버라이딩(Overriding)

📘 개념 설명

  • 자바의 상속은 기존 클래스의 기능을 확장(extends) 하는 개념이다. 부모의 멤버를 자식이 물려받아 재사용할 수 있다.
class Parent {
    void show() { System.out.println("Parent"); }
}

class Child extends Parent {
    void show() { System.out.println("Child"); }
}

public class Main {
    public static void main(String[] args){
        Parent p = new Child();
        p.show();
    }
}

출력:

Child
  • 오버라이딩: 상속받은 메서드를 같은 이름, 매개변수, 반환형으로 재정의
  • 동적 바인딩: 실행 시점에 실제 객체 타입(Child) 기준으로 메서드 결정

📝 연습문제

class Parent {
    int x = 100;
    int getX() { return x; }
}

class Child extends Parent {
    int x = 4000;
    int getX() { return x * 2; }
}

public class Main {
    public static void main(String[] args){
        Parent p = new Child();
        System.out.println(p.getX());
    }
}

✅ 해설

  • getX()는 오버라이딩 → 객체 타입(Child) 기준 호출
  • x는 필드 숨김 → 참조 타입(Parent) 기준 사용되지 않음

정답:

8000

✨ 3장. static(정적 멤버)과 Singleton 패턴

📘 개념 설명

  • static클래스 단위로 공유되는 영역이다. 모든 인스턴스가 같은 값을 본다.
class Counter {
    static int count = 0;
    Counter() { count++; }
}

public class Main {
    public static void main(String[] args){
        new Counter();
        new Counter();
        System.out.println(Counter.count);
    }
}

출력:

2

📝 연습문제

class Connection {
    private static Connection _inst = null;
    private int count = 0;

    static Connection get() {
        if(_inst == null)
            _inst = new Connection();
        return _inst;
    }

    void count(){ count++; }
    int getCount(){ return count; }
}

public class Main {
    public static void main(String[] args){
        Connection c1 = Connection.get();
        c1.count();
        Connection c2 = Connection.get();
        c2.count();
        System.out.println(c1.getCount());
    }
}

✅ 해설

  • static은 클래스 단위로 단 하나만 존재한다.
  • Connection.get()은 항상 동일 객체 반환.
  • count가 누적되어 2가 된다.

정답:

2

✨ 4장. 추상 클래스 & 인터페이스

📘 개념 설명

  • abstract 클래스는 상속을 위한 틀
  • 인터페이스(interface)는 모든 메서드가 추상(abstract)
abstract class Vehicle {
    abstract String getName(String val);
    void start(){ System.out.println("출발!"); }
}

class Car extends Vehicle {
    String getName(String val){ return "Car name : " + val; }
}

📝 연습문제

abstract class Vehicle {
    private String name;
    abstract String getName(String val);
    public String getName() { return "vehicle name:" + name; }
    public void setName(String val){ name = val; }
}

class Car extends Vehicle {
    public Car(String val){ setName(val); }
    public String getName(String val){ return "Car name : " + val; }
}

public class Main {
    public static void main(String[] args){
        Vehicle obj = new Car("Spark");
        System.out.println(obj.getName());
    }
}

✅ 해설

  • obj.getName()매개변수 없는 오버로딩 메서드 호출
  • name 필드는 "Spark"로 설정되어 있다.

정답:

vehicle name:Spark

✨ 5장. 예외 처리(Exception Handling)

📘 개념 설명

try {
    int x = 5 / 0;
} catch (ArithmeticException e) {
    System.out.println("0으로 나눌 수 없습니다");
} finally {
    System.out.println("항상 실행");
}

📝 연습문제

public class Main {
    public static void main(String[] args){
        int a = 5, b = 0;
        try {
            System.out.print(a / b);
        } catch (ArithmeticException e) {
            System.out.print("출력1");
        } finally {
            System.out.print("출력2");
        }
    }
}

✅ 해설

  • 5 / 0ArithmeticException 발생
  • catch"출력1" 출력, finally는 항상 실행

정답:

출력1출력2

✨ 6장. 배열(Array)과 참조(Reference)

📘 개념 설명

  • 배열은 참조형 객체이다.
  • 배열 원소로 객체를 저장하면, 각 칸에는 객체 주소값이 저장된다.
int[] arr = {1, 2, 3};
String[] s = {"A", "B"};

📝 연습문제

public class Main {
    public static void change(String[] data, String s){
        data[0] = s;
        s = "Z";
    }

    public static void main(String[] args){
        String data[] = {"A"};
        String s = "B";
        change(data, s);
        System.out.println(data[0] + s);
    }
}

✅ 해설

  • 배열(data)은 참조형이라 원소 변경이 반영됨.
  • 문자열(s)은 값 복사이므로 지역 변경은 영향 없음.

정답:

BB

✨ 7장. 람다(Lambda)와 함수형 인터페이스

📘 개념 설명

interface F { int apply(int x) throws Exception; }

public class Main {
    static int run(F f){
        try { return f.apply(3); }
        catch(Exception e){ return 7; }
    }
}
  • 람다는 함수형 인터페이스(메서드 1개)에서 사용 가능하며, 익명 함수처럼 작성된다.

📝 연습문제

public class Main {
    static interface F { int apply(int x) throws Exception; }
    static int run(F f){
        try { return f.apply(3); }
        catch(Exception e){ return 7; }
    }
    public static void main(String[] args){
        F f = (x) -> {
            if(x > 2) throw new Exception();
            return x * 2;
        };
        System.out.println(run(f) + run((int n) -> n + 9));
    }
}

✅ 해설

  • run(f) → 예외 발생 → 7
  • run((n)->n+9)3+9=12
  • 최종 7+12=19

정답:

19

✨ 8장. 문자열(String) 비교

📘 개념 설명

비교 방식의미
==참조 주소 비교
.equals()실제 내용 비교

📝 연습문제

String str1 = "Programming";
String str2 = "Programming";
String str3 = new String("Programming");

System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str1.equals(str3));

✅ 해설

  • str1 == str2 → true (리터럴 동일 참조)
  • str1 == str3 → false (new로 별도 객체)
  • .equals() → true (내용 동일)

정답:

true
false
true

✨ 9장. 재귀(Recursion)

📘 개념 설명

  • 재귀는 메서드가 자기 자신을 호출하는 구조이다. 항상 종료 조건을 포함해야 한다.

📝 연습문제

static int func(int[] a, int st, int end) {
    if (st >= end) return 0;
    int mid = (st + end) / 2;
    return a[mid] + Math.max(func(a, st, mid), func(a, mid + 1, end));
}

public static void main(String[] args){
    int[] data = {3,5,8,12,17};
    System.out.println(func(data,0,data.length-1));
}

✅ 해설

  • 중앙값 8 + 오른쪽의 최대 합 12 → 20

정답:

20

✨ 10장. 오버로딩(Overloading)과 오버라이딩(Overriding) 심화

📘 개념 설명

오버로딩(Overloading)
: 같은 이름, 다른 매개변수로 여러 메서드를 정의하는 것
→ 컴파일 시점에 결정됨 (정적 바인딩)

오버라이딩(Overriding)
: 상속 관계에서 부모 메서드를 재정의하는 것
→ 실행 시점에 결정됨 (동적 바인딩)

class Parent {
    void show(){ System.out.println("Parent"); }
}

class Child extends Parent {
    void show(){ System.out.println("Child"); }
}

📝 연습문제

public class Main {
    public static class Parent {
        public int x(int i){ return i + 2; }
        public static String id(){ return "P"; }
    }

    public static class Child extends Parent {
        public int x(int i){ return i + 3; }
        public String x(String s){ return s + "R"; }
        public static String id(){ return "C"; }
    }

    public static void main(String[] args){
        Parent ref = new Child();
        System.out.println(ref.x(2) + ref.id());
    }
}

✅ 해설

  • x(2) → 동적 바인딩으로 Child.x(int) 호출 → 5
  • id() → 정적 메서드, 참조 타입 기준 → Parent.id() = “P”

정답:

5P

✨ 11장. static 변수와 메모리 공유 구조

📘 개념 설명

static은 클래스 전체에서 공유되는 변수이다.
인스턴스와 무관하게 하나만 존재한다.

class Counter {
    static int count = 0;
    Counter(){ count++; }
}

모든 객체가 하나의 count를 공유한다.

📝 연습문제

class Connection {
    private static Connection inst = null;
    private int count = 0;

    static Connection get(){
        if(inst == null) inst = new Connection();
        return inst;
    }

    void count(){ count++; }
    int getCount(){ return count; }
}

public class Main {
    public static void main(String[] args){
        Connection c1 = Connection.get();
        c1.count();
        Connection c2 = Connection.get();
        c2.count();
        Connection c3 = Connection.get();
        c3.count();
        System.out.println(c1.getCount());
    }
}

✅ 해설

  • 모든 호출은 동일 객체를 참조
  • count() 총 3회 실행 → count = 3

정답:

3

✨ 12장. 추상 클래스(abstract)와 다형성

📘 개념 설명

추상 클래스:

  • 공통 구조를 정의하고 구체적 구현은 자식이 담당
  • abstract 메서드는 몸체가 없음

📝 연습문제

abstract class Vehicle {
    String name;
    abstract String getName(String val);
    public String getName(){ return "Vehicle name: " + name; }
}

class Car extends Vehicle {
    public Car(String val){ name = val; }
    public String getName(String val){ return "Car name: " + val; }
}

public class Main {
    public static void main(String[] args){
        Vehicle obj = new Car("Spark");
        System.out.println(obj.getName());
    }
}

✅ 해설

  • 호출된 메서드는 매개변수 없는 버전
  • "Vehicle name: Spark"

정답:

Vehicle name: Spark

✨ 13장. 예외 처리(Exception Handling)

📘 개념 설명

  • try ~ catch ~ finally 구조
try {
   int x = 10 / 0;
} catch (ArithmeticException e) {
   System.out.println("0으로 나눌 수 없습니다");
} finally {
   System.out.println("항상 실행");
}

📝 연습문제

public class Main {
    public static void main(String[] args){
        int a = 5, b = 0;
        try {
            System.out.println(a/b);
        } catch(ArithmeticException e) {
            System.out.print("출력1");
        } finally {
            System.out.print("출력5");
        }
    }
}

✅ 해설

  • a/b → 0으로 나눔 → ArithmeticException 발생
  • catch 실행 → "출력1"
  • finally 항상 실행 → "출력5"

정답:

출력1출력5

✨ 14장. 문자열(String) 비교

📘 개념 설명

  • == : 참조 주소 비교
  • .equals() : 문자열 내용 비교

📝 연습문제

String str1 = "Programming";
String str2 = "Programming";
String str3 = new String("Programming");

System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str1.equals(str3));

✅ 해설

  • 리터럴은 String Pool 공유 → str1 == str2 → true
  • new로 만든 객체는 별도 → str1 == str3 → false
  • 내용은 동일 → .equals() → true

정답:

true
false
true

✨ 15장. 배열 참조(Reference)와 스왑

📘 개념 설명

  • 배열은 참조형이므로, 스왑 시 주소가 교환된다.

📝 연습문제

public class Main {
    static class BO {
        public int v;
        public BO(int v){ this.v = v; }
    }
    public static void main(String[] args){
        BO a = new BO(1);
        BO b = new BO(2);
        BO c = new BO(3);
        BO[] arr = {a,b,c};
        BO t = arr[0];
        arr[0] = arr[2];
        arr[2] = t;
        arr[1].v = arr[0].v;
        System.out.println(a.v + "a" + b.v + "b" + c.v);
    }
}

✅ 해설

  • arr = {c,b,a}
  • b.v = c.v → 3
  • 최종 a=1, b=3, c=3

정답:

1a3b3

✨ 16장. 재귀 함수(Recursion)와 분할정복

📘 개념 설명

  • 재귀 함수는 자기 자신을 호출하며, 분할 → 정복 → 합침 패턴을 갖는다.

📝 연습문제

int func(int[] a, int st, int end){
    if(st >= end) return 0;
    int mid = (st + end) / 2;
    return a[mid] + Math.max(func(a, st, mid), func(a, mid+1, end));
}

배열 {3,5,8,12,17} 입력 시

✅ 해설

  • 중심값 8 + 오른쪽 최대 12 → 20

정답:

20

✨ 17장. 람다(Lambda)와 함수형 인터페이스

📘 개념 설명

  • 람다는 익명 함수로, 인터페이스의 단 하나의 메서드를 구현할 때 사용.
@FunctionalInterface
interface F { int apply(int x) throws Exception; }

📝 연습문제

F f = (x) -> {
    if(x > 2) throw new Exception();
    return x * 2;
};
System.out.print(run(f) + run((int n) -> n + 9));

✅ 해설

  • 첫 run은 예외 → 7
  • 두 번째 run → 12
  • 합 → 19

정답:

19

✨ 18장. 예외 + throws / throw 심화

📘 개념 설명

  • throws : 메서드가 예외를 호출자에게 던짐
  • throw : 예외를 실제 발생시킴

📝 연습문제

public class ExceptionHandling {
    public static void main(String[] args){
        int sum = 0;
        try {
            func();
        } catch (NullPointerException e) {
            sum += 1;
        } catch (Exception e) {
            sum += 10;
        } finally {
            sum += 100;
        }
        System.out.print(sum);
    }

    static void func() throws Exception {
        throw new NullPointerException();
    }
}

✅ 해설

  • func()NullPointerException 발생 → 첫 번째 catch 실행 → +1
  • finally는 항상 실행 → +100
  • 총합 101

정답:

101

✨ 19장. 제네릭(Generics)과 오버로딩 선택

📘 개념 설명

  • 오버로딩 시 가장 정확히 일치하는 타입의 메서드가 우선된다.

📝 연습문제

class Main {
  public static class Collection<T>{
    T value;
    Collection(T t){ value = t; }

    void print(){
       new Printer().print(value);
    }

    class Printer {
      void print(Integer a){ System.out.print("A" + a); }
      void print(Object a){ System.out.print("B" + a); }
      void print(Number a){ System.out.print("C" + a); }
    }
  }

  public static void main(String[] args){
      new Collection<>(0).print();
  }
}

✅ 해설

  • T = Integer
  • 가장 구체적인 print(Integer) 선택 → "A0"

정답:

A0

✨ 20장. 다형성과 메서드 호출 순서

📘 개념 설명

  • 자바의 다형성은 상속 + 오버라이딩 + 참조형 변환으로 이루어진다.
  • 부모 타입 변수로 자식 객체를 참조할 수 있고, 호출되는 메서드는 객체의 실제 타입 기준으로 결정된다.

📝 연습문제

public class Main {
    public static void main(String[] args){
        new Child();
        System.out.println(Parent.total);
    }
}

class Parent {
    static int total = 0;
    int v = 1;
    Parent(){
        total += (++v);
        show();
    }
    public void show(){ total += total; }
}

class Child extends Parent {
    int v = 10;
    Child(){
        v += 2;
        total += v++;
        show();
    }
    public void show(){ total += total * 2; }
}

✅ 해설

  • 부모 생성자 → total=2, show()(자식 버전 호출) → 6
  • 자식 생성자 → v=10→12, total+=12→18, show()(자식) → 18+36=54

정답:

54
profile
html_programming_language

0개의 댓글