C Pointer vs Java Reference Variables vs Other Languages Comparison

Asked 1 years ago, Updated 1 years ago, 93 views

Hi, how are you?

I am a student who forgot all the C and C++ I learned at school in the military and is currently studying Java and C# as an intern part-time job and hobby.

Currently, I am taking an introductory Java lecture at Programmers from the beginning, and I am asking you this question because I was curious while studying the reference type.

In Java, we learned that everything except basic variables is a reference variable. Class, array, etc.

You understand that the concept of a reference variable refers to a value in memory: an instance.

I vaguely remember that C's pointer was a similar concept, but as I looked it up, I saw a lot of articles saying that they don't use a pointer in Java or other languages.

We would like to know the similarities and differences between the pointer in C and the reference variable in Java. In addition, I would appreciate it if you could tell me what methods are used in Other languages (C++, C#, JavaScript, Python, Ruby, etc.).

c pointer java reference-variable

2022-09-21 19:36

1 Answers

If there is no pointer in Java, it is misleading.

To be exact, Memory cannot be handled directly is correct.

For example, c/c++ can be:

//c/c++
int a = 3;
memory address of int *p = &a; //a variable

For 32-bit OS, p is not an integer value, but a 4-byte memory address, such as 0x12abcdef.

c/c++ can also replace the value of p with any memory address, such as 0xaaaaaaaaaa.

If the developer accidentally changes the address value like that, an error will occur.

However, Java does not have direct access to memory. It's not directly possible, but if you create it with the new keyword, of course, it accesses the memory bungee internally.

//java
int a[] = new int[5];    

You should think that a is a memory address. The actual int 5 spaces are assigned linearly (side by side) to heap and their starting address is stored in a.

The big difference between c and Java is that c can handle memory addresses at will, whereas Java can never handle memory addresses directly. In other words, Java chose safety instead of sacrificing flexibility and some performance.

In other words, c handles the memory bungee directly, which can cause something like segment fault, but Java can never cause segment fault.

A good way to understand low-level features such as pointers is to study assemblies, even if they are difficult.(There's a lot to gain from studying assemblies.)


2022-09-21 19:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.