-1

While creating a new object in Java, does it give me a memory location, or does it give me a pointer which holds the address of a memory location.

In C, I would do

typedef struct node
{
 int data;
 struct node* left;
 struct node* right; 
}Node;

And to get a new Node, I would do

Node* node = malloc(sizeof(Node))

And to access the internal members,

I do node->data, node->left and node->right

To get a new Node, I could also do Node node; and access the members as

node.data. node.left and node.right

In Java, I just do

class Node
{
    int data;
    Node left;
    Node right;

    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}

And to create a new Node, I do

Node node = new Node();

Is node a pointer which holds the address of the actual memory allocated, or it THE actual memory allocated. I'm confused because I just have to do

node.data, node.left and node.right

But don't have an understanding of what actually happens here.

tubby
  • 2,074
  • 3
  • 33
  • 55

3 Answers3

0

In Java, the value of every Object is a reference. See also, JLS-4.3. Reference Types and Values which says (in part),

There are four kinds of reference types: class types (§8), interface types (§9), type variables (§4.4), and array types (§10).

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Java has references, but not pointers. Here are some of the differences between references in Java and pointers in C++:

  1. References store an address. That address is the address in memory of the object. So, when a class is declared like so: "PersonClass y = new PersonClass();", the "y" variable actually stores an address in memory. If you were to look at that address in memory you would see the details of the PersonClass object. Pointers in C++, however, point directly to the object.

  2. You can not perform arithmetic operations on references. So, adding 1 to a pointer is not possible, but is possible in C++.

http://www.programmerinterview.com/index.php/java-questions/does-java-have-pointers/

Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18
0
Node node = new Node();

This constructs and allocates memory for a new Node object, returns a reference to this object and assigns this reference to the variable node. It is quite similar to pointers in C. You can have multiple references to the same object without copying.

The major difference with C, is that the JVM will keep track of how many valid references (variables like node) exist. When the reference count reaches zero it will delete the object (garbage collection) automatically and asynchronously.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82