JAVA

메소드

장꾸꾸 2020. 8. 13. 18:42

메소드 

특정 기능의 모음, 집합, 덩어리. 객체의 동작에 해당하는 중괄호 {} 블록을 말한다. 이 중괄호 블록의 이름이 메소드의 이름이다. 메소드 호출시 중괄호 블록의 모든 코드들이 일괄적으로 실행된다. 메소드는 객체 간의 데이터 전달의 수단으로 사용된다. 외부로부터 매개값을 받을 수도 있고, 실행 후 어떤 값을 리턴할 수도 있다. 

 

+ void : 반환값의 종류를 의미하는 자리다.

 

// 클래스 라인
public class method {
	// 메소드 라인 각각의 라인에 맞춰서 줄을 잘 정리해줘야하는 이유
	public static void main(String[] args) {
// 1. 파라메타로 받은 숫자 구구단으로 보여주는 메소드
		System.out.println("구구단");
		gugu(2);
		gugu(3);
		gugu(4);
		gugu(5);
		gugu(6);
		gugu(7);
		gugu(8);
		gugu(9);
		
		System.out.println("사칙연산");
		math(4, "+", 6);
		math(7, "-", 6);
		math(4, "*", 6);
		math(7, "%", 6);
		
	}

	static void gugu(int number) {
		System.out.println(number + "단");
		for (int n = 1; n <= 9; n++) { // n을 1~9사이로 설정한다.
			System.out.println(number + "X" + n + "=" + (number * n));
		}
	}

//숫자 2개와 사칙연산 기호를 받아 계산결과를 보여주는 메소드
//if문을 사용해 연산자에 맞는 결과를 보여주도록 한다.
	static void math(int number2, String sign, int number3) {	
		if(sign.equals("+")){
			System.out.println(number2 + "+" + number3 + "=" + ((number2 + number3)));
		}else if(sign.equals("-")){
			System.out.println(number2 + "-" + number3 + "=" + ((number2 - number3)));
		}else if(sign.equals("*")){
			System.out.println(number2 + "*" + number3 + "=" + ((number2 * number3)));
		}else if(sign.equals("%")){
			System.out.println(number2 + "%" + number3 + "=" + ((number2 % number3)));
		}

	}
}

 

 

리턴값이 있는 메소드는 언제 쓸까? : 욕설필터로!

 

public class Main {

	public static void main(String[] args) {		

		String str = "바보야 너는 정말 병맛이야 지랄 좀 고만고만 해라";
		str = holyShitFilter(str);
		System.out.println(str);
	}
	
	static String holyShitFilter(String original) {
		String result = original;
		result = result.replace("바보", "**");
		result = result.replace("병맛", "**");
		result = result.replace("십팔", "**");
		result = result.replace("지랄", "**");
		
		return result;
	}

 

exercise) 리턴값 메소드 연습

 

// 클래스 라인
public class method {
	// 메소드 라인 각각의 라인에 맞춰서 줄을 잘 정리해줘야
	public static void main(String[] args) { //void는 리턴값이 없을 때, 리턴값이 있는 메소드는 변수의 유형대로 int, string등을 기재
		int a = 2;
		int b = 3;
		int temp1 = sum(a, b); // 리턴값이 날아가지 않도록 임시저장 공간을 만들어준다 
		System.out.println(temp1);
	}			

	static int sum(int a, int b) {
		int result2 = a + b;
		return result2;
	}
}

 

import java.lang.reflect.Array;

// 클래스 라인
public class method {
	// 메소드 라인 각각의 라인에 맞춰서 줄을 잘 정리해줘야
	public static void main(String[] args) { //void는 리턴값이 없을 때, 리턴값이 있는 메소드는 변수의 유형대로 int, string등을 기재

		int[] array1 = {5,66,8,9,108,80,69};
		int temp2 = array(array1);
		System.out.println(temp2);
	}
	
	static int array(int[] c){  // return 값이 없는 경우가 생기지 않도록 for문 바깥에 한다.
		int result3=0; 
		int sum = 0; //총합계산 위한 변수 선언
		for(int i = 0; i<c.length; i++) {
			sum += c[i]; // += 
			result3 = sum;
		}
		return result3;
	}
}

 

+ 총합 구하기 sum

 

public class test11111 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] array1 = {5,66,8,9,108,80,69};
		int sum = 0;
		for (int i =0; i <array1.length; i++) {
			sum += array1[i];
		}
		System.out.println(sum);
	}
}

 

+ call by reference 오류

primitive 원시타입과 reference를 혼동하지 말것

string은 특별해서 primitive 타입과 동일하게 취급되지만 이것 외에는 분명 다르다

 

깊은 복사와 얕은 복사 헷갈리지 말기

call by value

call by reference를 구분하자

 

public class Main {

	public static void main(String[] args) {
		int num =10;
		int num2 = num;
		num2++;
		System.out.println(num);
		
		int[] arr1 = { 10 };
		int[] arr2 = arr1;
		arr2[0]++;
		System.out.println(arr1[0]);
		
		String str = "aa";
		String str2 = str;
		str2 = "bb";
		System.out.println(str);
		
//		int num =10;
//		System.out.println(num);
//		a(num);
//		System.out.println(num);
//		
//		int[] num1 = { 10 };
//		System.out.println(num1[0]);
//		b(num1);
//		System.out.println(num1[0]);
	}	
	static void a(int num) {
		num++;
		System.out.println(num);
	}
	static void b(int[] num1) {
		num1[0]++;
		System.out.println(num1[0]);
	}	

}

https://re-build.tistory.com/3

 

[Java] Call by value와 Call by reference

이번에 다룰 주제는 Call by value, Call by reference 입니다. 함수의 호출 방식에는 Call by value와 Call by reference가 있습니다. 말 그대로 '값에 의한 호출'이냐, '참조에 의한 호출'이냐 라고 할 수 있는..

re-build.tistory.com