컴공댕이 공부일지

[Java 공부기록 ] 첫 번째 : 반복문, 메소드, 오버로딩, Call by value) 본문

기록/이론 공부 정리

[Java 공부기록 ] 첫 번째 : 반복문, 메소드, 오버로딩, Call by value)

은솜솜솜 2023. 3. 10. 00:32
728x90

반복문, 메소드, 오버로딩, Call by value

 

EC.crew 1주차.

구름 에듀로 Java 기초 문법을 공부중이다.

자료형 공부하면서 필기한 오버플로, 언더플로

 

확실히 c를 지난 학기 내내 공부했었어서 java 기초 문법 공부는 수월하다.

 

 

 

 

 

* 반복문

모든 반복문은 초기식 / 조건식 / 증감식의 구조

 

break와 continue는  조건문과 함께 쓰인다!

 

continue 활용 예제 (고의로 생략하기)

public class Main {
	
	public static void main(String[] args) {
		 
		for(int i=0; i<5; i++) {
			if(i==3) { //3이 나오면 아래 코드는 생략하고 바로 다음 반복문 진행.
				continue;
			}
			System.out.println(i);
			
		}
		
	}
}

>>> 0

1

2

4

 

 

do while 활용 예제

public class Main {
	
	public static void main(String[] args) {
		int a=0;
		
		do {
			System.out.println(a++);
		} while(a<3);
		
	}
}

>>> 0

1

2

 

 

break 활용 예제

public class Main {
	
	public static void main(String[] args) {
		int a=0;
		
		while(true) {
			System.out.println(a++);
			
			if(a==3) {
				break;
			}
		}
		
	}
}

>>> 0

1

2

 

do-while과 break를 각각 활용해 똑같은 예제 구현해보았다.

 

 

 

 

 

 

* 메소드

메소드의 기초 개념과 구조

 

 

 

메소드 사용해보기

public class Main {
	
	static int plus(int a, int b) {
		return a+b;
	}
	
	public static void main(String[] args) {
		
		System.out.println("3 + 7 = "+plus(3,7));
		//main 메소드에서 plus 메소드를 콜한다.
		
	}
}

>>> 3 + 7 = 10

 

 

 

**오버로딩 

메소드 사용 기법 중 하나.

같은 이름의 메소드를 여러 번 정의하는 것! 

매개변수의 개수나 타입을 다르게해서 비슷한 동작을 하는 메소드를 한 이름으로 묶는거지~

 

 

메소드 오버로딩 기법 활용

public class Main {
	
	static int plus(int a, int b) {
		return a+b;
	}
	
	static int plus(int a, int b, int c) {
		return a+b+c;
	}
	
	static double plus(double a, double b) {
		return a+b;
	}
	
	public static void main(String[] args) {
		
		System.out.println("3 + 7 = "+plus(3,7));
		System.out.println("1 + 5 + 2 = "+plus(1,5,2));
		System.out.println("3.95 + 2.31 = "+plus(3.95,2.31));
		//다 같은 더하기 연산을 하는 메소드들. 오버로딩 기법 활용.
	}
}

>>> 3 + 7 = 10
1 + 5 + 2 = 8
3.95 + 2.31 = 6.26

 

 

 

**심화: Call by Value

서로 다른 메소드에서 선언된 변수들이 동일한 변수명을 가지더라도 서로 영향을 끼치지 않는 개념

 

call by value 예제

public class Main {
	
	static int plus(int a, int b, int c) {
		c= a*b;
		return a+b;
	}
	
	
	
	public static void main(String[] args) {
		
		int a=1;
		int b=2;
		int c=3;
		int result=0;
		
		result = plus(a,7,c);
		
		System.out.printf("%d %d %d %d", result, a, b, c);
		//main 메소드의 값엔 변화가 없음.
	}
}

메소드 오버로딩 기법 활용

>>> 8 1 2 3

 

call by value

 

728x90
Comments