티스토리 뷰
package methodex;
public class MethodEx1 {
// TODO 이름만 있는 메서드 : call by name : 인자가 없다. 제어권만 있던 것으로 돌아가고 리턴값이 없는 것.
public static void view() { // 리턴 값이 없어서 void 를 쓰는 것.
System.out.println("Hello");
return; // 생략 가능
}
public static void star() {
System.out.println("*****");
}
public static void main(String[] args) {
view();
star();
view();
star();
}
}
Call by name 방식
package methodex;
// TODO
public class MethodEx2 {
public static int view1(){ // void가 아니라 int로 준다 리턴값에 맞춰서
return 10;
}
public static char view2() {
return 'A'; //char는 작은 따옴표
}
public static float view3() {
return 50.3f; //float을 리턴할 때는 뒤에 f를 붙인다.
}
public static boolean view4() {
return true;
}
public static String view5() {
return "Hello";
}
public static void view6() {
System.out.println("굿모닝");
}
public static void main(String[] args) {
int a = view1(); // 오류가 안나게 하려면 return 값을 int로 줘야 함
System.out.println(a);
char b = view2();
System.out.println(b);
float c = view3();
System.out.println(c);
System.out.println(view4());
System.out.println(view5());
view6();
}
}
Call by value 방식
package methodex;
public class Test {
public static void main (String[] args) {
char a = 'A';
String b = "Hello";
double c = 56.897867;
int d = 100;
//역슬러시 \n 붙이면 줄바꿈
System.out.printf("%c\n", a); //%c : 문자(char)
System.out.printf("%s\n", b); //%s : 문자열(string)
System.out.printf("%10.3f\n", c);
System.out.printf("%-10.3f\n", c); //%f : 실수(float, double)
System.out.printf("%.3f\n", c);
System.out.printf("%d\n", d);//%d : 정수(int, short, byte, long)
}
}
package methodex;
// TODO Call by Value : 값을 전달하는 방식
public class MethodEx3 {
public static void show(int a, char b, double c, float d) {
System.out.println(a+""+b+""+c+""+d);
}
public static int show2(int a, int b, int c) {
int d = a+b+c;
return d;
}
public static double show3(int a, int b, int c) {
return (double)(a+b+c)/3; //정수 나누기 정수는 정수.
// 실수 나누기 실수는 실수. 그래서 double을 붙여줌
}
public static String show4(int a, int b, int c) {
double result = (double)(a+b+c)/3;
if (result >= 60) {
return "합격";
}else {
return "불합격";
}
}
public static void main(String[] args) {
show(10, 'A', 10.4, 100.3f);
int sum = show2(95,85,73);
System.out.println("합계:" + sum);
System.out.printf("평균:%.2f\n", show3(95,85,73)); // 역슬러시는 원 표시 하면 되고
// 만약 3f로 하면 소숫점 3자리까지 됨
System.out.println("결과:" + show4(95,85,73));
}
}
이것도 call by value
package methodex;
// TODO 중첩 메서드 : 메서드 안에서 또다른 메서드 호출
public class MethodEx4 {
public static int total(int a, int b, int c) {
return a+b+c;
}
public static double avg (int tot) {
return (double)tot/3;
}
public static String grade (double tot) { // 소숫점 값을 가져와서
switch ((int)tot/10) { // 인트로 바꿔준 뒤에 10으로 나누면
// 앞에가 92 -> 9 .. 89 -> 8 이렇게 됨
// 선생님은 char로 하심
case 10 :
return "A";
case 9 :
return "A";
case 8 :
return "B";
case 7 :
return "C";
case 6 :
return "D";
default :
return "F";
}
}
public static String result(String gr) {
if(gr.equals("F")) {
return "불합격";
}else {
return "합격";
}
}
public static void main(String[] args) {
int k = 95, e = 85, m = 73;
System.out.println("총점:" + total(k,e,m)+"점");
System.out.printf("평균:%.2f\n", avg(total(k,e,m)));
System.out.println("학점:"+ grade(avg(total(k,e,m))));
System.out.println("결과:" + result(grade(avg(total(k,e,m)))));
}
}
package methodex;
// TODO call by reference
public class MethodEx5 {
public static void view1(String str) {
System.out.println(str);
}
public static void view2(int[] arr) {
for(int n : arr) {
System.out.println(n);
}
// for(int i=0; i<arr.length; i++) {
// System.out.println(arr[i]);
// }
}
public static void main(String[] args) {
String str = "happy";
view1(str);
int[] num = {10, 20, 30, 40, 50};
view2(num);
}
}
자바 포이치 방식
public static void view2(int[] arr) {
for(int n : arr) {
System.out.println(n);
}
// for(int i=0; i<arr.length; i++) {
// System.out.println(arr[i]);
// }
아래 주석과 동일한 효과를 냄
Method/Heap/Stack 영역
yaboong.github.io/java/2018/05/26/java-memory-management/
자바 메모리 관리 - 스택 & 힙
개요 Java 에서 메모리 관리는 어떻게 이루어지는지 알아보기 위함. Stack 과 Heap 영역 각 역할에 대해 알아본다. 간단한 코드예제와 함께 실제 코드에서 어떻게 Stack 과 Heap 영역이 사용되는지 살펴
yaboong.github.io
Method * method : 객체 생성 이전/ 프로그램 종료까지 살아있음 메서드 코드 byte/ static /전역변수 |
main/ view1 |
Heap * heap : 메모리 할당 시 소멸 / 자동소멸 (자바에서는) 메모리 할당은 new로 선언했을 때 시작 소멸은 Garbage Collection에 의해 자동소멸 |
ob가 사라지면 heap영역으로 들어갔던 ob.view2()가 사라짐. |
Stack * stack : 블럭 안(중괄호 안)에서 메모리 할당하고/ 블럭종료시 메모리가 소멸 생명이 가장 짧음/ 지역변수/ 매개변수(인자) - 괄호 안에 들어가는 애들, 얘네도 바로 소멸 파라메타로 받는 애들 |
static이 없는 경우는 만들어지지 않았음. 그래서 ob라는 변수를 stack 영역에 만들어줌.
public void view2() {
System.out.println("non-static method");
}
public static void main(String[] args) {
...
MethodEx6 ob=new MethodEx6();
ob.view2(); // static 없는 void
필요할 때만 호출하기 위해 (메모리를 효율적으로 관리하기 위해서)
static : 컴파일할 때, 객체가 생성되기 이전에 / 자기 클래스 안에서는 생략할 수 있지만
다른 클래스의 경우는
댓글