Static variable

:Static variables are also known as Class variables.

A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

 

 

스태틱변수=클래스변수

:만약 클래스 내에서 모두 공유하고 싶은 변수가 있다면 스택틱 변수로 선언해야한다.
스태틱변수는 클래스멤버 변수를 의미한다.

 

public class MemberVariable {
	public static Random rd = new Random();
	public static int num=0;   //Static variable
	
	public static void method0() {
		System.out.println("method0: "+num);
		num = rd.nextInt(100);
		System.out.println("method0: "+num);
	}

	public static void method1() {
		System.out.println("method1: "+num);
		num = rd.nextInt(100);
		System.out.println("method1: "+num);

	}

	public static void main(String[] args) {
		method0();
		System.out.println("num:"+num);
		method1();
		System.out.println("num:"+num);
	}
}

Local Variable

:A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

 

:메서드의 중괄호 영역 내에 선언된 변수를 지역변수라고 한다.

 

지역변수의 특징

1) stack메모리에 올라가며 메서드의 호출이 끝나면 스택에서 사라진다.
메모리를 절약하기위해 필용할떄 선언하고 용도가 끝나면 사라지도록 설계한 변수이다.
2) 지역에서만 사용가능하다. 즉 다른 메서드에 동일한 이름의 변수가 있어도 서로 다른 변수이다.
3) 매개변수도 지역변수이다.

 

!! 만약 여러개의 메서드에서 하나의 변수를 접근하고 싶다면 클래스 영역에 선언해야만한다.
!! 클래스에 선언한 변수는 모든 메서드에서 접근가능하다.

 

public class LocalVariable {
	//ClassVariable
	public static Random rd = new Random();
	
	public static void method0() {
		int num=0; //LocalVariable, num of method1
		num = rd.nextInt(100);
		System.out.println("method0: "+num);
	}

	public static void method1() {
		int num=0; //LocalVariable, num of method1
		num = rd.nextInt(100);
		System.out.println("method1: "+num);

	}

	public static void main(String[] args) {
		int num=0;//num of Main method
		method0();
		System.out.println("num:"+num);
		method1();
		System.out.println("num:"+num);
	}
}

declaire a temperary value or array.

public class SwapValue {
	public static void main(String[] args) {
		int num0 = 10, num1 = 20;
		System.out.printf("num0:%d, num1:%d", num0, num1);

		// 스왚이 불가능한 구조
		// num0=num1;//넘0에 넘1을 대입하라 ->넘0은 20이됨
		// num1=num0;//넘1에 넘0을 대입하라. 위에서 넘0이 20이 되었으니 넘1도 20이됨.

		// 옳은 방법
		// temp를 설정해서 넘0의 값을 임시로 넘겨줌
		int temp = num0;
		num0 = num1;
		num1 = temp;
		System.out.printf("\nnum0:%d, num1:%d", num0, num1);

	}
}
public class SwapArray {

	public static void swapArr(int[]_arr) {
		int temp =_arr[0];
		_arr[0] =_arr[1];
		_arr[1]=temp;
	}
	public static void main(String[] args) {
		int[] arr = { 10, 20 };
		System.out.println(Arrays.toString(arr));
		swapArr(arr); //int[] _arr = arr;
		System.out.println(Arrays.toString(arr));
	}
}

'java' 카테고리의 다른 글

Java/Static variable/스태틱변수, 클래스변수  (0) 2020.01.28
Java/Local Variable/지역변수  (0) 2020.01.28
Java/return문;  (0) 2020.01.27
Java/Def of Method2/메소드정의2  (0) 2020.01.27
Java/Def of Method/메소드정의  (0) 2020.01.27

return문
이 메서드를 호출한 곳으로 돌아가라.

 

1) return num;
num의 값을 가지고 돌아가라.
이 메서드의 결과값은 num이다. 

2) void 일 때 return은
빈손으로 돌아가라.
이 메서드에는 결과 값이 없다.
메서드의 실행을 중단하라.

 

public static void divide(int num0,int num1) {
		if(num1==0)
		{
			System.out.println("0으로 나눌수없습니다");
			return;
			}
		System.out.println("나눗셈결과:" + (num0/num1));
		}
	public static void main(String[] args) {
		
		divide(9,2);
		divide(4,0);
		
	}

'java' 카테고리의 다른 글

Java/Local Variable/지역변수  (0) 2020.01.28
Java/Swap values and arrays  (0) 2020.01.27
Java/Def of Method2/메소드정의2  (0) 2020.01.27
Java/Def of Method/메소드정의  (0) 2020.01.27
Java/Multi-dimensional array/이차원배열  (0) 2020.01.27

메서드(함수)
;기능을 일정영역으로 묶어서 사용하기 쉽도록 만든것

 

조건
1) 일부의 값은 변경되지만 
2) 논리가 동일한 코드가 반복될 때 

 

메서드를 만들면
1) 코드의 양이 줄어든다.  
2) 한눈에 파악이 된다.
3) 메서드의 내용만 수정하면 사용하는 모든 곳에 적용된다.
4) 자동차부품처럼 일부에 문제가 생기면 해당부품(메서드)만 수정하거나 교체하면 된다.(비용/시간이 절감된다.)


메서드의 형태

1)
리턴타입 메서드명 (매개변수,.....){
**메서드의영역**
*return리턴타입변수;*
}


2)
void 메서드명(매개변수){
**메서드의영역**
*리턴을 써도 되고 안써도 됨*
}

	int num0 = 0, num1 = 0;
		int result = 0;

		num0 = 10;
		num1 = 20;
		result = num0 + num1;
		System.out.printf("%d+%d의 합 [%d]\n", num0, num1, result);

		num0 = 100;
		num1 = 200;
		result = num0 + num1;
		System.out.printf("%d+%d의 합 [%d]\n", num0, num1, result);

		num0 = 1000;
		num1 = 2000;
		result = num0 + num1;
		System.out.printf("%d+%d의 합 [%d]\n", num0, num1, result);


		// 이런식으로 할 수 있지만 불편하고 비효율적이기 때문에
		// 논리가 반복이 될 때, 논리의 표현을 단순화 시키고 변수의 값만 수정할 수 있게
        //---> 메서드의 역할

//메서드의 영역
	public static void add(int num0, int num1) {
		int result=0;
		result = num0 + num1;
		System.out.printf("%d+%d의 합 [%d]\n", num0, num1, result);///동일한 코드의 반복

	}
	
	
	
	public static void main(String[] args) {
		add(10,20); 
		add(100,200);
		add(1000,2000);//값의변경
		
	}

//메서드를 만들땐 !!!하나의 메서드에 하나의 기능만 넣는 것!!!을 원칙으로 한다. -> 유연성증가


public class SuitableMethod {
	public static Scanner sc = new Scanner(System.in);

	public static void greeting() {
		System.out.println("안녕하세요");
	}

	public static int input() {
		System.out.println("수입력: ");
		int num = sc.nextInt();
		return num;
	}

	public static int add(int num0, int num1) {
		return num0 + num1;
	}

	public static void viewResult(int result) {
		System.out.println("합:" + result);
	}

	public static void main(String[] args) {

		greeting();
		int num0 = input();
		int num1 = input();
		int result = add(num0, num1);
		viewResult(result);

		greeting();
		int num2 = input();
		int num3 = input();
		int num4 = input();
		int result1 = add(num2, num3 + num4);
		viewResult(result1);

	}

'java' 카테고리의 다른 글

Java/Swap values and arrays  (0) 2020.01.27
Java/return문;  (0) 2020.01.27
Java/Def of Method/메소드정의  (0) 2020.01.27
Java/Multi-dimensional array/이차원배열  (0) 2020.01.27
Java/Arrays Sort  (0) 2020.01.27
public static void main(String[] args) {
		System.out.println("좋은아침");
		Scanner sc = new Scanner(System.in);
		System.out.println("나이?");
		int age = 0;
		age = sc.nextInt();
		if (age > 40)
			System.out.println("꾸벅");
		else if (age > 30)
			System.out.println("까딱");
		else if (age > 20)
			System.out.println("어이");
		else if (age > 10)
			System.out.println("여어");
		sc.close();
	}
public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int age = 0;
		while (true) {
			System.out.println("좋은아침");
			System.out.println("나이?");
			age = sc.nextInt();

			if (age > 40)
				System.out.println("꾸벅");
			else if (age > 30)
				System.out.println("까딱");
			else if (age > 20)
				System.out.println("어이");
			else if (age > 10)
				System.out.println("여어");
			else if (age < 0)
				break;
		}
		sc.close();
	}
	public static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {

		while (true) {
			int ret = greeting();
			if (ret < 0)
				break;
		}
///greeting(); 단독으로사용가능

	}

	public static int greeting() {
		int age = 0;
		System.out.println("좋은아침");
		System.out.println("나이?");
		age = sc.nextInt();

		if (age > 40)
			System.out.println("꾸벅");
		else if (age > 30)
			System.out.println("까딱");
		else if (age > 20)
			System.out.println("어이");
		else if (age > 10)
			System.out.println("여어");
		return age;
	}
public static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {

		while (true) {
			int ret = getAge();
			greeting(ret);
			if (ret < 0)
				break;
		}

	}

	public static int getAge() {
		int age = 0;
		System.out.println("좋은아침");
		System.out.println("나이?");
		age = sc.nextInt();

		return age;
	}

	public static void greeting(int _age) {

		if (_age > 40)
			System.out.println("꾸벅");
		else if (_age > 30)
			System.out.println("까딱");
		else if (_age > 20)
			System.out.println("어이");
		else if (_age > 10)
			System.out.println("여어");

	}

 

'java' 카테고리의 다른 글

Java/return문;  (0) 2020.01.27
Java/Def of Method2/메소드정의2  (0) 2020.01.27
Java/Multi-dimensional array/이차원배열  (0) 2020.01.27
Java/Arrays Sort  (0) 2020.01.27
Java/What is Array/Exercise/배열기초  (0) 2020.01.27

ex1

	int[][] kor = new int[3][5];// 3개반 5명
		Random rd = new Random();

		System.out.println(kor + "," + kor.length);//// kor은 참조값을 가르킴
		System.out.println(kor[0] + "," + kor[0].length);/// kor.length는 칸의 갯수
		System.out.println(kor[1] + "," + kor[1].length);
		System.out.println(kor[2] + "," + kor[2].length);

		// for (int i = 0; i < 3; i++) 3은 kor.length
		// for (int j = 0; j < 5; j++) 5는 kor[].length 로 치환
		for (int i = 0; i < kor.length; i++) {
			for (int j = 0; j < kor[1].length; j++) {
				kor[i][j] = rd.nextInt(100);
			}
		}

		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print(kor[i][j] + ",");
			}
			System.out.println();
		}
[[I@6d06d69c,3
[I@7852e922,5
[I@4e25154f,5
[I@70dea4e,5
35,91,31,91,41,
93,21,8,36,19,
95,7,99,8,50,

 

 

ex2

declaire 4x6 arrays, assign numbers from 1 and print all.

int[][] test = new int[4][6];

		int cnt = 0;/// 숫자대입할변수설정
		// 데이터대입용
		for (int i = 0; i < test.length; i++) {
			for (int j = 0; j < test[i].length; j++) {
				test[i][j] = ++cnt;// 숫자계속 대입 test안의 칸이 다찰때 까지
			}
		}

		// 데이터출력용
		for (int i = 0; i < test.length; i++) {
			for (int j = 0; j < test[i].length; j++) {
				System.out.print(test[i][j] + ", ");

			}

			System.out.println();
		}
1, 2, 3, 4, 5, 6, 
7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 

 

 

ex3

/*
		    ┌[][][][]
		[0][1][2]:arr
		ㄴ[][]  ㄴ[][][]
		
		*/
		int[][] arr = new int[3][];
		arr[0] = new int[2];
		arr[1] = new int[4];
		arr[2] = new int[3];// 총 9개의 저장공간
		int cnt = 0;

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				arr[i][j] = ++cnt;
			}
		}

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.print(arr[i][j] + ",");
			}
			System.out.println();
		}
1,2,
3,4,5,6,
7,8,9,

'java' 카테고리의 다른 글

Java/Def of Method2/메소드정의2  (0) 2020.01.27
Java/Def of Method/메소드정의  (0) 2020.01.27
Java/Arrays Sort  (0) 2020.01.27
Java/What is Array/Exercise/배열기초  (0) 2020.01.27
Java/Break and Labeled break;  (0) 2020.01.27
int[] scores = { 98, 12, 99, 9, 25 };
		System.out.println(Arrays.toString(scores));// 스코어내의 모든 정보확인

		// 오름차순 정렬
		Arrays.sort(scores); // 데이터가 적을떄
		// Arrays.parallelSort(scores); //데이터가 많을 떄

		System.out.println(Arrays.toString(scores));// 스코어내의 모든 정보확인
[98, 12, 99, 9, 25]
[9, 12, 25, 98, 99]

 

 

 

ex

get 5 numbers from users and print maximum and minimum value.

int[] score = new int[5];
		Scanner sc = new Scanner(System.in);

		for (int i = 0; i < score.length; i++) {
			System.out.println((i + 1) + "번째 정수를 입력하세요:");
			score[i] = sc.nextInt();
		}

		Arrays.sort(score);// 오름차순정렬
		System.out.println("최대값:" + score[score.length - 1]);
		System.out.println("최소값:" + score[0]);
		sc.close();

'java' 카테고리의 다른 글

Java/Def of Method/메소드정의  (0) 2020.01.27
Java/Multi-dimensional array/이차원배열  (0) 2020.01.27
Java/What is Array/Exercise/배열기초  (0) 2020.01.27
Java/Break and Labeled break;  (0) 2020.01.27
Java/Do-while loop  (0) 2020.01.25