
소스의 기능 설명 또는 특정 코드 부분을 컴파일에서 제외하고 싶을 때 사용
//한줄 주석
/*
여러
줄
주석
*/
개발자가 작성한 소스 중 컴파일 시 CPU가 실행하는 명령문으로 바뀌는 문장을 의미함.
;으로 종료해야 한다.int
mul =
32;
int time = 0; int sum = mul + time;
명령문을 선택적으로 실행하거나 반복을 제어하는 문장으로 이루어져있다.
if(condition){
...
}else{
...
}
swich(condition){
case condition:
...
break;
case nonCondition:
...
break;
default:
System.out.println("일치하는 값이 없음.");
}
while(condition){
...
}
while문과의 차이점은 일단 한 번 조건을 실행한 뒤 반복 여부를 결정한다.
do{ ... }while(condition);
for(initial; condition; inc){
...
}
// 초기식, 조건, 증감식
반복문을 도는 와중에 강제로 반복문을 종료시킨다.
int s = 0; for (int i = 0; i < 10; i++){ if (i == 5) break; s += i; }
// result : s = 0 + 1 + 2 + 3 + 4
#### continue
> 다음에 있는 실행문의 실행을 생략한다.
```java
int s = 0;
for (int i = 0; i < 10; i++){
if (i >= 5)
continue
s += i;
}
// result = 0 + 1 + 2 + 3 + 4
해당 문을 사용하면 다중 반복문에서도 한번에 원하는 반복문까지 반복을 종료할 수 있다.
public class Conditions {
public static void main (String[] args){
label1:
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
if (j == 2)
break label1;
int res = i*j;
System.out.printf("%d * %d = %d\n",i, j, res);
}
}
}
}
break label문과 같은 매커니즘으로 continue를 진행함
public class Conditions {
public static void main (String[] args){
label1:
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
if (j == 2)
continue label1;
int res = i*j;
System.out.printf("%d * %d = %d\n",i, j, res);
}
}
}
}
메모리에 연속적인 데이터 공간을 만들어 연속적인 데이터를 저장할 수 있도록 한다.
int [] num; // 선언 방법 1
int num[]; // 선언 방법 2
int num[] = {1, 2, 3}; // 선언과 동시에 초기화
num = new int[3]; // 생성 방법
num[0] = 1; // 초기화
int [][] arr;
arr = new int [10][10];
// 2d 배열 생성 방법
public class Conditions {
public static void main (String[] args){
int[] arr;
arr = new int[10];
for (int i = 0; i < arr.length; i++){
arr[i] = i*2;
}
int sum = 0;
for (int j = 0; j < arr.length; j++){
sum += arr[j];
}
System.out.println(sum);
}
}
❯ java ClassName arg1 arg2
public static void main(String[] args){
System.out.println(args[0]);
System.out.println(args[1]);
}
// OUTPUT
// arg0
// arg1
자주 사용하는 기능을 미리 만들어두고, 필요할 때마다 메서드명으로 호출하여 사용하는 개념
int methodName(int args1, int args2){
int localVar = args1 + args2;
return localVar;
}
함수라는 이름으로 다른 프로그래밍 언어에서 사용중이다.
public class Method{
public static void main(String[] args){
Method m = new Method();
int lv = m.methodName(1, 2);
}
}
인스턴스를 생성한 후 사용한다.
메서드 호출시 값이 복사되어 전달된다. (원본 ❌)
public class CallByValue{
public int increase(int n){
++n;
return n;
}
public static void main(String[] args){
int var1 = 100;
CallByValue val = new CallByValue();
int result = val.increase(var1);
System.out.println("var1 : "+var1+"result : "+result);
}
}
//RESULT
// var1:100 result:101
메서드의 매개변수 타입이 [[2. 자바의 기본 문법#참조형|참조형]]일때 사용된다. 원본이 그대로 바뀐다.
public class CallByRef{
public void increase(int[] n){
for (int i = 0; i < n.length; i++){
n[i]++;
}
}
public static void main(String[] args){
int[] ref1 = {100, 800, 1000};
CallByRef ref = new CallByRef();
ref.increase(ref1);
}
}
예외적으로 문자열을 전달하려면 참조형 데이터라도 값에 의한 호출을 해야한다. (단순히 call by value를 참조형이지만 적용했다 라고만 생각하면 될듯)