File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Pointers? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pointers?" Watch "Pointers?" New topic
Author

Pointers?

Josh Tambini
Greenhorn

Joined: Nov 30, 2004
Posts: 24
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

Joined: Apr 04, 2004
Posts: 815
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 ]

I've heard it takes forever to grow a woman from the ground
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
jQuery in Action, 2nd edition
 
subject: Pointers?