문자열 길이 구하기
문자열 붙이기 (concat)
String str = new String("hello");
System.out.println(str.concat(" world")); //출력결과는 hello world
System.out.println(str); //출력결과는 hello
문자열 자르기 (subString)
프로그램 상에서 사용되는 변수들은 사용 가능한 범위를 가진다. 그 범위를 변수의 스코프라고 한다.
변수가 선언된 블럭이 그 변수의 사용범위이다.
public class ValableScopeExam{
int globalScope = 10; // 인스턴스 변수
public void scopeTest(int value){
int localScope = 10;
System.out.println(globalScope);
System.out.println(localScpe);
System.out.println(value);
}
}
main메소드에서 사용하기
public class VariableScopeExam {
int globalScope = 10;
public void scopeTest(int value){
int localScope = 20;
System.out.println(globalScope);
System.out.println(localScope);
System.out.println(value);
}
public static void main(String[] args) {
System.out.println(globalScope); //오류
System.out.println(localScope); //오류
System.out.println(value); //오류
}
}
공통으로 사용하는 변수가 필요한 경우
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7;
public void scopeTest(int value){
int localScope = 20;
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
static한 변수는 공유된다.
VariableScopeExam v1 = new VariableScopeExam();
VariableScopeExam v2 = new VariableScopeExam();
v1.globalScope = 20;
v2.globalScope = 30;
System.out.println(v1.globalScope); //20 이 출력된다.
System.out.println(v2.globalScope); //30이 출력된다.
v1.staticVal = 10;
v2.staticVal = 20;
System.out.println(v1.staticVal); //20 이 출력된다.
System.out.println(v2.staticVal); //20 이 출력된다.
static 메서드(클래스 메서드)에서는 인스턴스 변수를 사용할 수 없다
변수의 유효 범위(scope)와 생성과 소멸(life cycle)은 각 변수의 종류마다 다름
지역변수, 멤버 변수, 클래스 변수는 유효범위와 life cycle, 사용하는 메모리도 다름
static 변수는 프로그램이 메모리에 있는 동안 계속 그 영역을 차지하므로 너무 큰 메모리를 할당하는 것은 좋지 않음
클래스 내부의 여러 메소드에서 사용하는 변수는 멤버 변수로 선언하는 것이 좋음
멤버 변수가 너무 많으면 인스턴스 생성 시 쓸데없는 메모리가 할당됨
상황에 적절하게 변수를 사용해야 함
프로그램에서 인스턴스가 단 한 개만 생성되어야 하는 경우 사용하는 디자인 패턴
static 변수, 메소드를 활용하여 구현할 수 있음
자바는 열거타입을 이용하여 변수를 선언할 때 변수타입으로 사용할 수 있다.
enum Gender{
MALE, FEMALE;
}
Gender gender2;
gender2 = Gender.MALE;
gender2 = Gender.FEMALE;
//Gender타입의 변수에는 MALE이나 FEMALE만 대입이 가능. 다른 값은 저장할 수가 없다.
특정 값만 가져야 한다면 열거형을 사용하는 것이 좋다.