Leveraging Programming Languages: Java Lang.

m_ngyeong·2025년 4월 14일
0

정보처리기사 이론

목록 보기
36/36
post-thumbnail

10. Leveraging Programming Languages


Java Lang.

클래스, 생성자, 멤버 변수, 메서드, for문, 연산 등

✅ Q1.

class Main {
    public static void main(String[] args) {
        Counter c = new Counter(3);
        int result = c.increase();
        System.out.println(c.val + result);
    }
}

class Counter {
    int val;

    public Counter(int val) {
        this.val = val;
    }

    public int increase() {
        for (int i = 0; i < 2; i++) {
            val += i;
        }
        return val;
    }
}

🖍️ 8

Counter c = new Counter(3); // val = 3
int result = c.increase();  // val += 0, val += 1 => val = 4
System.out.println(c.val + result); // 4 + 4 = 8

✅ Q2.

class Main {
    public static void main(String[] args) {
        A a = new A(1);
        a.n = 4;
        System.out.println(a.fun());
    }
}

class A {
    int n;

    public A(int n) {
        this.n = n;
    }

    public int fun() {
        int r = 0;
        for (int i = 1; i < n; i++) {
            r += i * 2;
        }
        return r;
    }
}

🖍️ 12

A a = new A(1);
a.n = 4;
--------------------------
i from 1 to 3 → r += i * 2  
i = 1 → r = 2  
i = 2 → r = 6  
i = 3 → r = 12

✅ Q3.

class Main {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "hello";
        String str3 = "hello world";
        String str4 = str3.replace('e', 'a');
        
        System.out.println(str1.equals(str2));
        System.out.println(str3.indexOf("world"));
        System.out.println(str4);
        System.out.println(str4.substring(0,3));
        System.out.println(str2.charAt(0));
    }
}

🖍️
true
6
hallo world
hal
h

System.out.println(str3.indexOf("world"));
System.out.println(str4.substring(0,3));
  • indexOf("world"): "world"라는 문자열이 처음 등장하는 인덱스 위치 반환
  • substring(0, 3): 인덱스 0부터 시작해서 3 직전까지(즉, 0, 1, 2 인덱스) 자름.
    "hallo world" → 인덱스 0부터 2까지는 "hal"
profile
ʚȉɞ

0개의 댓글