29

I have looked on google for answers but I am not satisfied.

My Logic:

Java uses memory locations, it's just behind the scenes where you can't see or access it (to my knowledge, probably there are ways of accessing them that I don't know).

My Confusion / Question :

What is the purpose of not having pointers in a programming language like Java, designed specifically for the internet to be used on any system, vs a programming language like c++, which does use pointers?

Edit


Many of you are saying "To keep it simple". If this is the case, then why does a popular programming language, like c++, use pointers anyway?

Community
  • 1
  • 1
Gabriel
  • 3,039
  • 6
  • 34
  • 44
  • 15
    The question should be: why doesn't have java 'pass by value' for objects – Thirler Nov 10 '11 at 14:00
  • @Thirler the question is still the same concept though – Gabriel Nov 10 '11 at 14:03
  • The "everything is a pointer, even if it doesn't look like one" decision dates back to Oak. That predecessor of Java was designed for embedded systems, not the Internet. – MSalters Nov 10 '11 at 14:03
  • @MSalters I thought that Oak was just java, but then renamed because of copyright reasons – Gabriel Nov 10 '11 at 14:05
  • @Gabe: There were some actual changes from Oak to Java - easy, back then, because it wasn't widely used yet. But pointers didn't change. – MSalters Nov 10 '11 at 14:07
  • 2
    @Thirler: Everything in Java is ["passed by value"](http://javadude.com/articles/passbyvalue.htm), though :-) – Kerrek SB Nov 10 '11 at 14:11
  • 1
    "If this is the case, then why does a popular programming language, like c++, use pointers anyway?" - (1) because C++ did not have as its design goal to "keep it simple", and (2) because C++ always had pointers, and removing them would break existing code – jalf Nov 10 '11 at 14:15
  • @jalf: I'd say that C++ *needs* pointers in order to implement any of its memory allocation features. – Kerrek SB Nov 10 '11 at 14:17
  • C++ needs pointers for a lot of reasons :) – jalf Nov 10 '11 at 14:20
  • Why then not to ask why all languages aren't like C/C++? Why is there Lisp or Haskell or Forth? What is the purpose of OP's question? – Victor Sorokin Nov 10 '11 at 14:20
  • Because the memory manipulation is an extra concern while writing an application that is not actually related to the application's business logic. By taking it away and letting GC handle it, Java allows a programmer to focus purely on the application/business logic. – Bhesh Gurung Nov 10 '11 at 14:58
  • Java doesn't have pointer concept but actually its 'reference' concept is the same as C++ pointer. For the sake of simpleness, address-of and dereference are invoked implicitly. – ExpExc Nov 10 '11 at 15:08
  • One related thing you might want to think about is the standard library that comes with the language. In C++ almost the entire library is written in the language itself (I think only some type traits, initializer lists and some numeric limits require compiler support). How is this in Java? Can you implement Java's `String` class in Java itself? (I don't know enough about it.) – Kerrek SB Nov 10 '11 at 15:43
  • I think C++ is there for speed, because java do some checking and garbage collecting, that may slow the performance a bit while C++ doesn't have to do these things so code run faster. – niceman Jan 06 '15 at 21:37

9 Answers9

67

The simple answer is that it is a design decision. The slightly longer answer is that pointers in C++ are only necessary for memory manipulation, which is not a concept that applies to Java (see below).

Java envisions a fairly systematic, object-oriented programming model, and all class-based types are essentially always handled through a pointer, and so this fact isn't exposed to the user at all.

Raw pointers in C++ aren't very necessary in high-quality, systematic and idiomatic programming, either. What raw pointers do allow you to do (namely pointer arithmetic) is generally considered "unsafe", and so it is simply left out of Java altogether.

Note by the way that many things people attempt to do with pointers in C and C++ is actually undefined behaviour. Using pointers correctly leaves you with a fairly restricted set of options, most of which can be done better in idiomatic C++.

About the only real use for pointers is direct memory manipulation. Since Java doesn't want you to do that (and in fact its garbage-collected memory management would actively interfere with and be broken by manual memory manipulation), there's no need for explicit pointers.

After your update: The last paragraph is (in my opinion) the most striking explanation: In C++ you need to be able to write your own memory managing code (cf. "allocators"). And memory has to be handled via pointers. So my strict answer is that you need pointers in C++ when you're implementing the memory management, and never otherwise.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
32

Internally a reference to an object is implemented as a pointer. There is no pointer arithmetic though...

C++ has pointers because it is built as a superset of C, which does have pointers. C has pointers because it was designed in the 60's. At that time computers had very little memory and pointers allowed the implementation of Strings, arrays and parameter passing.

This is an extract from the White Paper The Java Language Environment:

2.2.9 No More Pointers

Most studies agree that pointers are one of the primary features that enable programmers to inject bugs into their code. Given that structures are gone, and arrays and strings are objects, the need for pointers to these constructs goes away. Thus, Java has no pointer data types. Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects. Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices. The Java run-time system checks all array indexing to ensure indices are within the bounds of the array.

You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.

bluish
  • 26,356
  • 27
  • 122
  • 180
Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47
  • internally a reference MAY BE implemented as a pointer. Whether that really happens is dependent on the JVM implementation, it's not dictated by the JVM or language specifications. – jwenting Nov 10 '11 at 14:25
  • 6
    "C++ has pointers because it is built as a superset of C, which does have pointers. C has pointers because it was designed in the 60's." No. C/C++ have pointers because they are useful. C/C++ is still used in many situations where java would utterly fail, which is why they are still now, extremely popular languages. – jbat100 Nov 10 '11 at 14:27
  • @jwenting That's correct! I reckon it is the case in most implementations. – Costis Aivalis Nov 10 '11 at 14:28
  • @jbat100 Do not forget that C++ was originally called C with Classes. And the requirement was backwards compatibility with C. Java is the evolution of C++. – Costis Aivalis Nov 10 '11 at 14:30
  • 1
    @CostisAivalis You probably didn't see the reaction to one of the questionner's recent posts "Why doesn't Java replace C++". It's not an "evolution", it's a different language with different applications. – jbat100 Nov 10 '11 at 14:35
  • 3
    Why hasn't C++ replaced C? Isn't C++ evolution of C? Languages are very persistant... – Costis Aivalis Nov 10 '11 at 14:38
  • @CostisAivalis with good reason. Many languages died out, some didn't, that's because they are useful. If you only want to code in java that's fine. – jbat100 Nov 10 '11 at 14:45
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4883/discussion-between-costis-aivalis-and-jbat100) – Costis Aivalis Nov 10 '11 at 14:49
  • 1
    Also, JVM are coded in C/C++ (http://stackoverflow.com/questions/1220914/in-which-language-are-the-java-compiler-jvm-and-java-written). So C/C++ dying out should (if it were true) be of some concern to you. – jbat100 Nov 10 '11 at 14:51
17

Java does have pointers. In fact, everything in Java is pointers (called references).

Exceptions: int, boolean, char, etc.

As everything is pointers, no need for an asterisk to make a difference.

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • Pointers as in accessing memory locations, not changing data but actually viewing the memory location of an integer or something – Gabriel Nov 10 '11 at 14:01
  • 8
    There are some differences between pointers in C++ and references in Java. Pointers allow some arithmetic and references do not. – DerMike Nov 10 '11 at 14:02
  • 3
    C and C++ don't allow you to access arbitrary memory locations either. The difference is that in C++ it's undefined behavior, and may crash your process or do anything else, whereas in Java, the compiler prevents it. – jalf Nov 10 '11 at 14:03
  • 3
    @Gabe: They do. Did you perhaps mean, "why doesn't java have pointer _arithmetic_" ? – MSalters Nov 10 '11 at 14:04
  • 2
    @jalf: undefined behavior is just standardese for "we're not specifying this, but it might do something interesting". C was designed as a programming language for operating systems and those regularly use pointers to arbitrary locations, regardless of what the standard tells us is allowed. – Fred Foo Nov 10 '11 at 14:12
  • 1
    @larsmans: yes, and in doing so, you move beyond the C language, outside of that language's guarantees. The C language does not allow you to muck around with arbitrary memory. If you do so, your program is no longer well-defined by the C standard, *even if it works in practice* – jalf Nov 10 '11 at 14:19
  • @jalf: the standard isn't all there is to C. Otherwise, you'd have to say that the implementation language of, say, the Linux kernel is not C, while clearly, it is (even if it's a non-standard dialect). – Fred Foo Nov 10 '11 at 14:23
  • 1
    a reference is not a pointer... – jwenting Nov 10 '11 at 14:24
  • 1
    Strictly speaking, the Linux kernel relies on behavior that is, according to the C standard, undefined. That means that the behavior of the *entire* kernel is strictly speaking undefined. It is not a malformed C program, but it is an undefined one. You can call it "C" or "not C", whichever makes you happy. But that won't change that if you play strictly by the book, then all the C standard has to say about the Linux kernel is that (1) it is well-formed (or so I assume; it might rely on nonstandard syntax), an (2) its behavior is undefined. – jalf Nov 10 '11 at 14:28
  • 2
    And yes, the standard certainly is all there is to C. The C language is what it is regardless of what the Linux kernel does. What **else** would you say defines what C is, if not the standard? But we usually say that the Linux kernel is written in C because it's a good enough approximation to be useful – jalf Nov 10 '11 at 14:29
  • you can't have a reference to a reference. you would have to create some kind of intermediate object to hold a reference, so that's at least one way in which a reference is not a pointer. – symbiont May 29 '15 at 12:44
7

First, the obvious problem is that Java doesn't guarantee that an object stays at the same address throughout its lifetime.

Efficient garbage collectors rely on being able to move objects around, and doing so would invalidate any pointers that (previously) pointed to the object.

Second, Java very nearly does have pointers. C/C++ pointers aren't quite what you think they are.

A C++ pointer does not allow you to just point to an arbitrary memory address and read the contents of it. It does not allow you to increment a pointer past the end of an array.

The language just has no way to detect if you do those things, and no way to catch the error when you do it. But that doesn't mean it's allowed. It's undefined behavior, and in short, could do anything.

Java very nearly does have pointers. Here's a nearly complete list of what you can legally do with a pointer in C++:

  • dereference it to get the pointed-to object
  • reseat it so it points to a different object
  • make it a null pointer
  • if it points into an array, you may perform pointer arithmetics, adding to, or subtracting from the pointer, as long as the result still points into the same array, or taking the difference between two pointers if they both point into the same array.

The last point is really the only one that isn't possible in Java. And it is so mcuh more restricted than people usually think. It doesn't give you a carte blanche to create pointers to any old address. It doesn't let you "access memory directly".

So Java doesn't have pointers because:

  • it would be very challenging to implement correctly into a GC'ed language,
  • it would either require some degree of runtime checking (to guarantee that invalid memory accesses are detected and handled safely), or it would make Java an unsafe language, one where the behavior is not 100% specified,
  • there's just not much point, because pointers allow very little additional functionality, beyond what Java references have
jalf
  • 243,077
  • 51
  • 345
  • 550
  • "A C++ pointer does not allow you to..." Unfortunately "allow" is an antonym of "prevent" as well as an antonym of "forbid". C++ forbids you from attempting those things, but does not prevent them as part of the potential undefined behavior when you break the rules. So it allows them in one sense but not the other. – Steve Jessop Nov 10 '11 at 14:15
  • @Steve: I disagree. Surely "disallow" is a more correct antonym. "Prevent" means that something is disallowed, and that this is enforced. Neither "allow" or "disallow" say anything about whether it is enforced. – jalf Nov 10 '11 at 14:17
  • You're disagreeing with the dictionary, not just me, I'm not going to try to persuade you to believe it. – Steve Jessop Nov 10 '11 at 14:21
  • 1
    Fine, "prevent" can be the antonym" if it makes you happy. My point is that logically, the inverse of "allow" is "disallow". "Prevent" means something stronger. "Disallow" means that you are not allowed to do something. "Prevent" means that it is made *impossible* for you to do something. And surely, the opposite of "allowed" is "not allowed"? – jalf Nov 10 '11 at 14:24
  • Making a pointer null is same as reseating. – tripulse Sep 30 '20 at 15:15
4

For the same reason java doesn't have unsigned types. The designers of the language decided not to include them in order to keep the language "simpler".

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
3

Because Java is meant to be a simple, safe and relatively foolproof programming language. Pointers are a sharp tool that the Java designers decided not to put in the hands of programmers.

@oltarus is right that, in a sense, Java's references are pointers, but there's one major difference: you can't do arithmetic on them, while you can do arithmetic on pointers. Pointer arithmetic is at once a major source of bugs with pointers, since you make them point at invalid locations in memory (for example by forgetting to initialize them, or through off-by-one errors).

Update: C++ has pointers because they are necessary for the kind of low-level systems programming that C++ was designed to support. C++ was designed as a "better C" and a replacement for that language, which means that it has all the facilities necessary to implement things like operating systems and device drivers. Doing that in a language without pointers is practically impossible.

Both C and C++ follow the philosophy that you get almost full access to the hardware if you ask for it, so you can do practically anything you want, but the language also won't stop you from doing stupid things. Java, OTOH, restricts your access to the machine by running your program in its VM sandbox.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
3

The main reason is verifiability. The Java bytecode is defined so that the loader can decide in finite time whether the program is safe to execute. Pointer arithmetic cannot be expressed in a way that allows this verification, hence it was removed from the language, and only assignment of references remains.

The same restriction applies to C++/CLI; if you use certain expressions on pointers, the compiler can no longer express the code using only bytecode from the "safe" set, and the component fails to load if checks are enabled.

The difference between CLI and Java bytecode is that Java does not have an "unsafe" instruction set, as it was specifically designed for untrusted code on the Internet.

Simon Richter
  • 28,572
  • 1
  • 42
  • 64
3

In Java all objects are allocated on the heap. So you always refer to them with "pointers" (hence dropping the notation) as opposed to C/C++ where objects are either statically or dynamically allocated.

bluish
  • 26,356
  • 27
  • 122
  • 180
jbat100
  • 16,757
  • 4
  • 45
  • 70
1

The main reason is because pointers are lead to many errors which very hard to identify. In Java way life of programmer is easier.

For Updated question: C++ with pointers has better performance than Java.

mishadoff
  • 10,719
  • 2
  • 33
  • 55
  • ... or harder, depending on what you want to do. – Fred Foo Nov 10 '11 at 14:06
  • yes. it simpler to support tons of code. – mishadoff Nov 10 '11 at 14:08
  • Pointers have nothing to do with C++ vs Java performance. If anything, pointers are a drawback, because they make aliasing analysis really really hard for the compiler, which prevents a lot of useful optimizations – jalf Nov 10 '11 at 14:13
  • I compare not aspect of pointers in performance but two languages. C++ has better performance than Java. Do you wanna argue? – mishadoff Nov 10 '11 at 14:15
  • Sure, I'd like to argue that it's irrelevant. Because the question was not whether C++ was faster than Java, but rather why Java does not have pointers and C++ does. What does C++'s performance have to do with the question? – jalf Nov 10 '11 at 14:31