Chapter 12. 자바기본 API (2)
String 클래스
문자열을 사용하는데 가장 많이 사용하는 클래스
String 객체가 생성되면 그 값이 길어지거나 줄어들 수 없으며, 구성 문자들 중 어떤 것도 바꿀 수 없다. 즉, 우리가 String 객체의 값을 바꾼다면, 본래 객체 외의 새로운 객체를 생성하여 그 참조 주소를 가리키는 변수가 된다는 것이다.
| 함수 | 반환형 | 설명 |
|---|---|---|
| charAt(int index) | char | index 위치에 있는 문자 반환 |
| compareTo(String str) | int | str보다 사전 순으로 앞이면 음수, 같으면 0, 뒤면 정수 값을 반환 |
| concat(String str) | String | 기존 문자열에 str을 이어 새로운 String을 반환 |
| equals(String str) | boolean | str과 같은 문자열이면(대소문자 구분) True, 그렇지 않으면 False 반환 |
| equalsIgnoreCase(String str) | boolean | str과 같은 문자열이면(대소문자 무시) True, 그렇지 않으면 False 반환 |
| length() | int | 문자 길이를 반환 |
| replace(char oldChar, char new Char) | String | 문자열의 oldChar를 모두 new Char로 변경 |
| substring(int offset, int endIndex) | String | offset 위치에서부터 endIndex - 1까지에 걸친 문자열을 반환 |
| toLowerCase() | String | 모든 대문자를 소문자로 변환 |
| toUpperCase() | String | 모든 소문자를 대문자로 변환 |
String Class 예제
test.str.StringEx.java
01 package test.str;
02
03 public class StringEx {
04 public void testString() {
05 String str = "Hello Java"; // 공백도 하나의 문자로 취급
06 String concat, upperCase, replace, subString;
07
08 System.out.println("기본 String : " + str);
09 System.out.println("기본 String 길이 : " + str.length()); // 문자열의 길이 출력
10
11 concat = str.concat(", Hi Java"); // 문자열 연결
12 upperCase = concat.toUpperCase(); // 문자열 대문자로 변환
13 replace = upperCase.replace('J', 'L'); // 문자 J를 L로 변환
14 subString = replace.substring(3, 10); // 3~9번째 위치의 문자열 잘라내기
15
16 System.out.println("Concat String : " + concat);
17 System.out.println("upperCase String : " + upperCase);
18 System.out.println("replace String : " + replace);
19 System.out.println("subString String : " + subString);
20 }
21 }
test.main.Main.java
01 package test.main;
02
03 import test.str.StringEx;
04
05 public class Main {
06 public static void main(String[] args) {
07 new StringEx().testString();
08 }
09 }
------
기본 String : Hello Java
기본 String 길이 : 10
Concat String : Hello Java, Hi Java
upperCase String : HELLO JAVA, HI JAVA
replace String : HELLO JAVA HI LAVA
subString String : LO LAVA
StringBuffer 클래스와 StringBuilder 클래스
문자열을 다룰 때 사용하며, 문자열을 변경할 때마다 새로운 객체를 생성하는 String 클래스와 다르게 문자열 변경 시 새로운 객체를 생성하지 않고, 버퍼에 담겨 있는 문자열을 바로 수정한다.
StringBuffer 클래스와 StringBuilder 클래스의 객체는 객체 생성 시 크기를 지정하지 않으면 기본적으로 16개의 문자를 저장할 수 있는 버퍼를 가진다. StringBuffer 클래스와 StringBuilder 클래스는 기본적인 동작은 같으며 StringBuffer 클래스만 동기화(Thread Safe)를 지원한다는 점이 다르다.
StringBuffer Class 예제
test.str.StringBufferEx.java
01 package test.str;
02
03 public class StringBufferEx {
04 public void testStringBuffer() {
05 StringBuffer str1 = new StringBuffer();
06 StringBuffer str2 = new StringBuffer(30);
07 StringBuffer str3 = new StringBuffer("Java");
08
09 str1.append("Hi");
10 str2.append("Hello");
11 str3.append(0, str2 + " ");
12
13 System.out.println(str1);
14 System.out.println(str2);
15 System.out.println(str3);
16 }
17 }
test.main.Main.java
01 package test.main {
02
03 import test.strStringBufferEx;
04
05 public class Main {
06 public static void main(String[] args) {
07 new StringBufferEx().testStringBuffer();
08 }
09 }
------
HI
Hello
Hello Java
Math 클래스
숫자 계산에 흔히 사용되는 수학적 기능을 가지는 메소드를 제공하는 클래스
모든 메소드들이 정적 메소드로 정의되어 있어 객체를 생성하지 않고 사용한다.
| 메소드 | 설명 |
|---|---|
| static int abs(int num) | 절대 값을 반환 |
| static double acos(double num) | arc cosine을 반환 |
| static double asin(double num) | arc sine을 반환 |
| static double atan(double num) | arc tangent를 반환 |
| static double cos(double num) | cosine를 반환 |
| static double sin(double num) | sine을 반환 |
| static double tan(double num) | tangent를 반환 |
| static double ceil(double num) | 올림 값(ceiling)를 반환 |
| static double floor(double num) | 내림 값을 반환 |
| static double exp(double power) | 지정된 power 만큼 e의 제곱된 값을 반환 |
| static double pow(double num, double power) | num을 power 만큼 제곱한 값을 반환 |
| static double random() | 0.0(포함)과 1.0(미포함) 사이의 난수를 반환 |
| static double sqrt(double num) | 양수만 가능한 num의 제곱근을 반환 |
Math Class 예제
test.math.MathTest.java
01 package test.math;
02
03 public class MathTest {
04 public void printMath() {
05 System.out.println("abs(-10) : " + Math.abs(-10)); // -10의 절대값
06 System.out.println("ceil(3.7) : " + Math.ceil(3.7)); // 3.7의 올림
07 System.out.println("floor(3.7) : " + Math.floor(3.7)); // 3.7의 내림
08 System.out.println("exp(3.3) : " + Math.exp(3.3)); // e^3.3
09 System.out.println("pow(2.1, 2) : " + Math.pow(2.1, 2); // 2.1^2
10 System.out.println("random() : " + Math.random()); // 0.0 ~ 1.0 사이의 난수
11 }
12 }
test.main.Main.java
01 package test.main;
02
03 import test.math.MathTest;
04
05 public class Main {
06 public static void main(String[] args) {
07 new MathTest().printMath();
08 }
09 }
------
abs(-10) : 10
ceil(3.7) : 4.0
floor(3.7) : 3.0
exp(3.3) : 27.112638920657883
pow(2.1, 2) : 4.41
random() : 0.10559212646066529
Wrapper 클래스
자바의 기본형 데이터 타입을 클래스화 하기 위해 사용하는 클래스
기본형 데이터 타입을 클래스화하면 Object 클래스의 자식 클래스가 되며 데이터 타입에 상관 없이 Object 클래스를 이용한 처리가 가능해진다.
| 기본형 데이터 타입 | Wrapper 클래스 |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
Object형 매개 변수를 이용하여 하나의 함수로 int형과 double형 데이터 처리
test.wrapper.WrapperEx.java
01 package test.wrapper;
02
03 public class WrapperEx {
04 public void printWrapper(Object obj) {
05 System.out.println("데이터 : " + obj);
06 System.out.println("데이터 클래스 : " + obj.getClass());
07 }
08 }
test.main.Main.java
01 package test.main;
02
03 import test.wrapper.WrapperEx;
04
05 public class Main {
06 public static void main(String[] args) {
07 int i = 123;
08 double d = 3.14;
09 WrapperEx wp = new WrapperEx();
10 wp.printWrapper(i);
11 wp.printWrapper(d);
12 }
13 }
------
데이터 : 123
데이터 클래스 : class.java.lang.Integer
데이터 : 3.14
데이터 클래스 : class.java.lang.Double
박싱(Boxing), 언박싱(Unboxing)
박싱(Boxing)
기본형 데이터 타입을 객체화 시키는 작업
int i = 10; Integer iValue1 = new Integer(i); Integer iValue2 = new Integer(123); double d = 1.123; Double dValue1 = new Double(d); Double dValue2 = new Double(5.323);
언박싱(Unboxing)
언박싱(Unboxing) : 객체에 저장되어 있는 데이터를 기본형 데이터로 꺼내는 작업
Integer IValue = new Integer(4578); int i = IValue.intValue(); Double dValue = new Double(44.241); double d = dValue.doubleValue();
자동 박싱(Auto Boxing), 자동 언박싱(Auto Unboxing)
자바 JDK1.5 이상부터는 기본 타입과 Wrapper 클래스 타입 간의 변환이 자동으로 이루어진다.
int i = 10; Integer iValue = i; Double dValue = new Double(3.14); double d = dValue;
그 외 유용한 클래스
Object 클래스
Object 클래스와 유사한 이름을 가진 클래스로 객체 비교, 해시코드 생성, null 여부, 객체 문자열 리턴 등의 연산을 수행할 수 있다.
| 메소드 | 설명 |
|---|---|
| int compare(T a, tb, Comparator c) | 두 객체 a와 b를 Comparator를 사용해 비교 |
| int hashCode(Object o) | 객체의 해시코드 생성 |
| Boolean isNull(Object obj) | 널인지 확인 |
| Boolean nonNull(Object obj) | 널이 아닌지 확인 |
| String toString(Object o) | 객체의 toString()값 리턴 |
Comparator를 이용하여 Student 객체의 총점을 비교하는 예제
test.vo.Student.java
01 package test.vo;
02
03 public class Student {
04 private String name;
05 private int kor;
06 private int eng;
07
08 public Student(String name, int kor, int eng) {
09 this.name = name;
10 this.kor = kor;
11 this.eng = eng;
12 }
13 public int getSum() { return kor + eng; }
14 public String getName() { return name; }
15 }
test.controller.StuComparator.java
01 package test.controller;
02
03 import java.util.Comparator;
04 import test.vo.Student;
05
06 public class StuComparator implements Comparator <Student> {
07 @Override // Comparator 인터페이스의 compare() 메소드를 재정의
08 public int compare(Student o1, Student o2) {
09 if(o1.getSum() > o2.getSum()) return 1;
10 else if(o1.getSum() < o2.getSum()) return -1;
11 else return 0;
12 }
13 }
test.controller.SutManager.java
01 package test.controller;
02
03 import java.util.Objects;
04 import test.vo.Student;
05
06 public class StuManager {
07 public void scoreComp(Student s1, Student s2) {
08 new StuComparator().compare(s1, s2);
09 int result = Objects.compare(s1, s2, new StuComparator());
10
11 if(return > 0) System.out.println(s1.getName() + " 학생이 우수합니다");
12 else if(result < 0) System.out.println(s2.getName() + " 학생이 우수합니다");
13 else System.out.println("두 학생은 점수가 같습니다");
14 }
15 }
test.main.Main.java
01 package test.view
02
03 import test.controller.StuManager;
04 import test.vo.Student;
05
06 public class Main {
07 public static void main(String[] args) {
08 Student s1 = new Student("홍길동", 100, 90);
09 Student s2 = new Student("고길동", 90, 80);
10 new StuManager().scoreComp(s1, s2);
11 }
12 }
------
홍길동 학생이 우수합니다
Random 클래스
자바에서 난수를 발생시키는 방법은 두 가지가 있다. Math 클래스의 random() 메소드를 이용하는 방법과 Random 클래스를 이용하는 방법이다.
Math.random()은 정적 메소드로 객체를 생성하지 않고 편하게 사용할 수 있지만 double 형태의 난수만 발생시킬 수 있다. Random 클래스는 객체를 생성해야 하는 불편함이 있지만 int, long, float, double, boolean 형의 난수를 발생시킬 수 있다.
Random 클래스의 메소드
| 메소드 | 설명 |
|---|---|
| int nextInt() | int형 범위 안의 난수 발생 |
| int nextInt(int n) | 0부터 정수 n까지의 난수 발생 |
| boolean nextBoolean() | 무작위로 true 또는 false 반환 |
| float nextFloat() | float 범위의 난수 발생 |
| double nextDouble() | double 범위의 난수 발생 |
test.random.RandomEx.java
01 package test.random;
02
03 public class RandomEx {
04 public void testRandom() {
05 Random r = new Random();
06
07 System.out.println("nextInt() : " + r.nextInt()); // -2^31 ~ 2^31-1 사이의 난수
08 System.out.println("nextInt(100) : " + r.nextInt(100)); // 0~100 사이의 난수
09 System.out.println("nextBoolean() : " + r.nextBoolean()); // true 또는 false
10 System.out.println("nextDouble() : " + r.nextDouble()); // double형 표현 범위의 난수
11 System.out.println("nextFloat() : " + r.nextFloat()); // float형 표현 범위의 난수
12 }
13 }
test.main.Main.java
01 package test.main;
02
03 import test.random.RandomEx;
04
05 public class Main {
06 public static void main(String[] args) {
07 new RandomEx().testRandom();
08 }
09 }
------
nextInt() : -2014602294
nextInt(100) : 65
nextBoolean() : true
nextDouble() : 0.7777749855581843
nextFloat() : 0.16439652
Author And Source
이 문제에 관하여(Chapter 12. 자바기본 API (2)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@normal114/Chapter-12.-자바기본-API-2저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)