다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.
r.show();
System.out.println("s의 면적은 "+s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s를 포함합니다.");
}
(2,2)에서 크기가 8x7인 사각형
s의 면적은 36
t는 r을 포함합니다.
RectAngle.java
public class RectAngle {
int x;
int y;
int width;
int height;
int area;
RectAngle() {}
RectAngle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public int square(int width, int height) {
area = width*height; // 넓이 구하기
return area;
}
public void show(int x, int y, int width, int height) {
System.out.println("("+ x +"," +y+")에서 크기가"+width+"*"+height+"인 사각형");
}
// r의 x좌표 r.x~r.x+r.width
// r의 y좌표 r.y~r.y+r.height
public boolean contains(RectAngle r) {
if(r.x >= x && (r.x+r.width) <= (x+width) && r.y >= y && (r.y+r.height) <= (y+height) ) {
return true;
}
else
return false;
}
}
RectAngleOut.java
public class RectAngleOut {
public static void main(String[] args) {
RectAngle r = new RectAngle(2, 2, 8, 7);
// 사각형 r
RectAngle s = new RectAngle(5, 5, 6, 6);
// 사각형 s
RectAngle t = new RectAngle(1, 1, 10, 10);
// 사각형 t
r.show(r.x, r.y, r.width, r.height);
System.out.println("s의 면적은 = "+(s.square(s.width, s.height)));
if(t.contains(r))
System.out.println("t는 r을 포함합니다.");
if(t.contains(s))
System.out.println("t는 s를 포함합니다.");
}
}
String A = "ABCD";
String B = new String("ABCD");
문자열 객체는 재사용 될 가능성이 높기에,
같은 값일 경우 어플리케이션 당 하나의 String 객체만을
생성해두어 JVM의 힙(heap)을 절약하고자 했습니다.
힌트:String 객체의 charAt 함수를 활용
입력:abcd
출력 :
총글자수는 4개
자음 : 3개
모음 : 1개
소스코드
public static void main(String[] args) {
System.out.println("문자열을 입력하세요.");
Scanner s1 = new Scanner(System.in);
String in_string = s1.nextLine();
int consonants = 0;
int vowels = 0;
for (int i = 0; i <= in_string.length() - 1; i++) {
if (in_string.charAt(i) == 'a' || in_string.charAt(i) == 'e' || in_string.charAt(i) == 'i'
|| in_string.charAt(i) == 'o' || in_string.charAt(i) == 'u') {
vowels++;
} else
consonants++;
}
System.out.println("모음의 개수" + vowels);
System.out.println("자음의 개수" + consonants);
}
힌트:String 객체의 charAt 함수를 활용
입력:abcde
출력:edcba
소스코드
String str = "abcde";
int str_leng = str.length();
for(int i=str_leng-1; i>=0; i--) { // 4부터 0까지 반복 4,3,2,1,0
char out=' ';
out = str.charAt(str_leng-1);
System.out.print(out); // charAt 함수로 4,3,2,1,0번째 값을 출력
str_leng--;
}
concat 메소드는 두 문자열을 결합하는 것이다.
예를들어 str1 = ab; 과 str2 = cd;이란 문자열을 결합하고자 하면
str1.concat(str2); 로 표현되며
출력값은 abcd가 된다.
또한 str1.concat("CD"); 등으로
직접 문자열 내용을 입력해서도 결합이 가능하다.
substring 함수는
배열의 a번째 값부터, 가장 왼쪽에서부터 b번째까지 문자열을 자른다.
(주의, 배열은 0부터 시작한다)
ex)
str = "123456";
str.substring(2, 4);
배열의 2번째값 -> 3
가장 왼쪽서부터 4번째까지 -> 4
반환된 값 : 34
valueOf()메소드는 () 안에 들어간 모든것을 문자열 객체로 변환시켜주는 역할을 한다.
예제
str1 = "1234";
str2 = valueOf(true);
str3 = valueOf(false);
str4 = valueOf(12.34);
str5 = valueOf(str1);
println(str1);
println(str1 + str2);
println(str1 + str2 + str3);
println(str1 + str2 + str3 + str4);
println(str1 + str2 + str3 + str5);
출력 결과
1234
1234true
1234truefalse
1234truefalse12.34
1234truefalse12.341234
compareTo()는 두 문자열을 비교해서,
사전 순으로 st1보다 st2가 먼저 있다면 음수값을 반환하며,
ex) abcd, wxyz => 음수 반환
반대로 st2가 st1이 먼저 있다면 양수값을 반환한다.
ex) wxyz, abcd => 양수 반환
비교 후값이 같다면 0을 반환한다.
문자열의 대소문자를 구별하지 않는다면
compareToIgnoreCase() 함수를 사용하면 된다.
String str = "age: " + 17;
String str = "age: " + 17;은
age: 라는 문자열에 17을 붙이는것이며
.concat함수를 이용해 실행된다
실제 호출되는 함수는
"age: ".concat(String.valueOf("17"); 이다.
String 객체는 불변성을 가지고 있어서
String 객체로 만들어진것이 다르게 변환되더라도 객체 내에 있는값이 변환되는 것
이 아니고, 새로운 객체가 생성되어서 원래 지정하고 있었던 객체에서
생성된 다른 객체로 방향이 바뀌는 성질이 있다. 그렇게되면 생성될 때마다
객체가 힙 메모리에 누적되었다가 가비지 컬렉션에 의해 삭제된다.
다만, 변하지 않는 같은 값을 가르키는 객체가 많다면 보다 빠르게 작동될 수도 있다.
그러나 StringBuilder는 이 단점을 해결하기 위해서 만들어졌고,
수정시 객체 내에 있는 값이 바뀌게하는
append()와 delete()메소드를 제공한다.
예 1) String str1 = "ABCD";
str1 = str1 + "EF";
이면 "ABCD"라는 객체도 존재하고
문자열이 합쳐질때, "ABCDEF"라는 객체가 새로 생성되는것이며
그저 str1이 가리키고있는 객체가 바뀌는 것일 뿐이다.
그러므로 "ABCD" "ABCDEF"이 모두 존재하며
ABCD는 사용되지 않기에 컴파일 시 가비지 컬렉션으로 삭제된다.
예 2) StringBuilder str2 = "ABCD";
str2.append("EF");
이면 "ABCD"의 값이 "ABCDEF"로 지정되며
두개의 객체가 존재하는것이 아닌 내용물 자체가 바뀌는 것이다.