자바 시작하기 - 문법2

지니·2023년 5월 13일
0

자바 기초

목록 보기
2/7
post-thumbnail

상수 Constants, final variables

한 번 값이 할당되면 재할당이 불가능하다.
상수는 보통 전체를 대문자로 사용하고, 단어 간의 구분은 _를 사용한다.

public class helloWorld{
	public void main(String[] args) {
	   final double PI = 3.14;
       PI = 3.1415
	}
}

에러가 난다.

형변환 Type Casting

*byte < short < int < long <<< float < double

public class helloWorld{
	public void main(String[] args) {
	   int a = 128;
       short b = a;
	}
}

에러가 난다.
더 좁은 공간에 넣으려고 해서 에러가 발생

public class helloWorld{
	public void main(String[] args) {
	   short x = 10;
       int y = x;
	}
}

에러가 발생하지 않는다. (자동 형변환)
x, y값은 10이다.

public class helloWorld{
	public void main(String[] args) {
	   int a = 128;
       short b = (short) a;
	}
}

에러가 발생하지 않는다. (강제 형변환)
a, b는 값이 128이다.

public class helloWorld{
	public void main(String[] args) {
	   int a = 128;
       byte b = (byte) a;
	}
}

b의 값은 -128이다.
byte는 -128 ~ 127 의 범위를 가지기 때문에, 128이 들어왔을 때 한바퀴를 돌아 -128값이 지정된다.

계산할 때 형변환이 일어나게 하기

public class helloWorld{
	public void main(String[] args) {
	   int a = 10;
       short b = 20;
       
       short g = (short) (a + b);
	}
}

String

String은 문자열 객체이다.
객체는 힙 메모리 영역에 올라간다.
변수에는 힙 메모리 영역의 주소를 할당받는다.

public class helloWorld{
	public void main(String[] args) {
	   String str = "안녕"; //문자열 리터럴
	}
}

객체는 문자열 자체를 할당해서 쓰는데, 일반적으로 자바의 객체에서는 위와 같이 바로 값 자체를 대입할 수 없다.
새로운 객체를 생성한다고 선언해주어야 한다.

public class helloWorld{
	public void main(String[] args) {
	   String str = new String(original:"안녕"); //생성자
	}
}

1. '+' 연산자

String str_1 = "Hello, ";
String str_2 = "World!";

System.out.println(str_1 + " " + str_2);

2. StringBuilder

StringBuilder strBdr_1 = new StringBuilder("Hello,");
strBdr_1.append(" ");
strBdr_1.append("World!");

String str_new = strBdr_1.toString();
System.out.println(strBdr_1.toString());

직접적으로 문자를 넣을 수 없고, new연산자를 통해서만 넣을 수 있다.
속도가 빠르고 메모리가 효율적으로 사용될 수 있다.
데이터를 일부 변경할 수 있다.

string으로 바꾸기 위해 '변수명.toString()'을 사용해야 한다.

3. 문자열 슬라이스

string은 문자에 인덱스를 붙여 관리한다.

String str_1 = "이름: 자바";

따라서, '이름: 자바'의 인덱스 번호는
[0][1].. 로 표현된다.

String str_1 = "이름: 자바";
String str_name = str_1.substring(4, 6);
System.out.println(str_name)

출력결과: '자바'

substring(,) 메소드는 사용할 인덱스 번호의 시작과 끝을 넣어 사용한다.
**마지막 인덱스는 문자가 누락될 수 있다.

문자열 대소문자 변환

String str_1 = "abc";
String str_2 = "ABC";

str_1 = str_1.toUpperCase();
str_2 = str_2.toLowerCase();

System.out.println(str_1);
System.out.println(str_2);

출력 결과: str_1는 대문자로 변환되고, str_2는 소문자로 변환되어 출력된다.

소문자 변환: toUpperCase();
대문자 변환: toLowerCase();

String str_1 = "abc";
String str_2 = "ABC";

str_1 = str_1.toUpperCase();
str_2 = str_2.toLowerCase();

if (str_1.equalsIgnoreCase(str_2)) {
   System.out.println("str_1.equalsIgnoreCase(str_2)");
}

대소문자의 차이를 무시하고 str_1과 str_2를 비교하면, 둘은 같다고 판단할 수 있다.

공백 제거

1. 양쪽 끝 공백 제거

trim() 메소드를 사용하여 양쪽 끝 공백을 제거할 수 있다.

String str_1 = "    Hello   "
str_1 = str_1.trim();
System.out.println(str_1);

'Hello'출력

2. 문자열 중간 공백 제거

replace(타켓, 대체할 것) 메소드를 사용하여 문자열 중간 공백을 제거할 수 있다.

String str_1 = "He    llo "
str_1 = str_1.replace("    ","");
System.out.println(str_1);

'Hello'출력

콘솔 입출력

사용자에게 데이터를 입력받기 위해서는 Scanner 객체를 new 연산자를 통해 만들어주어야 한다.
즉, Scanner sc = new Scanner(System.in)를 사용한다.

입력받은 값을 저장하는 함수는 변수명.next이다.

nextLine()은 입력받은 값을 문자열을 형태로 다룰 수 있게 만들어 준다.
숫자데이터는 nextInt()로 다룰 수 있다.

Scanner sc = new Scanner(System.in);

System.out.println("아이디를 입력하세요.>>");
String username = sc.nextLine();

System.out.println("생년월일을 입력하세요.>>");
int birthDate = sc.nextInt();

System.out.printf("%s %d, username, birthDate);

입력하는 데이터와 출력되는 데이터를 일렬로 정렬시키고 싶다면,
println 대신 print를 쓰면 된다!

profile
IT학과 전과생

0개의 댓글