
โป JAVA์ ์ธ์ ์ ๋ฌ
- ์๋ฐ์์ ์ง์ํ๋ ํ์ ์๋ primitive type๊ณผ reference type์ด ์๋ค.
- primitive type : byte, char, short, int, long, float, double, boolean ๋ฑ๊ณผ ๊ฐ์ ์๋ฐ ๊ธฐ๋ณธ ํ์
- reference type : java.lang.object๋ฅผ ์์๋ฐ๋ ๋ชจ๋ ๊ฐ์ฒด
1. primitive type์ด ์ธ์๋ก ์ ๋ฌ๋๋ ๊ฒฝ์ฐ
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 10;
System.out.println("a = "+a);
add(a);
System.out.println("a = "+a);
}
static void add(int x) { // a์ ๊ฐ์ 1์ฆ๊ฐ ์์ผ์ฃผ๋ ํจ์
x++;
}
}
a = 10 a = 10
๊ฐ์ด ๋ฐ๋์ง ์๋ ๊ฒ์ ๋ณด์ Call By Value์์ ์ ์ ์๋ค.
2. ๊ฐ์ฒด ๋ ํผ๋ฐ์ค๊ฐ ์ธ์๋ก ์ ๋ฌ๋๋ ๊ฒฝ์ฐ
class Point{
int x;
Point(int x){
this.x = x;
}
}
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point p = new Point(10);
System.out.println("a = "+p.x);
add(p);
System.out.println("a = "+p.x);
}
static void add(Point a) { // a.x ๊ฐ์ 1 ์ฆ๊ฐ ์์ผ์ฃผ๋ ํจ์
a.x++;
}
}
a = 10 a = 11
๊ฐ์ด ๋ฐ๋๋ ๊ฒ์ ๋ณด์ Call By Reference์์ ์ ์ ์๋ค.
3. ๋ฐฐ์ด์ด ์ธ์๋ก ์ ๋ฌ๋๋ ๊ฒฝ์ฐ
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {10, 20};
System.out.println("x = "+a[0]+", y = "+a[1]);
swap(a);
System.out.println("x = "+a[0]+", y = "+a[1]);
}
static void swap(int x[]) { // x[0]์ x[y] ๊ฐ์ ๊ตํํ๋ ํจ์
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}
}
x = 10, y = 20 x = 20, y = 10
๊ฐ์ด ๋ฐ๋๋ ๊ฒ์ ๋ณด์ Call By Reference์์ ์ ์ ์๋ค.
[์ ๋ฆฌ] primitive type์ Call By Value, reference type์ Call By Value
'๐ป > JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] sortํจ์, ๋ฐฐ์ด ์ ๋ ฌ(์ค๋ฆ์ฐจ์, ๋ด๋ฆผ์ฐจ์) (0) | 2024.10.14 |
---|---|
[JAVA] String ๋น๊ตํ๊ธฐ (5) | 2024.09.30 |
[JAVA] ์๋ฐ Intํ Charํ ๋ณํ (0) | 2024.09.23 |
[JAVA] ์ ์ถ๋ ฅ(I/O)- ์คํธ๋ฆผ(Stream), ๋ฒํผ(Buffer), File์ ์ถ๋ ฅ์คํธ๋ฆผ ์ ๋ฆฌ (1) | 2024.09.07 |
[JAVA] ์๋ฐ ์์ธ์ฒ๋ฆฌ(Exception)- try catch๋ฌธ, throw, throws (12) | 2024.09.04 |