Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pointers?

 
Josh Tambini
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does java has pointers like in C\C++?
i know it has a GC but still...can i use pointers in java?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not only can you use pointers, you can't not use pointers. When you say

Car car;

you have created a pointer that points to a Car object. When you then say

car=new Car();

you are telling the program what car points to. A car object is created somewhere off in ObjectLand, and the pointer car is set to point to it. Thus, when you say,

Car myCar=car;

the pointers are set to equal. There is ONLY one car, but both car and myCar point to it.

Thus, if I say,

myCar.breakForNoReason();

the car pointed to by myCar will break for no reason. Thus, car will also be broken, becuase the car pointed to is broken.

However, if you at some point say

myCar=new Car();

myCar is set to point to a brand new car, different from the one car points to. Then you can break myCar, and car will be uneffected,


dig?
[ December 12, 2004: Message edited by: Nick George ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to what Nick said:

The important difference between Java pointers and C/C++ pointers is that Java pointers are opaque. They're not interchangeable with integers, as C pointers are generally assumed to be.

Technically, C/C++ pointers are opaque, too, but most people code as if they represent an integer address. And of course whether they're supposed to be opaque or not, C/C++ explicitly allows you to add/subtract pointers and offsets.

But you can only do two three things to a Java pointer: assign to it; compare them for equality; and dereference them. That's it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic