• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Pointers?

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic