- Array(배열)
동질자료형의 기억장소 집합체
배열길이(배열요소갯수) 구하는 법.... 배열이름.length // args.length
배열은 지역에 선언해도 자동 초기화 된다.
장점 1. 자료를 일괄처리 할 수 있다.
2. new연산자를 사용하여 생성한다. // int a[] = new int [3];
new 연산자는 heap 영역에 클래스 객체를 생성하는 연산자이다.
자바에서는 배열도 클래스의 일종이다. // new연산자를 이용해서 생성하니까.
- 배열 선언 형식
1. 자료형[] 배열명 = new 자료형[요소갯수];
2. 자료형[] 배열명;
배열명 = new 자료형[요소갯수];
3. 자료형[] 배열명 = {초기값1,초기값2,초기값3}; // 변수 a 이름은 stack에 저장되고 초기값3개의 주소값을 가지고 있다.
4. 자료형 배열명[] == 자료형 []배열명
int a[] = {1,2,3} == int a=1; int b=2; int c=3;
String str = "hello"; //stack에 할당.
String str = new String("hello") ; // heap에 할당.
- 2차원 배열
a[][] ={10,20}, {30,40,50};
---------------------------
행수 열수
stack / heap ~~~~~~~
a -> a[0] -> a[0][0]
a[0][1]
a[1 ] -> a[1][0]
a[1][1]
a[1][2]
----------------------------
배열 자동 초기화 예제
------------------------------------------------------------------
int n[] = new int [3];
double d[] = new double [3];
boolean b[] = new boolean [3];
char ch[]= new char[3];
String str[] = new String [3];
n[0]=3;
d[0]=12.5;
b[0]=true;
ch[0]='A';
str[0]="kim";
for(int i=0; i<3; i++)
System.out.println(n[i]+ " "+d[i]+ " " +b[i]+" "+ch[i]+" "+str[i]);
------------------------------------------------------------------
int a[]={1,3,5,7};
int b[]= new int[a.length];
b = a; //변수 a가 가리키는 heap영역의 주소를 b에 대입한다.
//C언어에서는 오류, 자바에서는 가능.
- 문자열을 각 문자 배열의 요소로 분해
문자열.getChars( srcBegin, srcEnd, destArray, destBegin)
시작위치 끝 복사받을 배열이름 복사받을 배열에서의 시작위치
String str = "GoodMorning-Kil-Dong";
char ch[] = new char[str.legth()]; // String은 배열과 달리 클래스이니까 .length() 로 길이를 구한다.
str.getChars(4, 11, ch, 2) // 문자열은 널 문자 포함이니까 11을 넣는다.
-----------------------------
G o o d m o r n i n g -
0 1 2 3 4 5 6 7 8 9 10 11
-----------------------------
* 문자열 srcBegin 문자부터 srcEnd번째 까지를 destArray의 destBegin 번째 부터 복사한다.
--------------------------------------
String str = "Goodmorning-Kim";
char ch[] = new char[str.length()];
str.getChars(4,11,ch,2);
for(int i = 0; i<ch.length; i++)
System.out.println(i+" "+ch[i] +" ");
--------------------------------------------------------------------------------
10~100까지 난수 발생
int a = (int)(Math.random()*91+10); // 10은 가장 작은수, 91는 나올수 있는 가지수
--------------------------------------------------------------------------------
class Lotto
{
public static void main(String args[])
{
int a[] = new int[6];
for(int i=0 ; i<6 ; i++)
{
a[i]=(int)(Math.random()*45)+1;
for(int j=0; j<i; j++)
{
//같은 값이 있는 비교할려고
if(a[i] == a[j])
{
i--;
break;
}
}
}
for(int i=0; i<6 ; i++)
{
System.out.print(a[i]+" ");
}
}//main
}
- 배열 정렬
-----------------------------------------------------------------------------
class Array_Sort
{
public static void main( String [] args )
{
String str[]={"나","사","아","마","바","다","가"};
disp(str);
Arrays.sort(str); // 배열 오름차순 정렬
disp(str);
Arrays.sort(str,Collections.reverseOrder()); //배열 내림차순 정렬
disp(str);
}// end main
static void disp(String arr[])//사용자 정의 함수
{
for(int i=0;i<arr.length; i++)
{
System.out.println(arr[i]+" ");
}
System.out.println();
}
}
Wrapper class // 인자값을 변수가 아닌 객체로만 받는 메서드를 사용할때
byte - Byte
char - Character
short - Short
int - Integer
long - Lon
float - Float
double - Double
boolean - Boolean
------------------
import java.util.*;
class Array_Sort_2
{
public static void main(String args[])
{
Integer a[]={90,88,77,66,55,33};
disp(a);
Arrays.sort(a);//오름차순.......... 인자값을 객체로 받는다.
disp(a);
Arrays.sort(a,Collections.reverseOrder());
disp(a);
}
static void disp(Integer []b)
{
for(int i=0; i<b.length; i++)
System.out.print(b[i]+ " ");
System.out.println();
}
}
----------------------------
객체지향 4대 특징
- 캡슐화, 은닉화
- 상속
- 다형성(Overload, Overriding)
- 추상화(복잡한 것을 단순화)
클래스 설계자 입장
클래스 사용자 입장
- OverLoading
1. 하나의 클래스 내에 이름이 같은 메서드가 여러개 있는 경우.
2. 구분은 매개면수로 한다, 갯수가 다르거나 자료형이 달라야 한다.
3. 확장(상속)이 가능하다.
4. 리턴형은 상관없다.
class AA
{
void aa(){}
int aa(int a){}
String aa(String name){}
}
- Overrding
1. 상속 받은 메서드 내용 재정의
2. 리턴형, 인수, 인수자료형은 반드시 같아야 한다.
3. 접근제한자는 상위와 같거나, 더 넓은 개념으로 사용 할 수 있다.
( 상위의 protected 는 public 사용가능 하다. )
4. 상속관계로서 사용가능.
5. 확장(상속) 가능하다.
----------------------------------------------------------------------------------------------
class 클래스 이름
{
//변수선언
private int age; //은폐필드 (자신의 클래스 내에서만 사용 가능)
생략 int age; //같은 패키지 안에서만..
protected String name; //보호필드 ( 자신의 클래스와 , 상속 받은 클래스에서 사용가능)
public String pum; // 공개필드 ( 어디서나 사용가능)
private 리턴형 메서드명 (){}
생략 리턴형 메서드명 (){}
protected 리턴형 메서드명(){}
public 리턴형 메서드명 (){}
}
class 클래스이름2 extends 클래스 이름 implements 인터페이스명
{
}
----------------------------------------------------------------------------------------------
- 메서드란
기본적으로 프로그램 명령문의 집합이며, 자바에서는 실행의 기본 단위가 된다.
메서드는 클래스에 속한 일부분이다.
System. out. println();
클래스 객체 메서드
- 클래스란
하나 이상의 변수, 또는 메서드를 포함하고 있는 변수와 메서드 집합체이다.
하나의 단위 프로그램이다(모듈)
- 자바 프로그램이란
하나 이상의 클래스로 구성된 클래스 집합체이다.
저장은 main()이 소속해 있는 클래스 이름으로 저장 한다.
프로그램을 실행하는 동안 동일 클래스나, 다른 클래스에 있는 메서드를 호출 할 수 있다.
프로그램 코드는 항상 메서드내에 존재해야 하며, 매서드는 항상 클래스내에 존재해야 한다.
- 메서드 기본 형식
접근제한자 리턴형 메서드이름 (인수)
{
처리내용;
}
[접근제한자] [static] 리턴형 메서드이름 (인수) throws ExceptionList
{
처리내용;
}
메서드는 실행중 런타임 오류가 발생 할 수 있다.
자바에서는 이런 문제를 다룰 수 있는 예외처리 기능이 제공된다.
- 메서드 예제
void aa() {}
boolean bb(int a) {}
int cc(String str ){}
void ee(char) {}
- 메서드 호출
자신의 클래스에서는 ==> 메서드명(인수값)
다른 클래스 메서드 호출 ==> 객체 생성하고 , 객체.매서드(인수값)
static 메서드 호출은 ==> 클래스이름.메서드(인수값), 객체 생성하고, 객체. 메서드()
-------------------------------------------------------------------------
class Test_2
{
public char aa()
{
System.out.println("aa() call...");
return 'A';
}
public int bb(){
System.out.println("bb() call...");
return 100;
}
public double cc(){
System.out.println("cc() call...");
return 30.9;
}
// end Test_2
}
class Method_3
{
public static void main(String args[])
{
Test_2 B = new Test_2();// 객체 생성
char ch = B.aa();
System.out.println("ch : "+ ch);
int in = B.bb();
System.out.println("in : " + in);
double dou = B.cc();
System.out.println("dou : " + dou);
}
}
-------------------------------------------------------------------------
- static 메서드
public static double abs(double a) ==> 절대값
public static double ceil(double a) ==> 올림값
public static double floor(double a) ==> 내림값
public static double round(double a) ==>반올림
public static double max(double a) ==> 둘 중 큰값
예제 // static 메서드는 객체 생성 하지 않고도 호출 가능하다... main메서드 이전에 실행된다..
class Method_1
{
public static void main(String args[])
{
System.out.println(Math.max(12.5, 77.7)); //큰값
System.out.println(Math.min(12.5, 77.7)); //작은값
System.out.println(Math.abs(-10)); //절대값
System.out.println(Math.ceil(5.7)); //반올림
System.out.println(Math.ceil(5.2));
System.out.println(Math.floor(5.7)); //내림값
System.out.println(Math.round(5.7)); //반올림
System.out.println(Math.round(5.3));
System.out.println(Math.pow(2,10)); //승수표현 2^10
}
}