본문 바로가기

Java

Java(15) - 기본 클래스, Object, Wrapper 클래스

728x90
반응형

1) 기본 클래스

   1-1) 개념

   1-2) toString()

   1-3) equals()

   1-4) hashCode()

   1-5) String

   1-6) Wrapper Class

2) 예제 풀이

 

 

 

 

1) 기본 클래스

1-1) 개념

java.lang 패키지는 자바에서 가장 기본적인 동작을 수행하는 클래스들의 집합이다!

따라서 자바에서는 java.lang 패키지의 클래스들은 import 문을 사용하지 않아도 클래스 이름만으로 바로 사용할 수 있도록 하고 있다.

 

 

1-2) toString()

  • 객체를 문자열로 표현하여 반환
  • 재정의하여 객체에 대한 설명이나 특정 멤버 변수 값을 반환 가능함

 

해시코드 : 해시 함수에 의해 자동으로 생성된 값인데 객체를 유일하게 식별할 수 있는 정수 값

 

 

1-3) equals()

  • 두 인스턴스의 주소 값을 비교하여 true or false의 값으로 반환
  • 재정의하여 두 인스턴스의 물리적(주소값), 논리적으로 동일한지 true or false 값을 반환하도록 변경 가능

인스턴스를 새로 생성할 경우, 실제로 heap 영역에 생성된 인스턴스들 각각이 만들어지는 주소가 모두 다르다!

 

 

1-4) hashCode()

  • 해시 알고리즘에 의해 생성된 정수 값
  • 해시 테이블은 객체의 주소 값 or 객체의 정보를 키 값으로 해시값을 계산함

 

 

1-5) String

  • private final char value[];을 멤버 변수로 가짐
  • String 인스턴스는 한 번 생성되면 그 값을 읽기만 할 수 있고, 변경 불가(불변 객체[immutable object])
  • (+) 연산자를 이용하여 문자열 결합을 하면 기존 문자열의 내용이 변경되는 것이 아니라 새로운 String 인스턴스를 생성

 

 

 

 

1-6) Wrapper Class

말 그대로 기본 타입에 해당하는 값을 클래스 형태로 포장하여 객체화시키는 것

  • 박싱(Boxing) : 기본 타입(primitive type)을 Wrapper class(클래스 타입)로 변환하는 것
  • 언박싱(Unboxing ) : Wrapper class를 기본 타입으로 변환하는 것

 

 

 

 

 

 

2) 예제 풀이

패키지 chapter12.object

ToString.class

package chapter12.object;

// toString() : 객체 정보를 문자열로 만들어서 다시 리턴하는 메서드
public class ToString {

	public static void main(String[] args) {
		int i = 1234;
		System.out.println(i);
		
		Human kim = new Human(29, "김상형");
		System.out.println(kim);
		
		String str = "범인: " + kim;
		System.out.println(str);

	}

}

 

 

 

 

Human.class

package chapter12.object;

public class Human {
	int age;
	String name;
	
	Human(int age, String name) {
		this.age = age;
		this.name = name;
	}

	@Override
	public String toString() {
		super.toString();
		return age + "세의" + name;
	}
	
}

 

 

 

User.class

package chapter12.object;

import java.util.Objects;

public class User {
	int userId;
	String userName;
	
	public User(int userid, String userName) {
		this.userId = userId;
		this.userName = userName;
	}

	@Override
	public int hashCode() {
		return Objects.hash(userId);
	}

	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())   // "getClass()"는 "this.getClass()"와 동일한 코드이다!
			return false;
		User other = (User) obj;  // userA.equals(userB)에서 userB와 같은 매개변수 자리에 들어가는 인수는 userId를 뽑아내려면 User 클래스로 강제 형변환(다운 캐스팅)해줘야 한다!
		if (this.userId != other.userId) {
			return false;
		} else {
			return true;
		}
	} 
	
}

 

 

 

Equals.class

package chapter12.object;

public class Equals {

	public static void main(String[] args) {
		User userA = new User(100, "이상원");
		User userB = userA;
		User userC = new User(100, "이상원");
		
		if (userA == userB) {  // 동일성 비교
			System.out.println("userA와 userB의 주소는 같다. 1");
		} else {
			System.out.println("userA와 userB의 주소는 다르다. 2");
		}
		
		if (userA.equals(userB)) {  // 동등성 비교
			System.out.println("userA와 userB는 같다. 3");
		} else {
			System.out.println("userA와 userB는 다르다. 4");
		}
		
		
		if (userA == userC) {  // 동일성 비교
			System.out.println("userA와 userC의 주소는 같다. 5");
		} else {
			System.out.println("userA와 userC의 주소는 다르다. 6");
		}
		
		if (userA.equals(userC)) {  // 동등성 비교
			System.out.println("userA와 userC는 같다. 7");
		} else {
			System.out.println("userA와 userC는 다르다. 8");
		}

	}

}

 

 

 

 

Student.class

package chapter12.object;

import java.util.Objects;

public class Student {
	String name;
	int stdNum;
	
	Student() {}
	Student(String name, int stdNum) {
		this.name = name;
		this.stdNum = stdNum;
	}
	
	@Override
	public int hashCode() {
		return this.stdNum;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (this.stdNum != other.stdNum) {
			return false;
		} else {
			return true;
		}
	}
	
}

 

 

 

HashCode.class

package chapter12.object;

public class HashCode {

	public static void main(String[] args) {
		Student st1 = new Student("홍길동", 20240001);
		Student st2 = new Student("홍길동", 20240001);
		Student st3 = st1;
		Student st4 = new Student("홍길동", 20240003);
		
		// 주소값 비교(물리적 위치)
		System.out.println(st1 == st2);
		System.out.println(st1 == st3);
		System.out.println(st1 == st4);
		System.out.println("============");
		
		// 주소값이 아닌 실제값 비교(가지고 있는 값)
		System.out.println(st1.equals(st2));
		System.out.println(st1.equals(st3));
		System.out.println(st1.equals(st4));
		System.out.println("============");
		
		// 해시값 출력
		System.out.println(st1.hashCode());
		System.out.println(st2.hashCode());
		System.out.println(st3.hashCode());
		System.out.println(st4.hashCode());
		System.out.println("============");
		
		// 실제 객체 고유 hashcode
		System.out.println(System.identityHashCode(st1));
		System.out.println(System.identityHashCode(st2));
		System.out.println(System.identityHashCode(st3));
		System.out.println(System.identityHashCode(st4));

	}

}

 

 

 

 

GetClass.class

package chapter12.object;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class GetClass {

	public static void main(String[] args) {
		Human kim = new Human(29, "김상형");
		
		Class cls = kim.getClass();
		System.out.println("클래스 이름 = " + cls.getName());
		System.out.println("슈퍼 클래스 = " + cls.getSuperclass().getName());
		
		System.out.print("필드 : ");
		Field[] fields = cls.getDeclaredFields();
		for (Field f : fields) {
			System.out.print(f.getName() + " ");
		}
		
		System.out.print("\n메서드: ");
		Method[] methods = cls.getDeclaredMethods();
		for (Method m : methods) {
			System.out.print(m.getName() + " ");
		}

	}

}

 

 

 

 

WrapperClass.class

package chapter12.object;

public class WrapperClass {

	public static void main(String[] args) {
		/*
		    Wrapper 클래스(Integer, Boolean, ...)의
		    생성자 호출로부터의 인스턴스화를 권장하지 않음(자바9 이후)
		*/
		
		// boxing : 기본형 --> 참조형
		// 기본형을 참조형으로 인스턴스화시키는 코드
		int i = 1234;
		Integer wrapint = new Integer(i);
		String str = wrapint.toString();
		System.out.println(str);
		
		String a = "56", b = "78";
		System.out.println(a + b);
		System.out.println(Integer.parseInt(a) + Integer.parseInt(b));
		
		// unboxing : 참조형 --> 기본형
		// 참조형을 기본형으로 인스턴스화시키는 코드
		Integer wrapint2 = new Integer(629);
		int j = wrapint2.intValue();
		System.out.println(j);
		
		Double wrapdouble = new Double("3.14");
		double di = wrapdouble.doubleValue();
		System.out.println(di);
		
		// auto boxing은 컴파일러가 필요하다면 자동으로 박싱, 언박싱을 해 줌!
		Integer c = new Integer(3);
		Integer d = new Integer(4);
		int e = c + d;
		System.out.println(e);
		
		System.out.printf("int 타입의 크기 = %d, 최대값 = %d, " + "최소값 = %d\n",
				Integer.SIZE, Integer.MAX_VALUE, Integer.MIN_VALUE);
		System.out.printf("short 타입의 크기 = %d, 최대값 = %d, " + "최소값 = %d\n",
				Short.SIZE, Short.MAX_VALUE, Short.MIN_VALUE);

	}

}

 

 

 

 

String1.class

package chapter12.object;

public class String1 {

	public static void main(String[] args) {
		/*
		    출력함수
		    print() / println() / printf() / String.format()
		    1. escape sequence(탈출 문자)
		        \n : 개행
		        \t : tab키 만큼 공백
		        \" : 큰 따옴표 출력
		        \' : 작은 따옴표 출력
		    2. printf 출력 서식(자바 1.5 이상)
		        - 지시자
		            %b : boolean 형식으로 출력
		            %d : 정수 형식으로 출력
		            %f : 소수점 형식으로 출력
		            %c : 문자 형식으로 출력
		            %s : 문자열 형식으로 출력
		            %o : 8진수 정수의 형식으로 출력
		            %x : 16진수 정수의 형식으로 출력
		        - 플래그
		            " - " : 왼쪽으로 정렬
		            " + " : 부호 출력
		            " 0 " : 남는 자리를 0으로 채움
		            " , " : 일정 자리수마다 구분문자 표시
		            " # " : 8진수, 16진수 표시 시 접두사 포함 등 출력형태 보완
		*/
		
		int number = 10;
		double score = 12.345;
		String text = Integer.toBinaryString(number);
		
		// 여기서 "%n"은 개행을 주기 위한 코드이다!
		System.out.printf("%b  %n", 3 < 1);  // boolean
		System.out.printf("%d  %n", number);  // 10진수
		System.out.printf("%o  %n", number);  // 8진수
		System.out.printf("%x  %n", number);  // 16진수
		System.out.printf("%,d %n", 1000000);  // 3자리수마다 ","표시
		System.out.printf("%+d %n", 10);  // 부호 표시
		System.out.printf("%+d %n", -10);  // 부호 표시
		
		System.out.printf("%f  %n", score); // 부동 소수점
		System.out.printf("%e  %n", score); // 지수
		
		System.out.printf("%c  %n", 65); // 문자
		System.out.printf("%s  %n", text); // 문자열
		System.out.printf("%s  %n", "ABcdeFG"); // 문자열
		
		System.out.printf("[%10d]  %n", number); // 전체 10자리(우측정렬)
		System.out.printf("[%-10d]  %n", number); // 전체 10자리(좌측정렬)
		System.out.printf("[%010d]  %n", number); // 전체 10자리(빈공간 0)
		System.out.printf("[%10.5f]  %n", score); // 전체 10자리(소수점 5자리)
		
		System.out.println("=======================");
		String str = String.format("이름: %s, 나이: %d", "홍길동", 20);
		System.out.println(str);

	}

}

 

 

 

 

String2.class

package chapter12.object;

public class String2 {

	public static void main(String[] args) {
		// length
		String str = "아름다운 우리나라";
		System.out.println("길이: " + str.length());
		System.out.println("2번째 문자: " + str.charAt(2)); // charAt(2) : 2번째 인덱스에 해당하는 문자를 뽑아주는 메서드
		System.out.println();
		
		// indexof
		String str2 = "String Search Method of String Class";
		System.out.println("앞쪽 t = " + str2.indexOf('t'));
		System.out.println("뒤쪽 t = " + str2.lastIndexOf('t'));
		System.out.println("앞쪽 z = " + str2.indexOf('z'));
		System.out.println("앞쪽 String = " + str2.indexOf("String"));
		System.out.println("뒤쪽 String = " + str2.lastIndexOf("String"));
		
		// startsWith, endsWith
		String str3 = "girl.jpg";
		System.out.println(str3.startsWith("g"));
		System.out.println(str3.endsWith(".jpg"));
		
		// changeCase...
		String str4 = "Kim Sang Hyung";
		System.out.println(str4.toLowerCase());
		System.out.println(str4.toUpperCase());
		
		// 문자열 자체를 변경하지는 않는다.
		str4.toUpperCase();
		System.out.println(str4);
		
		// 변경하려면 다시 대입받아 저장한다.
		str4 = str4.toUpperCase();
		System.out.println(str4);
		
		// trim
		String str5 = "    Kim Sang Hyung    ";
		System.out.println(str5.trim());
		System.out.println(str5.trim().concat(" BABO"));
		System.out.println();
		
		// replace
		String str6 = "독도는 일본땅. 대마도는 일본땅.";
		System.out.println(str6.replace("일본", "한국"));
		System.out.println(str6.replaceFirst("일본", "한국"));
		System.out.println();
		
		// substring
		String str7 = "0123456789";
		System.out.println(str7.substring(3));
		System.out.println(str7.substring(3, 7));
		System.out.println();
		
		// split
		String city = "서울,대전,대구,부산";
		String[] token = city.split(",");
		for (String s : token) {
			System.out.println(s);
		}
		System.out.println();
		
		// join
		String path = String.join("/", "user", "data", "app", "local");
		System.out.println(path);

	}

}

 

 

 

 

 

MathTest.class

package chapter12.object;

public class MathTest {

	public static void main(String[] args) {
		System.out.println(Math.E);
		System.out.println(Math.PI);
		
		System.out.println("왼쪽 = " + Math.floor(1.6));
		System.out.println("왼쪽 = " + Math.floor(-1.6));
		System.out.println("오른쪽 = " + Math.ceil(1.6));
		System.out.println("오른쪽 = " + Math.ceil(-1.6));
		System.out.println("자름 = " + (int) 1.6);
		System.out.println("자름 = " + (int) -1.6);
		
		System.out.println("반올림 = " + Math.round(1.6));
		System.out.println("반올림 = " + Math.round(1.4));

	}

}

 

 

 

 

RandomTest.class

package chapter12.object;

import java.util.Random;

public class RandomTest {

	public static void main(String[] args) {
		// Math의 random()
		for (int i = 0; i < 5; i++) {
			System.out.println(Math.random());
		}
		for (int i = 0; i < 5; i++) {
			System.out.println((int) (Math.random() * 10) + 1);
		}
		
		// Random
		Random r = new Random();
		for (int i = 0; i < 5; i++) {
			System.out.println(r.nextInt(10));
		}
		for (int i = 0; i < 5; i++) {
			System.out.print(getRandom(5, 10) + " ");
		}

	}
	static int getRandom(int a, int b) {
		return (int)(Math.random() * (b - a)) + a;
	}

}