프로그래밍/Java 공부

JAVA_is a, has a, java memory, 랩퍼클래스, 오토 박싱, 언박싱, enum

개발계발게발 2021. 6. 10. 17:27
반응형

 is a, Has a

 is a ~는 ~이다.

 Has a ~는 ~을 가지고 있다.

class Human{
	String name;
	int age;
}

class Student extends Human{
	int number;	
}

class Gun{
	String number;
	int count;
}

class Police{
	String name;
	int polNumber;
	Gun gun; //멤버변수로 객체를 가진다.
	//경찰은 총을 가진다는 구조로 경찰 클래스안에 권총 클래스의 객체를 멤버로 가지는 구조
}

public class isAHaA {
	public static void main(String[] args) {
		
		Student student = new Student();
		
		Police p = new Police();
		
		Gun gun = new Gun();
		p.gun = gun;
		p.gun.number = "10";
		p.gun.count = 30;
		
		System.out.println(p.gun);	//jun10.Gun@41a4555e
		System.out.println(p.gun.number); //10
		System.out.println(p.gun.count);  //30		
	}
}

 

 

memory

호출스택은 예외처리 할 때 필요


메소드 영역 클래스 데이터 (클래스 변수)
 

프로그램 실행 중 어떤 클래스가 사용되면 JVM은 해당 클래스 파일을 읽어서 클래스 데이터를
이곳(메소드 영역)에 저장하며 동시에 클래스 변수도 이곳(메소드 영역)에 생성

 

호출 스택 메인 메소드(지역 변수)

 

메소드 작업에 필요한 메모리 공간을 제공
메소드가 호출되면 호출스택에 메소드 활용을 위한 메모리가 할당된다.
메모리에서 메소드가 작업을 하는 동안 지역변수와 연산의 중간 결과가 저장
메소드가 작업을 마치면 할당되는 메모리 공간은 반환되어 비워진다.
호출스택은 제일 상위에 있는 메소드가 지금 실행중인 메소드

나머지는 모두 대기중
※ 언제나 호출스택의 제일 위에 있는 메소드가 지금 실행중인 메소드
아래에 있는 메소드가 바로 위에 있는 메소드를  호출해서 사용중인 메소드 


힙 영역 인스턴스(인스턴스) 변수

 

인스턴스가 이곳에 생성

리턴타입이 있는 메소드는 종료되기 직전 결과값을 반환
자신을 호출한 메소드에게 결과값을 반환
대기 중인 호출 메소드가 받아서 프로그램을 진행

 

public class memory {
	public static void main(String[] args) {
		System.out.println("메인 메소드 시작");
		first();		
		System.out.println("메인 메소드 끝");
	}
	public static void first() {
		System.out.println("first 메소드 시작");
		second();	//세컨드 호출
		System.out.println("first 메소드 끝");
	}
	public static void second() {
		System.out.println("second 메소드 시작");
		
		System.out.println("second 메소드 끝");
	}
}

 

랩퍼 클래스

 

컬랙션을 하기 위해 = 값을 담을때 참조형(R)만 담을 수 있다.
 기본 자료형은 컬랙션에 담을 수 없기 때문에 기본 자료형을 객체 타입으로 만들어 주는 것이 랩퍼 클래스

기본 자료형의 값을 컬랙션에 담기 위해서는 랩퍼클래스를 사용
모든 기본 자료형에 대해 그에 대응하는 랩퍼클래스가 있다.

기본 자료형의 값을 멤버 변수의 값으로 저장하고
이 값 주위로 값을 가공하는 메소드들이 감싸고 있다고해서 랩퍼클래스라고 불린다.

랩퍼(WRAPPER) : 감싸다  

기본 자료형 랩퍼 클래스
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

 

기본 타입을 객체타입처럼 사용
기본타입 + 메소드 = 랩퍼타입
컬렉션에 저장하기 위해서 객체 형태로 사용

 

		Integer integer = new Integer(10);	//JAVA 9 이전
		Integer integer2 = 10; 		//JAVA 9
		
		System.out.println(integer);
		System.out.println(integer2);
		
		//Integer to int
		
		int numInt = integer;
		int numInt2 = integer2.intValue();
		short numShort = integer2.shortValue();//캐스팅 없이 변환
		long numLong = integer2.longValue();

 

10진수 8진수 16진수

 

		//최대값 최소값
		System.out.println(Integer.MIN_VALUE);//-2147483648
		System.out.println(Integer.MAX_VALUE);//2147483647
		//16진수 저장
		//0x
		//0~9ABCDEF
		
		//public static final int MIN_VALUE = 0x80000000;
		//public static final int MAX_VALUE = 0x7fffffff;
		
		System.out.println(Integer.toBinaryString(10)); //1010
		System.out.println(Integer.toOctalString(9)); //11
		System.out.println(Integer.toHexString(17)); //11
		
		String b = Integer.toBinaryString(3); //11
		String o = Integer.toOctalString(9);  //11
		String h = Integer.toHexString(17);   //11
		
		System.out.println(b); //11
		System.out.println(o); //11
		System.out.println(h); //11
		
		System.out.println(Integer.parseInt(b, 2));	//3
		System.out.println(Integer.parseInt(o, 8));	//9
		System.out.println(Integer.parseInt(h, 16));//17
		
		int bi = 0b11;	//3  = 11
		int oi = 011;	//9  = 11
		int hi = 0x11;	//17 = 11
		
		int max = Integer.MAX_VALUE;
		int min = Integer.MIN_VALUE;
		System.out.println(max); //2147483647
		System.out.println(min); //-2147483648
		System.out.println(max/min); // 0??

 

컴파일러에 의해 기본타입이 랩퍼 클래스로 자동 변환 되는것을 오토 박싱 이라고 한다.

반대로 컬렉션에서 값을 가져와 기본타입에 넣을때에 1.5 이전에는 래퍼 클래스를 기본 타입으로 형변환 해줘야 했지만

1.5 이후부터는 자동으로 형변환 되어 기본값에 저장할 수 있다.(오토 언박싱)

		Integer integer3 = 200;	//오토 박싱
		//Integer integer3 = new Integer(200);
		//기본 자료형이 참조형으로 바뀌는 것 형변환 X

 

		integer = 200;
		
		integer2 = new Integer(200);
		
		if(integer == integer2) {	//다르다
			System.out.println("같다");
		}else {
			System.out.println("다르다");
		}
		
//		integer와 integer2가 같은 int값을 가지고 있는지 판별하기 위해서는
//		integer속에 있는 equals()를 써야한다.
//		Integer의 equals()는 값이 int인지 판단하도록 Object에서 equals()를 오버라이딩 한다.
		
		if(integer.equals(integer2)) {	//같다
			System.out.println("같다");
		}else {
			System.out.println("다르다");
		}
	
		System.out.println(integer.equals(integer2));	//true
		System.out.println(integer.compareTo(integer2));//0
		
		integer = 11;
		integer2 = 12;
		
		int check = integer.compareTo(integer2); // 1 0 -1
		
		if(check == 0) {
			System.out.println("같다");
		}else if(check == 1) {
			System.out.println("integer가 크다");//앞이 크다
		}else {//-1
			System.out.println("integer2가 크다");//뒤가 크다
		}
		
		numInt = 200;	//int
		integer3 = 200;	//Integer
		
		if(integer3.equals(numInt)){	//같다
			//컴파일러가 자동으로 numInt를 new Integer(numInt)로 변경
			System.out.println("같다");
		}else {
			System.out.println("다르다");
		}
		
		numInt2 = integer3;  // P = R
		//integer3객체의 int 값이 나와서 numInt2에 대입
		//오토언박싱
		
		integer3 = numInt2;	// R = P
		//오토 박싱
		
		double pi = 3.14;
		
		Double rPI = pi; //R타입으로 변경
		rPI = 3.14;
		
		Set<Double> cSET = new HashSet<Double>();
		cSET.add(rPI);
		cSET.add(3.14);
		
		ArrayList<Integer> aar = new ArrayList<Integer>();
		aar.add(integer3);	//R
		aar.add(integer2);	//R
		aar.add(numInt);	//P
		
		Object obj = 10;
		System.out.println(obj);	//10
		
		//obj = "10";
		//System.out.println(obj);	//10
		
		int num4 = (int)(obj) +1;
		System.out.println(num4);	//11
		
		obj = "10";
		System.out.println(obj);	//10
		
		int num5 = Integer.valueOf((String)obj) + 1;
		System.out.println(num5);	//11
		
		int num6 = 5 + ((Integer)obj).intValue();//다른방법

다른 형태로
 obj에는 10을 내포하는 Integer객체의 참조값이 대입
 컴파일 단계에서 Object = new Integer(10);으로 변경
 Object타입의 레퍼런스로 Integer 고유의 메소드를 호출할 수 없다.
 호출하려면 형변환 필요

 

Integer.parseInt(); // str이 숫자라면 그 값 가져오기

		String str = new String("값");
		str = "10";
		numInt = Integer.parseInt(str);//str이 숫자라면 그 값가져오기

 

enum - 열거형

 

public enum Season {
	Spring,
	Summer,
	Fall,
	Winter
}
public class EnumTest {
	Season season;
	int startMonth;
	
	public void seasonInfo() {
		//this.season = "Spring";
		this.season = Season.Spring;
	}
	
	public void seasonShow() {
		System.out.println("계절은 " + season);
		System.out.println("시작 월은 " + startMonth);
	}
	
	public static void main(String[] args) {
		
		EnumTest enumTest = new EnumTest();
		
		enumTest.seasonInfo();
		enumTest.seasonShow();
	}
}

 

반응형