일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- jsoup
- exclusive lock
- 오버라이딩
- 변수와 메서드
- SQL
- 참조타입
- 변수와 상수
- null/not null
- 피연산자
- 연산자와의 관계
- 프로그래머스 코테
- 추상메서드
- 서버 스크립트
- 원시타입
- 즉시로딩
- InterruptedException
- bufferedInputStream
- foreigen key
- Java
- 컬렉션 프레임워크
- 프로그래머스
- N+1
- 오버로딩
- 멱등성
- 메세지 큐
- git 기초
- delete
- 지연로딩
- Shared Lock
- select
- Today
- Total
[JAVA_Back-End]
[JAVA] 패키지 (import) + API (Object) 본문
<이전 포스팅 정리>
2023.08.23 - [JAVA] - [JAVA] 클래스와 인스턴스 + 생성자
[JAVA]
- 객체지향 프로그래밍 (OOP: Object Oriented Programming)
특성 == 문법
1) 캡슐화 (은닉화) - 데이터 숨김
1.1) 접근지정자
public - (default) - protect - private
멤버필드 -> private
메서드 -> public
1.2) setter / getter
set/get + 멤버필드의 대문자로
+ 메서드안의 제어문을 통해서 값을 제어할 수 있음
2) 상속성
2.1) 두 개 이상의 클래스 관계
is ~ a - 상속
has ~ a - 인스턴스
2.2) 부모/자식
=> 공통적인 추출(abstraction) / 유도(확장)
extends 한개 클래스 - 단일 상속
오버라이딩(재정의)
super, super()
final
3) 추상화
4) 다형성
[Package]
패키지 선언
package 패키지명;
패키지
1. 식별자
2. 소문자로 적는것이 좋다. (클래스와 구분하려면)
3. 소스의 첫번째 줄에 적어야한다.
4. 패키지명= 회사의 도메인명으로 사용 (www.naver.com -> com.naver.www(반대로 뒤집어서 패키지명을 사용함))
import 패키지명.클래스명
패키지 있는 클래스 컴파일
> javac -encoding utf-8 -d. 파일명
패키지 있는 클래스 실행
> java pack1.파일명
자바 내장 라이브러리(API)
외부 제공되는 라이브러리(API)
(모듈)-> 패키지 -> 클래스
(java 9)
IDE - 개발자 도구 = 개발 편리성(문법)
Eclipse 사용,,,, (나중에 jsp를 하기 위한 web developers 으로 다운받기)
Eclipse workspace 설치경로
-> C:\Java\java-workspace
JAVAEE
JAVA로 변경
uft-8
Java Project와 class생성하기 (이름만 설정)
C:\Java\java-workspace\JavaEx01\src ==> java소스 확인 가능
C:\Java\java-workspace\JavaEx01\bin ==> class파일 확인 가능
[Eclipse 사용법]
Getter/Setter 자동생성: 클래스(멤버필드)안에서 오른쪽 클릭 -> Source -> Generate Gatters and Setters 선택
생성자 자동생성: 클래스 안에서 오른쪽 클릭 -> Source -> Generate Constructor using Fields 선택
* PackEx02.java - 패키지 추가 후 클래스 선언
* Person.java
- 모든 클래스에는 최상위 클래스인 Object클래스를 상속받는다.
* ObjectEx01.java - 오브젝트 클래스를 사용하여 참조값 출력
* ObjectEx02.java - toString()을 사용하여 오버라이딩 후 내용 출력
*ObjectEx03.java - 내용 값과 참조 값의 차이 확인
* Student.java - setter과 getter가 정의된 Student 클래스
* StudnetEx01.java - Student 클래스를 참조하여 set으로 값 넣고 get으로 받아오기
Eclipse 사용하여 코딩
* JavaEx03.java - eclipse에서 클래스 정의 + 객체로 선언 + 메서드 호출 |
import com.naver.Child; import com.naver.Parent; publicclass JavaEx03 { publicstaticvoid main(String[] args) { // TODO Auto-generated method stub Parent p =new Parent(); //parent class를 객체로 선언한 뒤 viewParent()메서드를 호출함 p.viewParent(); Child c =new Child(); //parent class를 객체로 선언한 뒤 viewParent()메서드를 호출함 c.viewChild(); c.viewParent(); //child에 parent의 viewParent메서드를 오버라이딩하여 호출함 } } |
* Child.java |
package com.naver; publicclass Child extends Parent { publicvoid viewChild() { System.out.println("Child viewChild() 호출"); } //annotation => compiler 알려주는 역할 @Override publicvoid viewParent() { // TODO Auto-generated method stub System.out.println("Child viewParent()호출"); } } |
* Parent.java |
package com.naver; public class Parent { publicvoid viewParent(){ System.out.println("Parent viewParent() 호출"); } } |
< 문자열 출력 - 다양한 클래스 적용하기 >
* Ex9_12.java |
public class Ex9_12 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("01"); StringBuffer sb2 = sb.append(23); sb.append('4').append(56); StringBuffer sb3 = sb.append(78); sb3.append(9.0); System.out.println("sb="+sb); System.out.println("sb2="+sb2); System.out.println("sb3="+sb3); System.out.println("sb="+sb.deleteCharAt(10)); System.out.println("sb="+sb.delete(3,6)); //3에서 6까지 문자열 삭제 System.out.println("sb="+sb.insert(3,"abc")); System.out.println("sb="+sb.replace(6, sb.length(), "END")); System.out.println("capacity="+sb.capacity()); System.out.println("length="+sb.length()); } } |
* InitcapEx02.java - hong gil dong -> Hong Gil Dong 으로 이름 앞글자 대문자로 변환 |
public class InitCapEx02 { public static void main(String[] args) { if(args.length !=1) { System.out.println("1개를 입력하셔야 합니다."); }else { Util u = new Util(args[0]); System.out.println(u.capitalizeName()); } } } |
* Util.java - InitcapEx02.java 의 참조 클래스 |
public class Util { private String name; public Util(String name) { this.name=name; } public String capitalizeName() { String [] names= this.name.split(" "); //이름을 공백으로 나눈다 (argument로 받음) String result=""; for(int i=0;i<names.length;i++) { result=names[i].substring(0,1).toUpperCase()+names[i].substring(1); //나눈 이름중 한글자씩은 substring으로 나눠 첫번째 자리만 Uppercase를 적용한다. } return result; } } |
Hong Gil Dong예제 실행시킬 때 => args로 받아서 결과값을 출력하기 때문에 argument로 실행시키기
오른쪽 클릭 -> Run as -> Run Configurations -> Arguments
* Ex9_15.java - 문자열을 숫자로 변환하기 |
public class Ex9_15 { public static void main(String[] args) { // TODO Auto-generated method stub int i = new Integer("100").intValue(); int i2 =Integer.parseInt("100"); Integer i3 =Integer.valueOf("100"); int i4 = Integer.parseInt("100",2); int i5=Integer.parseInt("100",8); int i6=Integer.parseInt("100",16); int i7=Integer.parseInt("FF",16); //int i8=Integer.parseInt("FF"); // NumberFormatException발생 Integer i9 = Integer.valueOf("100",2); Integer i10 = Integer.valueOf("100",8); Integer i11 = Integer.valueOf("100",16); Integer i12 = Integer.valueOf("FF",16); //Integer i13 = Integer.valueOf("FF"); //NumberFormatException 발생 System.out.println(i); System.out.println(i2); System.out.println(i3); System.out.println("100(2)->"+i4); System.out.println("100(8)->"+i5); System.out.println("100(16)->"+i6); System.out.println("FF(16)->"+i7); System.out.println("100(2)->"+i9); System.out.println("100(8)->"+i10); System.out.println("100(16)->"+i11); System.out.println("FF(16)->"+i12); } } |
* Ex9_16.java - 오토박싱 & 언박싱 오토박싱 & 언박싱 오토박싱 - 기본형 값을 래퍼 클래스의 객체로 자동 변환해주는 것 언박싱 - 래퍼 클래스의 객체를 기본형 값으로 자동 변환해주는 것 |
public class Ex9_16 { public static void main(String[] args) { // TODO Auto-generated method stub int i=10; Integer intg =(Integer)i; Object obj=(Object)i; Long lng =100L; int i2=intg+10; long l =intg+lng; Integer intg2 = new Integer(20); int i3 = (int)intg2; Integer intg3 =intg2 +i3; System.out.println("i ="+i); System.out.println("intg ="+intg); System.out.println("obj ="+obj); System.out.println("lng ="+lng); System.out.println("intg+10 ="+i2); System.out.println("intg+lng ="+l); System.out.println("intg2 ="+intg2); System.out.println("i3 ="+i3); System.out.println("intg2 + i3 ="+intg3); } } |
< Math클래스 적용 >
* MathEx01.java - 올림/내림/반올림 |
public class MathEx01 { public static void main(String[] args) { System.out.println(Math.ceil(10.3)); //올림 System.out.println(Math.ceil(10.5)); System.out.println(Math.ceil(10.7)); System.out.println(Math.floor(10.3)); //내림 System.out.println(Math.floor(10.5)); System.out.println(Math.floor(10.7)); System.out.println(Math.round(10.3)); //반올림 System.out.println(Math.round(10.5)); System.out.println(Math.round(10.7)); System.out.println(Math.pow(10.0, 2.0)); } } |
* MathEx02.java - 랜덤함수(random) |
public class MathEx02 { public static void main(String[] args) { // TODO Auto-generated method stub //0에서 1까지의 난수 발생 System.out.println((int)(Math.random()*10)); //정수화 시킬 때 (int)로 하면 된다. System.out.println((int)(Math.random()*10)); System.out.println((int)((Math.random())*45)+1); } } |
*StringBuilderEx01.java - 문자열의 길이를 확인하기 |
public class StringBuilderEx01 {
public static void main(String[] args) { // TODO Auto-generated method stub StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(100); StringBuilder sb3 = new StringBuilder("Hello Java"); System.out.println(sb1.capacity()); //기본이 16 System.out.println(sb2.capacity()); //100의 용량을 만들어냄 System.out.println(sb3.capacity()); //문자열 길이 + 16 =26 System.out.println(sb1.length()); //실제 데이터가 들어간 길이 System.out.println(sb2.length()); System.out.println(sb3.length()); //charAt //substring //indexOf //replace // 내부 문자열 조작 //append / insert / delete System.out.println(sb3); sb3.append("안녕"); //문자열 뒤에 문자열 추가하기 System.out.println(sb3); sb3.insert(3, "추가내용"); //문자열 사이에 문자열 추가하기 System.out.println(sb3); sb3.delete(0, 4); //문자열 범위 지정해서 삭제하기 System.out.println(sb3); } } |
*StringEx01.java - 문자열 출력하기 (참조값 비교 vs 내용 비교) |
public class StringEx01 { public static void main(String[] args) { // TODO Auto-generated method stub //문자열 생성 String str1 = "Hello Java"; //생성자 String str2= new String("Hello Java"); char[] arr = {'H', 'e', 'l','l','o','j'}; String str3 =new String(arr); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str1.toString()); String str11 = new String("java"); String str12 = new String("java"); //참조값 비교 (false) System.out.println(str11==str12); //내용비교 (true) System.out.println(str11.equals(str12)); String str21 = "Hello Java"; String str22 = "Hello Java"; System.out.println(str21==str22); System.out.println(str21.equals(str22)); } } |
*StringEx02.java - 문자와 문자열 |
public class StringEx02 { public static void main(String[] args) { String str1="Hello String Hello String"; System.out.println(str1.length()); System.out.println("Hello".length()); //문자열(String) - 문자(char) char c1=str1.charAt(0); char c2=str1.charAt(5); System.out.println(c1); System.out.println(c2); //문자열(String) - 문자열(String) //String pstr1 = str1.charAt(2); //System.out.println(pstr1); } } |
*StringEx03.java - 문자와 문자열의 다양한 활용 |
public class StringEx03 {
public static void main(String[] args) { String str1="Hello String Hello String"; //문자열 위치 검색 int pos1 = str1.indexOf('l'); // 영문자 l System.out.println(pos1); int pos2 = str1.indexOf("zz"); //영문자 System.out.println(pos2); //문자열의 존재 여부 // endsWith //contains System.out.println(str1.startsWith("he")); //문자열 치환 String rstr = str1.replace("Hello", "안녕"); //Hello를 안녕으로 치환 System.out.println(rstr); //문자열 String jstr = str1.concat("안녕"); //str1뒤에 문자열을 추가함 System.out.println(jstr); //대소문자 변환 System.out.println("hello".toUpperCase()); //대문자 변환 System.out.println("HELLO".toLowerCase()); // 소문자 변환 //공백제거 trim String ostr1=" Hello Java "; System.out.println(ostr1.trim()); //문자열 분리 String sstr = "google, banana, pineapple, kiwi"; String[] arr1= sstr.split(","); // ,을 기준으로 각 단어들을 배열상태로 만듦 System.out.println(arr1[0]); System.out.println(arr1[3]); String sstr2 = String.join(";",arr1); System.out.println(sstr2); } } |
< 시스템 클래스 >
* SystemEx01.java - 프로그램의 흐름 파악하기 |
public class SystemEx01 {
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("프로그램 시작"); if(args.length !=1) { System.out.println("1개를 입력하셔야 합니다"); //프로그램 종료 (밖으로 빠져나와 출력문이 출력되는 것이 아닌 if문 안에서 종료될 수 있도록 함) System.exit(0); } System.out.println("정상실행"); //정상일때는 정상실행이 출력되고, 입력이 없을 때는 if문 안으로 가 오류문을 출력하고 그 안에서 프로그램 종료가 될 수 있도록 한다. System.out.println("프로그램 끝"); } } |
* SystemEx02.java - 프로그램의 실행시간 측정 |
public class SystemEx02 { public static void main(String[] args) { // TODO Auto-generated method stub //프로그램의 실행시간 측정 long time1= System.currentTimeMillis(); //ms단위 //long time1=System.nanoTime(); int sum=0; for( int i =1;i<=1_000_000;i++) { sum+=i; } long time2=System.currentTimeMillis(); System.out.println("실행시간 : "+(time2 - time1)); } } |
* SystemEx03.java - 출력문과 출력문 사이의 공백 |
public class SystemEx03 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello"); // \n-엔터 //System.out.println("\n"); System.out.println(System.lineSeparator()); //엔터역할 -> 줄과 줄 사이의 공백을 담당 System.out.println("World"); } } |
* SystemEx04.java - 시스템 정보 확인하기 |
public class SystemEx04 {
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(System.getProperty("os.name")); //시스템의 OS확인 System.out.println(System.getProperty("user.name")); //시스템 사용자 이름 확인 System.out.println(System.getProperty("user.home")); //시스템의 홈 경로 확인 } } |
* WrapperEx01.java - 래퍼 클래스 - 원시 자료형 값을 객체로 포장하는 클래스 - 기본형 변수도 객체로 다뤄야 할 경우 - 매개변수로 객체를 요구할 때, 기본형 값이 아닌 객체로 저장해야할 때, 객체간의 비교가 필요할 때 사용 |
public class WrapperEx01 { public static void main(String[] args) { //최대 최소 System.out.println(Integer.MIN_VALUE); //integer의 최소 System.out.println(Integer.MAX_VALUE); //integer의 최대 System.out.println(Double.MIN_VALUE); //double의 최소 System.out.println(Double.MAX_VALUE); //double의 최대 //형변환 Integer i1 = Integer.valueOf(123); Integer i2 = Integer.valueOf("123"); //Autoboxing (자동으로 박스화 시킴) Integer i3 =123; byte b =i1.byteValue(); float f =i1.floatValue(); String s = i1.toString(); //unboxing int i4=i3; } } |
* JuminCheck.java - 올바른 주민번호인지 확인하기 |
//형식이 맞다 아니다로 출력되게하기 public class JuminCheck { public static void main(String[] args) { // TODO Auto-generated method stub //입력값 검사 if(args.length != 1) { System.out.println("1개를 입력하셔야 합니다"); System.exit(0); }else { Util2 u = new Util2(args[0]); //형식이 맞다 아니다로 출력되게하기 if(u.Jumin()==true) { System.out.println("올바른 형식입니다"); }else { System.out.println("올바른 형식이 아닙니다"); } } } } |
* Util2.java - JuminCheck.java의 참조 클래스 |
public class Util2 { String jumin2; public Util2(String args) { // TODO Auto-generated constructor stub this.jumin2= args; } public Boolean Jumin() { String jumin= this.jumin2.replace("-",""); int[] arr1= new int[] {2, 3,4,5,6,7,8,9,2,3,4,5}; int sum=0; for(int i=0;i<arr1.length;i++) { sum+=Integer.parseInt(jumin.substring(i,i+1))*arr1[i]; } int lastNum = Integer.parseInt(jumin.substring(12,13)); int resultsum=(11-(sum%11))%10; if(lastNum==resultsum) { return true; }else { return false; } } } |
< 정리 >
[Wrapper 클래스]
1. 자료형에 대한 최대 최소
2. 형변환을 할 수 있음
오토박싱 & 언박싱
오토박싱 - 기본형 값을 래퍼 클래스의 객체로 자동 변환해주는 것
언박싱 - 래퍼 클래스의 객체를 기본형 값으로 자동 변환해주는 것
'Programming > JAVA' 카테고리의 다른 글
[JAVA] 에러처리 + ArrayList (0) | 2023.08.29 |
---|---|
[JAVA] 프로세스 (0) | 2023.08.25 |
[JAVA] 클래스와 인스턴스 + 생성자 (0) | 2023.08.23 |
[JAVA] 배열, 객체지향 프로그래밍 (0) | 2023.08.22 |
[JAVA] JAVA 변수, 연산자, 조건문과 반복문 (2) | 2023.08.21 |