본문 바로가기
Web & Mobile/JAVA

Lecture 25 - Java(6) 클래스, 접근제어자, 이클립스 환경 구축법

by Bennyziio 2023. 6. 20.
반응형

클래스

모듈(X)
    패키지(도메인)
        클래스 배치
            import 패키지명.(.여러개.).클래스

            (패키지명)
            디렉토리.디렉토리.디렉토리.클래스

        has - a : 멤버변수(instance)
        is - a : 상속

        상속
        - extends 클래스(한개) : 단일 상속(다중 상속 X)
        - 생성자와 초기화 블럭은 상속 X
        - final
            class - 상속불가
            method - 오버라이드 불가
            멤버변수/지역변수 - 상수
        - 오버라이드(재정의) 조건 : 메서드 이름, 타입, 매개변수가 같아야 한다
        - super
        - super()

접근 제어자(access modifier)
접근 제어자는 멤버 또는 클래스에 사용되어, 해당하는 멤버 또는 클래스를 외부에서 접근하지 못하도록 제한하는 역할을 한다.

접근 제어자가 사용 될 수 있는 곳 - 클래스, 멤버변수, 메서드, 생성자
private - 같은 클래스 내에서만 접근이 가능하다.
default - 같은 패키지 내에서만 접근이 가능하다.
protected - 같은 패키지 내에서, 그리고 다른 패키지의 자손클래스에서 접근이 가능하다.
public - 접근 제한이 전혀 없다.

접근 범위가 넓은 쪽에서 좁은 쪽의 순으로 왼쪽부터 나열하면 다음과 같다.
public > protected > (default) > private

public은 접근 제한이 전혀 없는 것이고, private은 같은 클래스 내에서만 사용하도록 제한하는 가장 높은 제한이다. 그리고 default는 같은 패키지내의 클래스에서만 접근이 가능하도록 하는 것이다.
마지막으로 protected는 패키지에 관계없이 상속관계에 있는 자손클래스에서 접근할 수 있도록 하는 것이 제한목적이지만, 같은 패키지 내에서도 접근이 가능하다. 그래서 protected가 default보다 접근 범위가 더 넓다.

접근 제어자를 이용한 캡슐화
클래스나 멤버, 주로 멤버에 접근 제어자를 사용하는 이유는 클래스의 내부에 선언된 데이터를 보호하기 위해서이다.
데이터가 유효한 값을 유지하도록, 또는 비밀번호와 같은 데이터를 외부에서 함부로 변경하지 못하도록 하기 위해서는 외부로부터의 접근을 제한하는 것이 필요하다. 이것을 데이터 감추기(data hiding)라고 하며, 객체지향개념의 캡슐화(encapsulation)에 해당하는 내용이다.

접근 제어자를 사용하는 이유
- 외부로부터 데이터를 보호하기 위해
- 외부에는 불필요한, 내부적으로만 사용되는, 부분을 감추기 위해서

DataMainEx01

class DataEx01 {
    private String data1 = "홍길동";
    String data2 = "박문수";
    public String data3 = "이몽룡";
}

public class DataMainEx01 {
    public static void main(String[] args) {
        DataEx01 d = new DataEx01();

        System.out.println(d.data1);
        System.out.println(d.data2);
        System.out.println(d.data3);
    }
}

에러 발생!!

class DataEx01 {
    //private String data1 = "홍길동";
    // default
    String data2 = "박문수";
    public String data3 = "이몽룡";
}

public class DataMainEx01 {
    public static void main(String[] args) {
        DataEx01 d = new DataEx01();

        //System.out.println(d.data1);
        System.out.println(d.data2);
        System.out.println(d.data3);
    }
}

접근 제어

캡슐화
    접근 제어자를 통한 멤버 변수 통제
    private 변수명;

    public / protected 메서드명 : 멤버변수에 접근
setter : set : writing
getter : get : reading

class Time {
    private int hour;
    private int minute;
    private int second;
}

public class TimeEx01 {
    public static void main(String[] args) {
        Time t = new Time();
        t.hour = 10;
    }
}

class Time {
    private int hour;
    private int minute;
    private int second;

    // reading : get
    public int getHour() {
        return hour;
    }

    public int getMinute() {
        return minute;
    }

    public int getSecond() {
        return second;
    }

    // writing : set
    public void setHour(int hour) {
        this.hour = hour;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }

    public void setSecond(int second) {
        this.second = second;
    }
}

public class TimeEx01 {
    public static void main(String[] args) {
        Time t = new Time();
        //t.hour = 10;

        t.setHour(10);
        t.setMinute(20);
        t.setSecond(30);

        System.out.println(t.getHour());
        System.out.println(t.getMinute());
        System.out.println(t.getSecond());
    }
}

class Time {
    private int hour;
    private int minute;
    private int second;

    // reading : get
    public int getHour() {
        return hour;
    }

    public int getMinute() {
        return minute;
    }

    public int getSecond() {
        return second;
    }

    // writing : set
    public void setHour(int hour) {
        if(hour < 0 || hour > 25) {
            this.hour = 0;
        } else {
            this.hour = hour;
        }
    }

    public void setMinute(int minute) {
        if(minute < 0 || minute > 61) {
            this.minute = 0;
        } else {
            this.minute = minute;
        }
    }

    public void setSecond(int second) {
        if(second < 0 || second > 61) {
            this.second = 0;
        } else {
            this.second = second;
        }
    }
}

public class TimeEx01 {
    public static void main(String[] args) {
        Time t = new Time();
        //t.hour = 10;

        t.setHour(-1);
        t.setMinute(20);
        t.setSecond(30);

        System.out.println(t.getHour());
        System.out.println(t.getMinute());
        System.out.println(t.getSecond());
    }
}

TimeTest

public class TimeTest {
    public static void main(String[] args) {
        Time t = new Time(12, 35, 30);
        System.out.println(t);
        //t.hour = 13;
        t.setHour(t.getHour()+1);
        System.out.println(t);
    }
}

class Time {
    private int hour, minute, second;

    Time (int hour, int minute, int second) {
        setHour(hour);
        setMinute(minute);
        setSecond(second);
    }

    public int getHour() {
        return hour;
    }
    public void setHour(int hour) {
        if (hour < 0 || hour > 23) return;  // 여기서 return은 충족시 빠져나가라
        this.hour = hour;
    }
    public int getMinute() {
        return minute;
    }
    public void setMinute(int minute) {
        if (minute < 0 || minute > 59) return;
        this.minute = minute;
    }
    public int getSecond() {
        return second;
    }
    public void setSecond(int second) {
        if (second < 0 || second > 59) return;
        this.second = second;
    }
    public String toString() {
        return hour + ":" + minute + ":" + second;
    }
}

제어자(modifier)의 조합
제어자를 조합해서 사용할 때 주의해야 할 사항
1. 메서드에 static과 abstract를 함께 사용할 수 없다.
    static 메서드는 몸통이 있는 메서드에만 사용할 수 있기 때문이다.
2. 클래스에 abstract와 final을 동시에 사용할 수 없다.
    클래스에 사용되는 final은 클래스를 확장할 수 없다는 의미이고 abstract는 상속을 통해서 완성되어야 한다는 의미이므로 서로 모순되기 때문이다.
3. abstract 메서드의 접근 제어자가 private일 수 없다.
    abstract 메서드는 자손클래스에서 구현해주어야 하는데 접근 제어자가 private이면, 자손클래스에서 접근할 수 없기 때문이다.
4. 메서드에 private과 final을 같이 사용할 필요는 없다.
    접근 제어자가 private인 메서드는 오버라이딩 될 수 없기 대문이다. 이 둘 중 하나만 사용해도 의미가 충분하다.

이클립스 Java 환경 세팅법

이클립스
자바 소스 넣는법
1. 프로젝트(애플리케이션 1)
2. 패키지
3. 자바 소스

자바 소스 넣는 법

java.lang패키지
java.lang패키지는 자바프로그래밍에 가장 기본이 되는 클래스들을 포함하고 있다. 그렇기 때문에 java.lang패키지의 클래스들은 import문 없이도 사용할 수 있게 되어 있다. 즉 java.lang패키지 외의 것들은 모두 import를 써야한다는 의미다

Object 클래스
Object 클래스는 모든 클래스의 최고 조상이기 때문에 Object클래스의 멤버들은 모든 클래스에서 바로 사용 가능하다.

ObjectEx01

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
	}

}

o랑 o.toString은 같은 내용을 출력한다

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
	}

}

hashcode를 사용하여 주소 위치를 알려준다

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
	}

}

hashcode를 이용한 주소 위치를 hexa값으로 나타냈다

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
	}
}

getClass를 이용하여 자바에서 만든 내부패키지를 출력한다

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
	}
}

o와 o1의 주소 위치 비교 방법 1

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
	}
}

o와 o1의 주소 위치 비교 방법 2

public class Person {
	private String name;
	private int age;
}
public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person();
		
		System.out.println(p);
		System.out.println(p.toString());
	}
}

toString은 오브젝트를 확인 하는데 쓰인다

public class Person {
	private String name;
	private int age;
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "[" + this.name + ": " + this.age + "]";
	}
}
public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person("홍길동", 30);
		
		System.out.println(p);
		System.out.println(p.toString());
	}
}

Person 오버라이드

위와 같은 방법으로도 오버라이드를 할 수 있다

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person("홍길동", 30);
		
		System.out.println(p);
		System.out.println(p.toString());
		
		String str = new String("Hello");
		
		System.out.println(str);
		System.out.println(str.toString());
	}
}

str은 오라클이 준거고 내부적으로 오버라이딩이 되어 있다(오버라이드가 아니였으면 주소가 찍혔어야했다)

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person("홍길동", 30);
		
		System.out.println(p);
		System.out.println(p.toString());
		
		String str = new String("Hello");
		
		System.out.println(str);
		System.out.println(str.toString());
		System.out.printf("%x%n", str.hashCode());
	}
}

참조주소를 알고 싶으면 hashcode를 써준다

equals(Object obj)

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		// 주소
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		// 내용, 데이터 비교
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person("홍길동", 30);
		
		System.out.println(p);
		System.out.println(p.toString());
		
		String str = new String("Hello");
		
		System.out.println(str);
		System.out.println(str.toString());
		System.out.printf("%x%n", str.hashCode());
		
		Person p1 = new Person("홍길동", 30);
		Person p2 = new Person("홍길동", 30);
		
		if (p1 == p2) {
			System.out.println("주소 같다");
		} else {
			System.out.println("주소 다르다");
		}
		if (p1.equals(p2)) {
			System.out.println("데이터 같다");
		} else {
			System.out.println("데이터 다르다");
		}
	}
}

오버라이드 된 p1 == p2는 주소값을 비교하는데 p1.equals(p2)는 객체의 내용을 비교하게 된다.

public class ObjectEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
		Object o = new Object();
		
		// 객체 참조 주소
		System.out.println(o);
		System.out.println(o.toString());
		
		System.out.println(o.hashCode());
		System.out.printf("%x%n", o.hashCode());
		System.out.println(o.getClass());
		
		Object o1 = new Object();
		// 주소
		if(o == o1) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		// 내용, 데이터 비교
		if(o.equals(o1)) {
			System.out.println("주소 같음");
		} else {
			System.out.println("주소 다름");
		}
		
		Person p = new Person("홍길동", 30);
		
		System.out.println(p);
		System.out.println(p.toString());
		
		String str = new String("Hello");
		
		System.out.println(str);
		System.out.println(str.toString());
		System.out.printf("%x%n", str.hashCode());
		
		Person p1 = new Person("홍길동", 30);
		Person p2 = new Person("홍길동", 30);
		
		if (p1 == p2) {
			System.out.println("주소 같다");
		} else {
			System.out.println("주소 다르다");
		}
		if (p1.equals(p2)) {
			System.out.println("데이터 같다");
		} else {
			System.out.println("데이터 다르다");
		}
		
		String str1 = new String("Hello");
		String str2 = new String("Hello");
		
		if (str1 == str2) {
			System.out.println("주소 같다");
		} else {
			System.out.println("주소 다르다");
		}
		if (str1.equals(str2)) {
			System.out.println("데이터 같다");
		} else {
			System.out.println("데이터 다르다");
		}
	}
}

str1, str2도 위 p1, p2와 같다

String클래스
기존의 다른 언어에서는 문자열을 char형의 배열로 다루었으나 자바에서는 문자열을 위한 클래스를 제공한다. 그 것이 바로 String클래스인데, String클래스는 문자열을 저장하고 이를 다루는데 필요한 메서드를 제공한다.

String클래스의 생성자와 메서드

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());	
	}
}

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
	}

}

length

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
	}

}

문자열 특정 위치 출력

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
	}

}

마지막 문자

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
	}

}

일부 문자열 추출

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("l");
		System.out.println(idx1);
	}

}

문자열 검색

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
	}

}

문자열 검색 : 없는 문자일 경우 -1 출력됨

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
	}

}

문자열 검색 왼쪽 0 부터 오른쪽으로 카운트하면서 마지막 l의 위치를 출력한다

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		boolean b1 = str1.startsWith("he");
		System.out.println(b1);
	}

}

문자열의 존재 여부

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
	}

}

문자열의 존재 여부

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
	}

}

문자열 치환

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
	}

}

문자열 결합

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
		
		// 대소문자 변환
		System.out.println("hello".toUpperCase());
		System.out.println("HELLO".toLowerCase());
	}

}

대소문자 변환

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
		
		// 대소문자 변환
		System.out.println("hello".toUpperCase());
		System.out.println("HELLO".toLowerCase());
		
		// 공백 제거
		String oStr1 = "     Hello    ";
		System.out.println(oStr1);
		System.out.println(oStr1.trim());
	}

}

공백제거

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
		
		// 대소문자 변환
		System.out.println("hello".toUpperCase());
		System.out.println("HELLO".toLowerCase());
		
		// 공백 제거
		String oStr1 = "     Hello    ";
		System.out.println(oStr1);
		System.out.println(oStr1.trim());
		
		// 구분자 중심 문자열 분리
		String str4 = "apple,banana,pineapple,kiwi";
		String[] arr1 = str4.split(",", 2);
		for(String arr : arr1) {
			System.out.println(arr);
		}
	}

}

구분자 중심 문자열 분리 : 2번째까지만 분리

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
		
		// 대소문자 변환
		System.out.println("hello".toUpperCase());
		System.out.println("HELLO".toLowerCase());
		
		// 공백 제거
		String oStr1 = "     Hello    ";
		System.out.println(oStr1);
		System.out.println(oStr1.trim());
		
		// 구분자 중심 문자열 분리
		String str4 = "apple,banana,pineapple,kiwi";
		String[] arr1 = str4.split(",", 2);
		for(String arr : arr1) {
			System.out.println(arr);
		}
		
		// printf => 형식 문자열
		String fstr = String.format("%s-%s-%s", "사과", "키위", "딸기");
		System.out.println(fstr);
	}

}

형식 문자열

public class StringEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 생성
		String str1 = "Hello";
		String str2 = new String("Hello World");
		
		char[] cArr = {'H', 'e', 'l', 'l', 'o'};
		String str3 = new String(cArr);
		
		System.out.println(str1);
		System.out.println(str1.toString());
		
		// equals - 문자열의 내용 비교
		
		// length
		System.out.println(str1.length());
		System.out.println("Hello World".length());
		
		// 문자열(String) -> 문자(char)
		char ch1 = str1.charAt(0);
		char ch2 = str1.charAt(1);
		System.out.println(ch1);
		
		// str1 마지막 문자
		System.out.println(str1.charAt(str1.length() - 1));
		
		// 문자열 -> 일부 문자열 추출
		String pstr1 = str1.substring(3);
		System.out.println(pstr1);
		String pstr2 = str1.substring(3, 4);
		System.out.println(pstr2);
		
		// 문자열 검색(Hello)
		int idx1 = str1.indexOf("z");
		System.out.println(idx1);
		int idx2 = str1.lastIndexOf("l");
		System.out.println(idx2);
		
		// 문자열의 존재여부(true/false)
		// constains / endsWith
		boolean b1 = str1.startsWith("He");
		System.out.println(b1);
		
		// 문자열 치환
		String rstr = str1.replaceAll("Hello", "안녕");
		System.out.println(rstr);
		
		// 문자열 결합 : +
		String jstr = str1.concat(" 안녕");
		System.out.println(jstr);
		
		// 대소문자 변환
		System.out.println("hello".toUpperCase());
		System.out.println("HELLO".toLowerCase());
		
		// 공백 제거
		String oStr1 = "     Hello    ";
		System.out.println(oStr1);
		System.out.println(oStr1.trim());
		
		// 구분자 중심 문자열 분리
		String str4 = "apple,banana,pineapple,kiwi";
		String[] arr1 = str4.split(",", 2);
		for(String arr : arr1) {
			System.out.println(arr);
		}
		
		// printf => 형식 문자열
		String fstr = String.format("%s-%s-%s", "사과", "키위", "딸기");
		System.out.println(fstr);
		
		// split - join
		String fstr2 = String.join(",", arr1);
		System.out.println(fstr2);
	}

}

split - join : join

StringEx02

public class StirngEx02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(String arg : args) {
			System.out.println(arg);
		}
	}

}

Test1 hong gil dong -> Hong Gil Dong으로 변환

public class Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "hong gil dong";
		String[] arr1 = str1.split(" ");
		
		String sentence = "";
		
		for(int i=0; i<arr1.length; i++) {
			sentence += arr1[i].substring(0, 1).toUpperCase() + arr1[i].substring(1) + " ";
		}
		System.out.println(sentence);

	}

}

Test 2 주민번호체크

public class Test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "880518-1237611";
		String str2 = str1.replaceAll("-", "");
		System.out.println(str2);
		int[] carr1 = {2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5};
		
		int sum = 0;
		for(int i=0; i<carr1.length; i++) {
			sum += (Integer.parseInt(str2.substring(i, i+1)) * carr1[i]);
		}
		int last = Integer.parseInt(str2.substring(12, 13));
		
		int result = (11 -(sum % 11)) % 10;
		
		if(last == result) {
			System.out.println("맞음");
		} else {
			System.out.println("틀림");
		}
	}

}

argument로 하는 법

public class Test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = args[0];
		String str2 = str1.replaceAll("-", "");
		System.out.println(str2);
		int[] carr1 = {2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5};
		
		int sum = 0;
		for(int i=0; i<carr1.length; i++) {
			sum += (Integer.parseInt(str2.substring(i, i+1)) * carr1[i]);
		}
		int last = Integer.parseInt(str2.substring(12, 13));
		
		int result = (11 -(sum % 11)) % 10;
		
		if(last == result) {
			System.out.println("맞음");
		} else {
			System.out.println("틀림");
		}
	}

}
반응형

댓글