포인터
C, C++ 프로그래밍 언어에서 포인터는 다른 변수의 주소를 보유하는 변수입니다.
예
#include <iostream>
using namespace std;
int main() {
//int variable
int i = 8;
//pointer variable
int * pI;
//assign the address of i to its pointer
pI = &i;
//print the number
cout<<i<<endl;
//print the address of the number
cout<<pI<<endl;
//print the value pointed by pointer
count<<*pI<<endl;
//change the value of variable using its pointer
*pI = 10;
//print the number
cout<<i<<endl;
} 출력
8 0x7fee1ae7bc94 8 10
참조
자바 프로그래밍 언어에서 참조는 개체를 참조하고 개체의 속성과 기능을 활용할 수 있는 변수입니다.
예
public class Tester {
public static void main(String[] args) {
Student student = new Student();
student.setName("Mahesh");
System.out.println(student.getName());
}
}
class Student {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} 출력
Mahesh
포인터와 참조의 차이점
다음은 C/C++ 포인터와 참조 간의 몇 가지 차이점입니다.
-
자바에는 포인터 연산이 없습니다. 포인터는 메모리 주소이고 포인터는 변수의 메모리 주소를 가리킵니다. C/C++에서는 포인터가 새 주소를 가리키도록 증가/감소할 수 있지만 Java에서는 참조에 대한 산술 연산이 허용되지 않습니다.
-
자바에서 포인터 조작 없음 참조는 내부적으로 포인터를 사용하지만 Java는 참조 변수를 사용하여 기본 포인터에 대한 조작을 허용하지 않습니다. Java를 보다 안전하고 강력하게 만듭니다. 참조는 개체를 참조하거나 null만 될 수 있습니다.
-
자바에서 포인터 캐스팅 없음 C/C++에서는 int*를 char*로 변환할 수 있지만 Java에서는 관련 객체만 변환할 수 있습니다. 동일한 계층의 개체입니다.