- 자바는 객체를 만들기 위해 반드시 클래스를 먼저 만들어야 한다.
- 클래스는 객체를 만들기 위한 일종의 틀이다.
- 붕어빵이 객체라면, 붕어빵 틀은 클래스
public class Car{
}
public class CarExam{
public static void main(String args[]){
Car c1 = new Car();
Car c2 = new Car();
// Car라는 객체(붕어빵)가 2개 만들어지고 객체를 참조하는 c1,c2 변수가 선언됨.
}
}
String str = new String("Hello");
String str1 = "hello";
String str2 = "hello";
상수
가 저장되는 영역에 저장된다. String str3 = new String("hello");
String str4 = new String("hello");
- String은 다른 클래스와 다르게 new를 사용하지 않고 사용할 수 있다.
- 메모리를 아끼려면 String은 new를 사용하지 않고 사용하는 것이 좋다.
- String은 불변 클래스이다. 불변이란 String이 인스턴스가 될때 가지고 있던 값을 나중에 수정할 수 없다.
- String은 문자열과 관련된 다양한 메소드를 가지고 있다. 메소드를 호출한다 하더라도 String은 내부의 값이 변하지 않는다.
- String이 가지고 있는 메소드중 String을 반환하는 메소드는 모두 새로운 String을 생성해서 반환한다.
: 문자열 자른 결과값을 반환하는 메서드
String str5 = "hello world";
String str6 = str5.substring(3);
두 문자열을 비교할 때, == 연산자
를 이용.
== 연산자는 문자열 변수를 비교할 때 변수의 레퍼런스를 비교한다.
두 문자열이 같은 값인지는 equals 메서드
를 사용한다.
public class StringExam {
public static void main(String[] args) {
String str1 = new String("Hello world");
String str2 = new String("Hello world");
if( str1.equals(str2) ){
System.out.println("str1과 str2는 같은 값을 가지고 있습니다.");
}
else{
System.out.println("str1과 str2는 다른 값을 가지고 있습니다.");
}
}
}