| Method | Description |
|---|---|
| public final native Class<?> getClass() | 객체의 Class 클래스의 객체를 반환한다. Class 클래스를 사용하여 해당 클래스의 메타데이터를 얻을 수 있다. (클래스의 필드, 메서드 정보 등) |
| public native int hashCode() | 객체 자신의 해시코드(객체를 식별하는 유일한 정수값)을 반환한다. |
| public boolean equals(Object obj) | 파라미터로 전달된 객체와 객체 자신(this)의 참조값을 비교해서 같으면 true를 반환한다. |
| protected native Object clone() | 이 객체의 복사본(복제)을 생성하고 반환한다. |
| public String toString() | 이 객체의 정보를 문자열로 반환한다. |
| public final native void notify() | 일시 중지 상태의 단일 스레드를 실행 대기 상태로 만든다. |
| public final native void notifyAll() | 일시 중지 상태의 모든 스레드를 실행 대기 상태로 만든다. |
| public final native void wait() | 다른 스레드가 notify 할 때까지 현재 스레드가 대기 상태로 빠지면서 일시중지된다. |
| protected void finalize() | 객체가 Garbage collection 되기 전에 Garbage collector에 의해 호출된다. Java 9 버전 이상에서는 더 이상 사용되지 않는다(Deprecated). |
public String toString(){
return getClass().getName()
+ "@"
+ Integer.toHexString(hashcode());
}
ObjectEx01 o = new ObjectEx01();
System.out.println("Object toString()->" + o.toString());
[결과]
Object toString()->ch12.ObjectEx01@5a39699c
public class ObjectToString{
private String name = "GilDong";
private int age = 10;
public static void main(String[] args){
ObjectToString o = new ObjectToString();
System.out.println(o);
System.out.println(o.toString());
}
@Override
public String toString(){
return "name=" + name + " age=" + age;
}
}
[결과]
name=Gildong age=10
name=Gildong age=10
public boolean equals(Object obj){return (this==obj);}
class ObjectEq{
private int val;
public ObjectEq(int val){
this.val = val;
}
@Override
public boolean equals(Object obj){
if(obj != null && obj instanceof ObjectEq){
return this.val == ((ObjectEq)obj).val;
}
return false;
}
}
public class ObjectEqualsTest{
public static void main(String[] args){
Object obj1 = new Object();
Object obj2 = new Object();
if(obj1.equals(obj2)){ //obj1 == obj2
System.out.println("obj1.equals(obj2)-> true");
}else{
System.out.println("obj1.equals(obj2)-> false");
}
ObjectEq oeq1 = new ObjectEq(10);
ObjectEq oeq2 = new ObjectEq(10);
//객체 참조값을 비교
if(oeq1 == oeq2){
System.out.println("o1 == o2 -> true");
}else{
System.out.println("o1 == o2 -> false");
}
//오버라이딩된 메서드를 호출하여 객체의 필드값을 비교
if(oeq1.equals(oeq2)){
System.out.println("o1.equals(o2) -> true");
}
}
}
[결과]
obj1.equals(obj2) -> false
o1 == o2 -> false
o1.equals(o2) -> true
public class GetClassEx1{
public static void main(String[] args){
String str = "getClass() 메서드 실행";
Class clazz = str.getClass();
System.out.println("클래스명 : " + clazz.getName());
System.out.println("상위 클래스명 : " + clazz.getSuperclass());
System.out.println("메서드 목록");
for(Method method : clazz.getMethods()){
System.out.println(method.getName() + "\t");
}
System.out.println();
System.out.println("필드 목록");
for(Field field : clazz.getFields()){
System.out.println(field.getName() + "\t");
}
}
}
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesTest{
public static void main(String[] args){
Properties props = System.getProperties();
Enumeration propsNames = props.propertyNames();
while(propsNames.hasMoreElements()){
String propName = (String)propsNames.nextElement();
String property = props.getProperty(propName);
System.out.println("property '" " propName +
"' = '" + property + "'");
}
}
}
[결과]
property 'java.runtime.name' = 'OpenJDK Runtime Environment'
property 'java.vm.version' = '11.0.12+0'
property 'gopherProxySet' = 'false'
property 'java.vm.vendor' = 'Homebrew'
property 'java.vendor.url' = 'https://github.com/Homebrew/homebrew-core/issues'
property 'path.separator' = ':'
property 'java.vm.name' = 'OpenJDK 64-Bit Server VM'
property 'user.country' = 'KR'
property 'java.runtime.version' = '11.0.12+0'
property 'os.arch' = 'aarch64'
property 'java.vm.specification.vendor' = 'Oracle Corporation'
property 'os.name' = 'Mac OS X'
property 'sun.jnu.encoding' = 'UTF-8'
property 'jdk.debug' = 'release'
property 'java.class.version' = '55.0'
property 'java.specification.name' = 'Java Platform API Specification'
property 'sun.management.compiler' = 'HotSpot 64-Bit Tiered Compilers'
...
public class KeyboardInput{
public static void main(String[] args){
String s;
//키보드로 입력받을 수 있는 reader 객체를 생성한다.
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir);
System.out.println("Stop 버튼을 누르면 프로그램이 종료됩니다!");
try{
//콘솔에서 입력을 받는다
s = in.readLine();
while(s != null){
//입력받은 값을 출력
System.out.println("Read: " + s);
s = in.readLine(); //다시 입력 받는다
}
in.close(); //입력 받는 Reader를 close
}catch(IOException e){
e.printStackTrace();
}
}
}
| Method | Description |
|---|---|
| abs(value) | 주어진 값의 절대값을 반환한다. |
| max(v1, v2) | 두 값 중 가장 큰 값을 반환한다. |
| min(v1, v2) | 두 값 중 가장 작은 값을 반환한다. |
| round(value) | 십진수를 가장 가까운 값으로 반올림하는데 사용된다. |
| sqrt(value) | 숫자의 제곱근을 반환하는데 사용된다. |
| pow(v1, v2) | 첫 번째 인수의 값을 두 번째 인수로 거듭제곱한 값을 반환한다. |
| signum(value) | 주어진 값의 부호를 찾는데 사용된다. |
| ceil(value) | 주어진 값을 올림하여 반환한다. |
| floor(value) | 주어진 값을 버림하여 반환한다. |
| sin(value) | 주어진 이중 값의 삼각 사인 값을 반환하는데 사용된다. |
| random() | 0.0보다 크거나 같고 1.0보다 작은 양수 부호의 랜덤 값을 반환한다. |
| rint(value) | 주어진 값과 가장 가까운 정수의 double형을 반환한다. |
public class MathTest{
public static void main(String[] args){
out.println("10의 절대값 : " + Math.abs(10));
out.println("10.0 절대값: " + Math.abs(10L));
out.println("20.0d의 절대값 : " + Math.abs(-20.0d));
out.println("큰 값을 반환 : " + Math.max(20, 10));
out.println("작은 값을 반환 : " + Math.min(10.0, 20.0));
out.println("Random 값을 반환 : " + Math.random());
out.println("올림 값 : " + Math.ceil(20.3));
out.println("작거나 같은 가장 작은 정수를 반환 : " + Math.floor(99.7));
out.println("가장 가까운 정수를 double 타입으로 반환 : " + Math.rint(101.57));
out.println("radians로 지정된 sin 값을 반환 : " + Math.sin(100));
out.println("radians로 지정된 cos 값을 반환 : " + Math.cos(100));
out.println("radians로 지정된 tan 값을 반환 : " + Math.tan(100));
out.println("100으로 지정된 로그값을 반환 : " + Math.log(100));
out.println("3.0의 2.0승 값을 double 값으로 반환 : " + Math.pow(3.0, 2.0));
out.println("Square root값을 double 값으로 반환 : " + Math.sqrt(3));
}
}
[결과]
10의 절대값 : 10
10.0 절대값 : 10
20.0d의 절대값 : 20.0
큰 값을 반환 : 20
작은 값을 반환 : 10.0
Random 값을 반환 : 0.6787390797156491
올림 값 : 21.0
작거나 같은 가장 작은 정수를 반환 : 99.0
가장 가까운 정수를 double 타입으로 반환 : 102.0
radians로 지정된 sin 값을 반환 : -0.5063656411097588
radians로 지정된 cos 값을 반환 : 0.8623188722876839
radians로 지정된 tan 값을 반환 : -0.5872139151569291
100으로 지정된 로그값을 반환 : 4.605170185988092
3.0의 2.0승 값을 double 값으로 반환 : 9.0
Square root값을 double 값으로 반환 : 1.7320508075688772
| 기본형 | 래퍼클래스 |
|---|---|
| boolean | Boolean |
| char | Character |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
public boolean equals(Object obj){
if(obj instanceof Integer){
return value == ((Integer)obj).intValue();
}
return false;
}
//사용예
Integer i1 = Integer.valueOf(10);
Integer 12 = Integer.valueOf(10);
boolean isEquals = i1.equals(i2);
public class AutoBoxing{
public static void main(String[] args){
int val = 20;
//valueOf() 메서드를 이용하여 래퍼 클래스 객체 변환
Integer i1 = Integer.valueOf(val);
//Autoboxing으로 래퍼 클래스 객체 자동 변환
Integer i2 = val;
}
}
public class UnBoxing{
public static void main(String[] args){
//new 생성자를 사용하는 것은 deprecated되었다
//Integer i = new Integer(20);
Integer i = Integer.valueOf(20);
//intValue() 메서드를 이용하여 기본형으로 변환
int val1 = i.intValue();
//Unboxing 기능으로 기본형으로 자동 변환
int val2 = i;
}
}
public class AutoBoxingUnBoxing{
public static void main(String[] args){
Integer num = Integer.valueOf(15); //박싱
int n = num.intValue(); //언박싱
System.out.println(n);
Character ch = 'X'; //Character ch = new Character('X'); :오토박싱
char c = ch; //char c = ch.charValue(); :오토언박싱
System.out.println(c);
//오토박싱과 오토언박싱을 통해 기본형과 래퍼클래스간의 다양한 연산도 가능하다
Integer num1 = Integer.valueOf(7); //박싱
Integer num2 = Integer.valueOf(3); //박싱
int int1 = num1.intValue(); //언박싱
int int2 = num2.intValue(); //언박싱
Integer result1 = num1 + num2; //10
Integer result2 = int1 - int2; //4
}
}
| Modifier 리턴타입 | 메서드 | Description |
|---|---|---|
| byte | byteValue() | 지정된 숫자의 값을 byte로 변환한다. |
| abstract double | doubleValue() | 지정된 숫자의 값을 double로 변환한다. |
| abstract float | floatValue() | 지정된 숫자의 값을 float으로 변환한다. |
| abstract int | intValue() | 지정된 숫자의 값을 int로 변환한다. |
| abstract long | longValue() | 지정된 숫자의 값을 long으로 변환한다. |
| short | shortValue() | 지정된 숫자의 값을 short로 변환한다. |
Number Abstract 클래스와 이를 상속하고 있는 Integer 래퍼클래스 소스의 일부다.
public abstract class Number{
implements java.io.Serializable{
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue(){
return (byte)intValue();
}
public short shortValue(){
return (short)intValue();
}
}
}
public final class Integer extends Number implements Comparable<Integer> {
...
public int intValue(){
return value;
}
}
public class NumberTestEx{
public static void main(String[] args){
Double doubleValue = Double.valueOf(123.456);
int intValue = doubleValue.intValue(); //소숫점 버림
short shortValue = doubleValue.shortValue();
long longValue = doubleValue.longValue();
System.out.println("integer value: " + intValue);
}
}
[결과]
integer value: 123
char[] ch = {'g','i','l','d','o','n','g'};
String s = new String(ch); //String s = 'gildong";과 같음
String s1 = "literal";
String s2 = "literal"; //새 인스턴스를 생성하지 않는다.
public class StringEx01 {
public static void main(String args[]){
String s1 = "java"; // 문자열 리터럴로 string 객체 생성
char ch[] = {'g','i','l','d','o','n','g'};
String s2 = new String(ch); // char 배열을 문자열로 변환
// new 키워드로 자바 문자열 객체 생성
String s3 = new String("새로운 문자열");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
String strVar1 = "abc";
String strVar2 = "abc";
String strVar3 = new String("abc");
String strVar4 = new String("abc");
// true = 동일한 객체 참조값
System.out.println(strVar1 == strVar2);
// false = new로 생성되어 객체 참조값이 다르다
System.out.println(strVar3 == strVar4);
// 오버라이된 equals메서드로 값을 비교
System.out.println(strVar1.equals(strVar2));
System.out.println(strVar3.equals(strVar4));
}
}
[결과]
java
gildong
새로운 문자열
true
false
true
true
| Method | Description |
|---|---|
| charAt(int index) | 지정한 index에 있는 문자를 반환한다. |
| length() | 문자열의 길이를 반환한다. |
| concat(String str) | 파라미터 문자열을 현재 문자열에 덧붙인다. |
| substring(int beginIndex, int endIndex) | 지정한 시작위치부터 종료위치 범위에 포함된 문자열을 반환한다. |
| isEmpty() | 빈 문자열 여부를 반환한다. |
| contains(CharSequence s) | 지정된 문자열이 포함되어 있는지 여부를 반환한다. |
| replace(char old, char new) | 문자열 중의 old 문자를 new 문자로 변경한 문자열을 반환한다. |
| equalsIgnoreCase(String another) | 문자열과 another 문자열을 대소문자 구분없이 동일한지 여부를 반환한다. |
| split(String regex) | 문자열을 지정된 분리자*(regex)로 나누어 문자열 배열에 저장 후 반환한다. |
| indexOf(int ch) | 주어진 문자열이 존재하는지 확인하여 그 위치를 반환하며, 없으면 -1을 반환한다. |
| toLowerCase() | 저장되어 있는 문자열을 모두 소문자로 변환 후 반환한다. |
| toUpperCase() | 저장되어 있는 문자열을 모두 대문자로 변환 후 반환한다. |
| trim() | 저장되어 있는 문자열의 왼쪽 끝과 오른쪽 끝에 있는 공백을 제거한 문자열을 반환한다. |
| valueOf(기본형 value) | 지정된 값을 문자열로 변환하여 반환한다. |
String s = new String("ABCDEFGH");
System.out.println(s.charAt(4)); //E
System.out.println(s.compareTo("ABCDEFGH")); //0
System.out.println(s.compareToIgnorCase("abcdefgh")); //0
System.out.println(s.concat("abc")); //ABCDEFGHabc
System.out.println(s.endsWith("FGH")); //true
System.out.println(s.equals("ABCDEFGH")); //true
System.out.println(s.equalsIgnoreCase("abcdefgh")); //true
s = new String("This is a String");
System.out.println(s.indexOf("i"); //2
System.out.println(s.indexOf("i", 7)); //13
System.out.println(s.indexOf("is")); //2
System.out.println(s.lastIndexOf("is")); //5
System.out.println(s.length()); //16
System.out.println(s.replace('i', 'Q')); //ThQs Qs a StrQng
System.out.println(s.replaceAll("is", "IS")); //ThIS IS a String
System.out.println(s.startWith("This")); //true
System.out.println(s.substring(5)); //is a String
System.out.println(s.substring(5, 13)); //is a Str
System.out.println(s.toLowerCase()); //this is a string
System.out.println(s.toUpperCase()); //THIS IS A STRING
| Method | Description |
|---|---|
| append(데이터타입 value) | 지정된 값을 현재 문자열 끝에 추가한다. |
| capacuty() | 현재 문자열의 총 버퍼크기(용량)을 반환한다. 버퍼의 기본 용량은 16개이며, 현재 용량에서 문자 수가 증가하면 (oldcapacity * 2)+2만큼 용량이 증가한다. |
| 예) 현재 용량이 16인 경우 → (16*2)+2=34 | |
| charAt(int index) | 지정한 index에 있는 문자를 반환한다. |
| delete(int beginIndex, int endIndex) | 지정한 시작위치부터 종료위치 범위에 문자열 중에서 삭제한 문자열을 반환한다. |
| indexOf(String str) | str 문자열의 인덱스를 반환한다. |
| length() | 문자열내의 문자 개수를 반환한다. |
| replace(int start, int end, String str) | start에서 ends문자열을 str 문자열로 대체하여 반환한다. |
| reverse() | 문자열의 역순으로 된 문자열을 반환한다. |
| substring(int start, int end) | start에서 end까지의 문자열을 반환한다. |
public class StringBufferEx01 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("홍길동");
sb.append("버퍼 테스트");
sb.insert(3, "문자열 추가 ");
sb.substring(0,2);
String result = sb.toString();
System.out.println("capacity="+sb.capacity());
System.out.println("length="+sb.length());
System.out.println("result : " + result);
// 지정 인덱스 문자열 변경
sb.replace( 1 , 3 , "자바" );
System.out.println("sb replace : " + sb);
// 지정 인덱스 문자열 삭제
sb.delete( 1 , 3 );
System.out.println("sb delete : " + sb);
// 문자열을 반대로 변경
sb.reverse();
System.out.println("sb reverse : " + sb);
}
}
[결과]
capacity=16
length=16
result : 홍길동문자열 추가 버퍼 테스트
sb replace : 홍자바문자열 추가 버퍼 테스트
sb delete : 홍문자열 추가 버퍼 테스트
sb reverse : 트스테 퍼버 가추 열자문홍
Capacity 예제
public class StringBuferEx03 {
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 (oldcapacity*2)+2
}
}
string 객체는 immutable(불변형) Unicode characters다.
concat, replace, substring, toLowerCase, toUpperCase, trim 메서드들은 새로운 String Object를 생성하는 메서드들이다.
검색 메서드: endsWith, startWith, indexOf, lastIndexOf
비교 메서드: equals, equalsIgnoreCase, compareTo
기타: chatAt, length
StringBuffer object는 mutable(변형) Unicode characters다.
생성자
Modification methods: append, insert, reverse, serCharAt, serLength
StringBuffer buffer = new StringBuffer();
buffer.append("bind").append("string");
StringBuffer sb = new StringBuffer("스트링버퍼");
sb.append("123");
| String | StringBuffer |
|---|---|
| 불변형(immutable)이다. | 변경 가능(mutable)하다. |
| 문자열에 변화를 주는(문자열을 더해 조합하는 등의 변화) 새로운 String 인스턴스를 생성하고 기존 인스턴스가 삭제될 수 있다. 인스턴스 생성이 반복되는 과정 속에서 overhead가 심해질 수 있다. | 빠르며 문자열을 연결할 때 String보다 메모리를 덜 소비한다. |
| Object 클래스의 equals() 메서드를 오버라이드하며, equals() 메서드로 두 문자열의 내용을 비교할 수 있다. | equals() 메서드를 오버라이드하지 않았다. |
| 값을 비교하려면 toString()으로 문자열을 얻은 후 String의 equals()메서드로 비교한다. | |
| String constant pool을 사용한다. | Heap 메모리를 사용한다. |
Overhead 비교 예제
public class StringVSStringBuffer{
public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "연결";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("연결");
}
return sb.toString();
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
concatWithString();
System.out.println("String을 연결시키는데 걸리는 시간 : "+(System.currentTimeMillis()-startTime)+"ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("StringBuffer를 연결할 때 걸리는 시간 : "+(System.currentTimeMillis()-startTime)+"ms");
}
}
[결과]
String을 연결시키는데 걸리는 시간 : 54ms
StringBuffer를 연결할 때 걸리는 시간 : 0ms
public class StringBuilderEx1{
public static void main(String[] args){
StringBuilder sb = new StringBuilder("Hello");
sb.delete(1,3);
System.out.println("sb delete : "+sb); //Hlo
sb.reverse();
System.out.println("sb reverse "+sb) //olH
//문자 대체, 문자 교체, 문자 치환
sb.setCharAt(1, 'b');
System.out.println("sb setCharAt : "+sb); //obH
}
}
StringBuffer의 문자열 리터럴을 추가하는 append() 메서드는 스레드 동기화를 위한 synchronized 처리가 되어 있다.
@Override
public synchronized StringBuffer append(Object obj){
toStringCache = null;
super.append(String.valueOf(obj));
return this;
}
@Override
@HotSpotIntrinsicCandidate
public StringBuilder append(String str){
super.append(str);
return this;
}