<p>Some people use the term "pointers" to describe Java references. References definitely do need to be described (though they should be called references rather than pointers). Fields, variables, and parameters of class type are often treated as though they hold instances, but they never actually do.</p>

<p>Reference-type variables can hold four different kinds of things:</p>

<ol>
<li><p>A reference to an object <em>that will never change</em> (often an immutable type like <code>String</code>), which is used to encapsulate the contents thereof.</p></li>
<li><p>A unshared reference to an object, which could be mutable, used to encapsulate the contents thereof.</p></li>
<li><p>A reference to an object that is "owned" by the entity holding the reference, but which may also identified by references held by other entitites that don't own it.</p></li>
<li><p>A reference to an object that is "owned" by some other entity.</p></li>
</ol>

<p>The Java language makes no distinction among these different categories of references, but one cannot reasonably expect to write code which is efficient and correct without knowing which category every reference belongs to.  In the first two situations, code may treat a reference-type variable as though it holds the object identified thereby, but a programmer must know which of those two situations applies.</p>

<p>If field <code>arr</code> of some object holds a reference to an <code>int[]</code> containing {1,2,3}, and one wants <code>arr</code> to hold a reference to an array holding {1,2,4}, there are two ways of accomplishing that: change the third item of the <code>int[]</code>, or create a new <code>int[]</code> holding {1,2,4} and store a reference to that in <code>arr</code>.  Either approach may be correct, but if one doesn't know into which category <code>arr</code> belongs, one won't know which approach to use.</p>

CC BY-SA 4.0
2020-11-12T06:42:18.953Z
Putting words in quotes does not make clear the idiosyncratic meaning you intend but do not give.
philipxy
CC BY-SA 4.0
2020-11-12T15:45:30.867Z
@philipxy: Are you talking about "owned"?  The idea there is that in cases where references to a mutable object are shared, only one entity--the "owner"--will hold a reference that it would be expected to use in any way it sees fit, and all other entities that hold references would be expected to use them only to perform actions on behalf of that "owner".  For example, if a GUI object that displays a list subscribes to an update event from an "observable list" object, that list object will need to hold a reference to a delegate which will in turn hold a reference to the GUI object.
supercat
CC BY-SA 4.0
2020-11-12T15:48:36.723Z
The sole purpose of the delegate will be to invoke a method which was designated by the GUI object, on the GUI object, when it's necessary to notify it that the contents of the list have changed.  Calling that method will likely modify the GUI object, but the GUI object wouldn't be "owned" by the observable list object but instead by the GUI window/form object in which it appears.
supercat
CC BY-SA 4.0
2020-11-12T16:29:41.387Z
@philipxy: I didn't want to fall into the rabbit hole of trying to describe why entities might hold references to objects whose state they don't regard as their own, perhaps you might offer some idea how to convey that concept in more detail than just the term "own", but without getting bogged down?
supercat
CC BY-SA 3.0
2017-07-19T14:47:32.857Z
2017-07-19T16:41:11.977Z
2017-07-19T16:41:11.977Z
supercat
<p>Learning pointers is not vital for learning Java, although references become very important once arrays or class instances are introduced given the importance between a reference type or a native type makes when cloning instances (shallow vs. deep copying), passing parameters into methods, or discussions regarding instance hash writing (needed for some of the ordered containers).</p>

CC BY-SA 3.0
2017-07-16T19:02:51.407Z
Hi FluxIX! Welcome to [cseducators.se]! I hope to see you around, asking and answering.
thesecretmaster
CC BY-SA 3.0
2017-07-16T18:32:43.807Z
2017-07-16T18:32:43.807Z
FluxIX
<p>You need to teach about the <strong><em>references</em></strong>, regardless how you call them.</p>

<p>Even if you do not see the reference as a pointer, you absolutely need to explain what the reference is, as otherwise no student will understand the things going on behind </p>

<pre><code>a.x = 1;
b = a;
b.x = 2;
a.x == // WTF?
</code></pre>

<p>or, with arrays:</p>

<pre><code>a[0] = 1;
b = a;
b[0] = 2;
a[0] == // WTF?
</code></pre>

<p>And it is really not the best idea just to keep secret from the students how the values would change. These cases are frequent in Java code, they are far from the corner cases nobody needs to care about.</p>

<p>And the reference is easiest to explain in terms "it is the address in computer memory". Maybe a reference is also something deeply fundamentally else but I still need to see the easier understandable explanation and, well ... it just is, unless we start talking abut the physical, virtual address, address translation, handles that need to be resolved into addresses and other advanced concepts.</p>

CC BY-SA 3.0
2017-07-20T10:49:29.107Z
Welcome to [CSEducators.se]! Wow! This is a wonderful answer. I hope we'll be hearing more from you.
ItamarG3
CC BY-SA 3.0
2017-07-20T10:01:40.160Z
2017-07-20T10:08:55.767Z
2017-07-20T10:08:55.767Z
h22
<p>The following sentence from JLS Section 4.3.1</p>
<blockquote>
<p>&quot;The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object&quot;.</p>
</blockquote>
<p>is sometimes exhibited as an &quot;proof&quot; that Java actually has pointers.</p>
<p>Putting it in context:</p>
<ul>
<li>Language specification documents are not the kind of material beginners are expected to learn programming from ;</li>
<li>at the time (90's), &quot;serious programmers&quot; (the intended readers of language specifications) were probably familiar with mainstream programming languages of the time.</li>
</ul>
<p>Before Java, most programming languages (C, C++, FORTRAN, Cobol, ...- counter-examples are SmallTalk and Lisp) shared the notion of a variable as a name for a memory chunk <strong>containing</strong> the binary representation of some information.</p>
<p>Java has some obvious similarities (syntax) with C++, but drastically differs on that notion : a variable refers to <strong>a value</strong> (of primitive type) or an object. An object is not <em>contained</em> in a variable.</p>
<p>So assigning an object in Java doesn't involve the duplication of that object.</p>
<p>It's a point to be stressed (heavily) when explaining Java to confused C++ programmers. And a simple way to do it is to say Java variables contain references, which are like <strong>C++</strong> pointers containing addresses of objects (and are magically de-referenced without a star).</p>
<p>But it's only a way to illustrate concepts of Java with a metaphor, borrowing from a different world. It only helps if you know C++ beforehand. Having to teach pointers first makes the thing more complicated.</p>
<p>The basic explanation is</p>
<ul>
<li>objects exist somewhere in the memory space,</li>
<li>references indicate where they are,</li>
</ul>
<hr />
<p>Actually pointers are not a &quot;very hard&quot; subject (addresses as first class data). The beginner's difficulties come from the algorithmic side of linked data structures.</p>

CC BY-SA 4.0
2021-02-03T14:08:15.567Z
2021-02-05T20:05:51.103Z
2021-02-05T20:05:51.103Z
Michel Billaud
<p>I think, no and yes. Students should know that somewhere in Memory lies an object with the values involved. They don't need to know that an internal representation is likely a memory address. Concepts that are alien to Java such as offsets and such can be ignored.</p>

CC BY-SA 3.0
2017-07-18T17:23:01.550Z
Also, welcome to [cseducators.se]!
Ben I.
CC BY-SA 3.0
2017-07-18T16:24:45.270Z
2017-07-18T16:24:45.270Z
georgejo
<p>This is too long to be a comment:</p>
<p>Java is a pass by value language.  You must understand that what variables store in Java.  Primitives store their values directly. Object types store heap memory addresses.  In either case, when you pass that an argument to a function that argument is evaluated, and then it is assigned to the function's parameter and it behaves like a local variable.</p>
<p>So, if you are passing a variable to a function the evaluation process causes a copy of the bit pattern it is storing to be made.  In the case of an object, that's a copy of the memory address.  This is why I carefully explain the idea of memory address to my beginning programming students.  Python operates similarly, but it has no primitive types.  All Python data are objects stored on the heap.</p>

CC BY-SA 4.0
2021-02-21T21:01:51.763Z
2021-02-21T21:01:51.763Z
ncmathsadist
<p>Learning about references is important, but I don't feel that learning about pointers is that important for <strong>beginning</strong> Java students. Certainly intermediate students will need to understand them.</p>

<p>When I started learning about pointers, I had a hard time grasping them at all until I learned assembly language. Once I learned assembly (for any processor), pointers made sense. It helped that I learned PDP-11 assembly at about the same time I learned C.  Since C is essentially structured PDP-11 assembly language, I was easily able to see the relationship between the pointer structures and the compiled code.</p>

<p>Java hides the concept of a pointer sufficiently deeply that I would be hard pressed to explain it with java. I can explain java structures in terms of pointers, but have difficulty expressing it the other way around. For teaching pointers and pointer concepts, I would probably use C (yep - plain old C, without the ++) and the x86 assembly language as a starting point.</p>

<p>After that, it's easy to explain that the JVM is built in C, and java object references are implemented as pointers.</p>

CC BY-SA 3.0
2017-07-17T15:22:26.540Z
+1 I agree that pointers are sufficiently abstracted in reference based languages like Java, C#, and many others that they do not need to be covered in an introductory programming course.  However, one potential pitfall many institutions fall into is the next instructor (for intermediate courses) tends to assume they have already been covered in earlier courses.
Lee Hiles
CC BY-SA 3.0
2017-07-18T00:36:14.020Z
Irrespective of the importance, I can't say I shared your experience. Even having never programmed in assembly or seriously in C/C++ (just a couple college projects well after I had learned Java used pointers), I had no trouble grasping the idea that Java has your object's data in a separate block (over on the heap) and that the variable I'm using at the moment actually just corresponds to an address pointing to that block. Granted, that's a bit simplistic, but I didn't find the basic concept of pointers that hard, and even that limited understanding made Java's behavior more sensible.
jpmc26
CC BY-SA 3.0
2017-07-18T13:13:36.700Z
@LeeHiles C# also has pointers, so that's not quite as good an example. Not quite as raw as C's, but then again C's aren't quite as raw as assembly's. E.g. there's no null pointer in assembly, that's a C construct; a pointer in assembly isn't necessarily a single integer; two pointers can point to the same memory despite having different values (*and vice versa*); I've got more where those came from :P In contrast, I've seen plenty of programs in C or Pascal that avoided pointers almost entirely (not counting "indexing a statically allocated array" as "using pointers").
Luaan
CC BY-SA 3.0
2017-07-22T17:54:18.717Z
@jpm26 java was invented about 20 years after I learned about pointers. I came through BASIC that was still close enough to its Fortran roots to be recognizable as such (no scope, so no distinction between references and values),  into pascal and C. We have had different experiences for sure.
pojo-guy
CC BY-SA 3.0
2017-07-16T00:59:27.827Z
2017-07-16T01:31:24.033Z
2017-07-16T01:31:24.033Z
pojo-guy
<p>For a beginning course: <strong><em>no</em></strong>.</p>

<p>I have helped clarify behavior for fellow students who got lost by an instructor who explained things in terms of pointers. I have programmed in C, and most of my current programming is done in Rust; I understand pointers and what problems they are best suited to solve. But in Java, you don't have any access to pointers, so explaining pointers only serves to muddy the waters for a student trying to grep the <em>way a computer thinks</em>.</p>

<p>I take the position that a intro-level course should only cover programming, and the actual science of computer science should be postponed to at earliest 102. But my college also lacks a Software Engineering track, and I would argue most people pursuing a CS education actually want that instead of the science.</p>

<p>In any case, Java uses <em>pass by reference</em>. I know exactly what anyone who cares about terminology and grew up in C/++ is thinking as soon as I say that: Java is <em>pass reference by value</em>. But this is inconsistent with Java's own mental model.</p>

<p>Here's the mental model I have shared multiple times to great effect with students who failed to understand Java's Objects the first time:</p>

<p>A variable is a binding to a value. Thus, when you do <code>Animal c = new Cat();</code>, <code>c</code> is a binding to the constructed <code>Cat</code>. This binding is transparent, and when you use it, you are talking directly to the bound object.</p>

<p>However, in order to facilitate resource sharing, when you pass this object as a parameter to a method, a new binding is created. This binding is to the same object, but is a new binding, so assignment to the binding does not effect the old one (the <em>pass by value</em>).</p>

<p>But because these two bindings are bound to the same object, there is <em>only one object</em>. This means that mutating this object by using its fields or methods will have the effect that the object the original binding is bound to also changes, because they are the same object.</p>

<p>Note that nothing about this mental model breaks on primitives (or the quasi-primitive String), since primitives can only be changed by reassigning. A slightly higher-level course, or even later in the course once students <em>understand</em> the shared resource concept, can mention that primitives aren't bindings but rather just their value.</p>

<p>Once binding misdirection gets multiple layers deep (Objects containing Objects containing etc), it can be useful to talk about and diagram name bindings as a pointer to a value, but that's as far as I go. Stack/Heap doesn't need to be discussed in a Java class: the GC and no stack allocated objects mean that just "somewhere in memory" is all that really needs to be mentioned on object storage until you're at an advanced level where cache coherency or GC overload matters.</p>

<hr>

<p>Post Script:</p>

<p>I've called Java <em>pass by reference</em> here, which will (and has) riled up a bunch of people who want <em>pass by reference</em> to only mean what is expressed in C as <code>function(&amp;name)</code>, which Java is not doing. As such, it may be better to call it <em>pass by resource sharing</em>, <em>pass by resource binding</em>, or <em>pass by binding</em>. In C's definition, you are passing a <em>copy</em> of the <em>reference</em> by <em>value</em> (<code>function(&amp;*name)</code>). By my reading of Java, though, I argue that we are passing by the reference to the value, because the binding is not separate from the value. This is a terminology problem, and unfortunately, even in a field that relies on unambiguous interpretations, we do overload our terminology.</p>

CC BY-SA 3.0
2017-07-16T16:33:55.207Z
Really wonderful answer. *"But my college also lacks a Software Engineering track, and I would argue most people pursuing a CS education actually want that instead of the science."* is exactly right. Come by the [chat room](https://chat.stackexchange.com/rooms/59174/the-classroom) to say hi, and welcome to [cseducators.se]!
Ben I.
CC BY-SA 3.0
2017-07-17T17:06:20.427Z
I think using the phrase *Java uses pass by reference* is dangerous at best, especially when talking about an introductory class. Keep it high level, but if any students ask about the nitty-gritty, make sure they know that Java is pass by value, even for references.
Kevin Workman
CC BY-SA 3.0
2017-07-17T18:22:24.217Z
I never did grok pointers and constantly had trouble with them when working in languages like C++ (I never could remember if I needed to `*` the variable or `&` and on which *side* that operator needed to go, because seriously, would it have *killed* someone to make that syntax consistent?). I *hated* pointers. Object references in languages like Java and C#? So easy to understand and use effectively.
Draco18s no longer trusts SE
CC BY-SA 3.0
2017-07-17T18:28:17.590Z
@KevinWorkman As I said, it's a matter of definitions. When you have a Java binding, it _is_ the thing it's bound to; you don't have to `*` it to dereference the pointer. The way Java is implemented is by passing the pointer by value, but because the binding _is_ the bound value, you're passing the bound value by reference. C's pass-by-reference is a completely different thing to Java's, and it's a conflation of definitions. By C's definitions, Java is pass-reference-by-value, and I will never object to that, because it is correct. Just confusing if you don't know pointers inside out.
CAD97
CC BY-SA 3.0
2017-07-17T18:30:38.120Z
*"Just confusing if you don't know pointers inside out."* That's exactly my point. This is for an introductory class. The students do not know pointers inside out.
Kevin Workman
CC BY-SA 3.0
2017-07-17T22:58:24.240Z
Did you mean "grok" when you typed "grep"?  That's a funny typo.  :)
Wildcard
CC BY-SA 3.0
2017-07-18T00:22:20.457Z
This answer is misleading at best, and potentially dangerously wrong. Java most definitely does **not** have call-by-reference semantics. (Compare [this question on Stack Overflow](https://stackoverflow.com/questions/40480), and also the large amount of confusion in [this other Stack Overflow question](https://stackoverflow.com/questions/373419).) Too many people try to conflate "call-by-reference" with "reference types", so it's important to distinguish those concepts early, before a wrong mental model sets in.
Daniel Pryden
CC BY-SA 3.0
2017-07-18T00:27:18.260Z
@DanielPryden Did you read that paragraph? I've read that answer. I acknowledge immediately that Java is _pass reference by value_. The difference is that I (and Java, by my reading) consider a binding _to be indistinguishable from_ the bound value, so passing a reference is passing a reference to that bound value, not the binding itself, thus, passing the reference by value. It's not comparable to C/++ where a pointer/reference and the value itself are different things. EDIT: your grace period edit makes clearer what you mean. I don't disagree.
CAD97
CC BY-SA 3.0
2017-07-18T00:30:32.290Z
@CAD97: I've edited my comment while you were responding. I think that that's exactly the crux of my point: I believe it's essential to distinguish between a binding and a bound value. The Java language makes this non-obvious, but that just serves to confuse students later when they discover values being mutated through multiple references. I think it's much better to address this source of confusion head-on.
Daniel Pryden
CC BY-SA 3.0
2017-07-18T00:37:00.210Z
@DanielPryden If the binding _is_ the value, and you pass the reference _to that value (by value)_ (`func(&*ptr)`), you get what Java does and what we're both describing. Coming from a pointer understanding, the question in question describes the exact behavior. Coming from Java's angle, though, my argument is that _binding is its value_ plus _pass by reference to that value_ plus _value lives somewhere in memory_ is the better way to explain it without leaking the abstraction away from pointers. But I'm not going to argue the point; we're in agreement with different terminology definitions.
CAD97
CC BY-SA 3.0
2017-07-20T02:02:42.110Z
If we're being properly pedantic, *C* does not have pass by reference.  `f(&x)` is explicitly passing the address of `x` by value.  It isn't passing `x` at all.
Ray
CC BY-SA 3.0
2017-07-20T02:08:43.423Z
@Ray I changed the wording of my Post Script slightly. Hopefully it doesn't imply anything incorrect anymore; it's supposed to drive away the pedants ;) (<joking tone marker>)
CAD97
CC BY-SA 3.0
2017-07-20T11:55:22.703Z
[Pass by reference](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference) means that a called method can reassign *the caller's* variables to a distinct value. A good litmus test is whether you can write a function that swaps the caller's variables. Java doesn't enable this style of programming. Yes, it shoves the object on the heap, and the object can be mutated. But that isn't what "pass by reference" means; it means that full access to the caller's local variable is given. At this point, though, the matter is so widely confused that I'm not sure the terms have value anymore.
jpmc26
CC BY-SA 3.0
2017-07-20T12:02:16.930Z
In other words, contrary to your post script, the binding **is very much** separate from the value. And what's worse, understanding that the binding is a separate thing from the value is fundamental to understanding how Java works.  I can assign a list to `x`, add some elements, and then assign it `y`. Reassigning `x` to a new list and adding elements to that doesn't change the list bound to `y`. Also, how else could you make sense of the fact that two variables can be assigned the same value simultaneously?
jpmc26
CC BY-SA 3.0
2017-07-22T02:50:25.470Z
CAD97, of course the essence of your answer about pointers is more important then terminology you used and I agree with your answer but anyways I am curious about the terminology you use because it is not standard and it can confuse a lot of people. In C# you can pass by reference with ref keyword so you can make a swap function that is impossible to make in Java: `static void SwapStrings(ref string s1, ref string s2)` . If you omit keyword ref then you get the same behavior like in Java. If you call that default behavior pass by reference then how you call it when you use ref keyword in C#?
CodesInTheDark
CC BY-SA 3.0
2017-07-22T03:13:40.627Z
@CodesInTheDark Terminology is hard. The way I'd explain C#'s `ref` keyword is <del>by pretending it doesn't exist</del> probably saying that while `string s` is a binding to a string, `ref string s` is a binding to a binding to a string. So instead of passing the reference to the string, you're passing the reference to your binding to the string. (That's starting to sound like pointers... and `ref` (plus naming) is the one thing I don't like about C#.)
CAD97
CC BY-SA 3.0
2017-07-16T16:16:04.027Z
2017-07-20T02:05:16.683Z
2017-07-20T02:05:16.683Z
CAD97
<p>A related (rhetorical) question:</p>

<p><strong>Should C students be taught the [machine language] idea of reusing a pointer as a CPU instruction if the value happens to line up?</strong></p>

<p>The speaker in a Functional Programming talk I recently saw discussed part of the history of programming languages, and the opinion <em>seriously held</em> by some at one time that <em>assembly language</em> was too far abstracted because it didn't allow you to reuse CPU instruction codes as pointers and vice-versa if the values lined up.  :)</p>

<p>Also related (classic): <a href="http://www.catb.org/jargon/html/story-of-mel.html" rel="noreferrer">The Story of Mel</a>.</p>

<p>Then, the follow-up: <strong>How is that fundamentally different from teaching Java students pointer arithmetic?</strong></p>

<hr>

<p>Of course, this is a trick answer, because I <strong>do</strong> think both concepts (pointer arithmetic and reusing pointers as instructions) should be taught to Java students <em>as ideas.</em>  As part of the <em>history</em> of the subject, and the layers of abstraction underneath the level they're working at.</p>

<p>But you shouldn't make them actually <em>do</em> any pointer arithmetic.  It's totally sufficient that they understand that there is such a thing and have some idea about roughly how it was done.  It's just a significance that they're not going to actually <em>use</em> in Java, so it's good background, but don't overdo it.  It's not closely related to what you're teaching them to <strong>DO.</strong></p>

<p>Your students need to have:</p>

<ol>
<li>An excellent mastery on the <em>practical</em> skills they need to code in Java, and</li>
<li>A clear enough <em>understanding</em> of the theory and underlying concepts and background of what they are doing that <strong>they</strong> won't become obsolete after some new CS breakthrough or new language or new industry direction.</li>
</ol>

<p>Does the concept of pointer arithmetic belong in a <em>FIRST</em> class on Java?  That depends considerably on how long the course is.</p>

<p>I would say in a full semester course it would deserve perhaps a ten minute discussion at some point fairly well into the course, just for some comparative approach to Java's references and to emphasize that pointers <em>are</em> still used under the hood.  And so that your students understand that there <em>are</em> other ways to do things than how Java does them.</p>

<hr>

<p>(The balance between theoretical and practical knowledge I am advocating here is well conveyed in <a href="http://www.appliedscholastics.org/results.html" rel="noreferrer">Mr. Hubbard's Study Technology</a>, which I highly recommend for all educators and students.)</p>

CC BY-SA 3.0
2017-07-18T13:12:31.933Z
Oh yes, I remember that story of Mel. Is a cute story but code like that is fundamentally unmaintainable, which the story also shows. Real software can't work like that because (unethical or not) change requests come in and you can't just add a new feature to golf'ed code.
Draco18s no longer trusts SE
CC BY-SA 3.0
2017-07-17T22:22:26.223Z
2017-07-17T22:37:47.623Z
2017-07-17T22:37:47.623Z
Wildcard
<p>As someone who learned to program with ruby, I think that the concept of how a reference to an object works under the hood is <em>vital</em>. Having the knowledge that "under the hood" my variables may be represented as pointers to values makes certain things much easier to understand. For example, in ruby:</p>

<pre><code>a = Object.new
b = a.clone
c = a
c == b #=&gt; false
c == a #=&gt; true
</code></pre>

<p>Behavior like this could be seen as mind boggling: Why are 2 empty Objects the same, but the other 2 are not? But when given the conceptual knowledge that a pointer is a reference to a value this can be understood because <code>a</code> and <code>c</code> both point to the same Object in memory, while <code>b</code> points to a different object. Thus they have different Object IDs (<code>a.object_id == b.object_id #=&gt; false</code>) and:</p>

<pre><code># Define a setter and getter for the test variable
a.instance_exec { def self.test; @test; end; def self.test=(new_val); @test=new_val; end }
a.test = "Foo"
c.test == "Foo" #=&gt; true
b.test == "Foo" #=&gt; NoMethodError
</code></pre>

<p>In summary, I think that it's very important to include the concept of what a pointer is in the class, but there's no need to go into the down and dirty details unless the students will actually have to work with pointers.</p>

<p>The basics of what a pointer is (an integer memory address) should still be mentioned, because that gives basis to the otherwise abstract concept of a "reference". Students tend to find it useful to actually understand what's going on in hardware in that case.</p>

CC BY-SA 3.0
2017-07-16T14:49:16.453Z
This doesn't require knowledge of pointers.  It's rather easy to explain to students that you can have two different objects that are identical, but are just copies of each other.  That way, `Object.new` creates a new, identical function reference.  (Which, incidentally, is basically how Java does it)
Nathan Merrill
CC BY-SA 3.0
2017-07-16T21:54:48.047Z
I wasn't saying that we are copying function references.  Rather that they are "copies" (meaning that they look identical).  That said, "duplicates" is likely a better word.
Nathan Merrill
CC BY-SA 3.0
2017-07-16T23:02:36.957Z
How would the explanation be harder to understand if we said "*this can be understood because `a` and `c` both **reference** the same Object in memory, while `b` **references** a different object*"?
Bergi
CC BY-SA 3.0
2017-07-17T20:50:42.007Z
While I love Ruby and hence any mention of it in an answer, it has no pointers, only references. So not the right answer for the question at hand.
AnoE
CC BY-SA 3.0
2017-07-17T22:04:06.923Z
There's nothing "under the hood" in your example.  You merely are illustrating the difference between Ruby objects and Ruby variables.
Solomon Slow
CC BY-SA 3.0
2017-07-17T22:06:44.543Z
Re, "Why are 2 empty Objects the same, but the other 2 are not?"  There's no "other 2" in your example:  It only creates two objects.  `a`, `b`, and `c` are _not_ objects.  They are _variables_.  They _refer to_ objects, and in particular, `a` and `c` refer to the same object, while `b` refers to a different object.
Solomon Slow
CC BY-SA 3.0
2017-07-16T00:15:45.337Z
2017-07-16T21:45:54.207Z
2017-07-16T21:45:54.207Z
thesecretmaster
<p>No</p>

<p>Because of the way that you learn, you think of them as fundamental, to the way references work. They are not. References do not have to work this way.
[I would still agree that pointers are fundamental to understanding memory in Von Neumann / Harvard architecture.]</p>

<p>Java uses references. You can think of these as being pointers, that must point to a valid object of the correct type or to the null object. But there are other ways to thing of references, e.g. like indexes, or like references (in a book or urls). You don't even need to know what is inside.</p>

<p>Other languages don't have references. E.g stack based languages.</p>

<p>Therefore they are not fundamental in any way.</p>

<hr>

<p>My thought on types of references in Object Orientated Programming. See <a href="https://richarddelorenzi.wordpress.com/2009/08/10/types-of-reference/" rel="noreferrer">https://richarddelorenzi.wordpress.com/2009/08/10/types-of-reference/</a></p>

<p>A reference is free or fixed:</p>

<ul>
<li>I fixed reference can not be reassigned.
e.g. reference in (C++), const pointer (C++)</li>
<li>A free reference can be reassigned.
e.g. pointer in (C++), reference in (C#, Java, python …)</li>
</ul>

<p>A reference is:</p>

<ul>
<li>not null-able: Can point to a valid object: e.g. Eiffel reference</li>
<li>null-able: Can point to a valid object or null. e.g. Java, C#, python, Traditional Eiffel, Eiffel null-able reference</li>
<li>radical: Can point anywhere. e.g.  pointer, and even a reference in (C++)</li>
</ul>

<p>A reference refers to something that is:</p>

<ul>
<li>Constant</li>
<li>Mutable</li>
</ul>

CC BY-SA 3.0
2017-07-16T14:04:25.980Z
@nocomprende while I agree with what you are saying, we must be interpreting the results wrong. For how do we explain young children programming in scratch without first learning how a transistor works? I think the foundation that we build on can be, how it works (how in this language it is implemented). Or it could be based on, what it does. It is a reference, so it is like a URL, or an index entry in a book.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-16T22:32:43.800Z
@alephzero (BenI. and richard and anyone else who wants to discuss) Feel free to continue this interesting conversation in [this new room in chat](http://chat.stackexchange.com/rooms/62334/discussion-on-answer-by-richard-is-it-important-to-teach-pointers-in-a-first-cou).
thesecretmaster
CC BY-SA 3.0
2017-07-18T13:54:45.970Z
@nocomprende Surely learning abstractions first then delving into into the detail behind them is how we learn almost everything?
Ben Aaronson
CC BY-SA 3.0
2017-07-18T16:39:32.513Z
@nocomprende Ah I see, I think we're talking about slightly different things here. There's "abstracting" as in "discarding an irrelevant to detail to get a more general result". Like starting by adding apples, then moving to addition as a concept that works for anything. But there's also "abstracting" as in "hiding the inner workings". Like how if you know how to operate a VCR player, you also know how to operate a DVD player- the differences are abstracted behind a common interface. Natural sciences have a lot of examples of learning from more abstract -> more detailed in this second meaning
Ben Aaronson
CC BY-SA 3.0
2017-07-18T16:40:49.413Z
e.g. period table -> molecules and atoms -> quantum field theory. You certainly wouldn't want to do that in the reverse order, in large part because, as you say, it's better to start with concrete, accessible examples. And I'd suggest that learning about the workings of a computer is similar. Scratch exists because creating simple programs is accessible and concrete. Building understanding all the way up from transistors would be the opposite.
Ben Aaronson
CC BY-SA 3.0
2017-07-18T17:39:41.827Z
@nocomprende I made a similar comment in the chat link above, but you shouldn't conflate *what* you teach somebody with *which order* you teach it. I wouldn't hire a software developer who knew about transistors but had no conception of writing code, either, but that's not a position anyone's promoting.
Ben Aaronson
CC BY-SA 3.0
2017-07-18T17:42:57.640Z
@nocomprende BenAarenson is discussing the order of teaching, not what to teach. Also can you use the chat room http://chat.stackexchange.com/rooms/62334/discussion-on-answer-by-richard-is-it-important-to-teach-pointers-in-a-first-cou . I will ask a question on order of teaching in a few days. And invite (via chat room) you all to contribute.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-16T13:49:50.920Z
2017-07-17T17:01:42.267Z
2017-07-17T17:01:42.267Z
ctrl-alt-delor
<p>What is important is to teach students the difference between Java objects, and Java variables.  There are thousands of questions on <a href="https://stackoverflow.com">Stack Overflow</a> asked by students and by junior developers who do not understand the difference.</p>

<p>When we write <code>Foobar f = new Foobar(...)</code>, it's <em>much</em> easier to say that <code>f</code> <em>is</em> a <code>Foobar</code> than it is to say that <code>f</code> <em>holds a reference to</em> a <code>Foobar</code>---I am guilty of taking that shortcut all the time---but nobody can get past the beginner stage until they learn that non-primitive Java variables only ever hold object references, and that the objects themselves only exist in a far-away place called "the heap."</p>

CC BY-SA 3.0
2017-07-17T22:48:16.077Z
Nice point, and welcome to [cseducators.se]. I hope we hear more from you in the future!
Ben I.
CC BY-SA 3.0
2017-07-18T21:12:43.537Z
[Stack Overflow it is](http://stackoverflow.com/legal/trademark-guidance), not StackOverflow (see the last section).
Peter Mortensen
CC BY-SA 3.0
2017-07-17T22:19:05.070Z
2017-07-19T13:34:21.887Z
2017-07-19T13:34:21.887Z
Solomon Slow
<p>I think you're asking the wrong question. In my opinion the right questions are:</p>

<ol>
<li>Is it important to teach pointers at some point in the curriculum?</li>
<li>If so, which courses in the curriculum are most suitable for teaching them? (Plural to cover cases where some of the courses are optional, or where students may not grasp the concept the first time and may need reinforcement later).</li>
<li>Are there any courses which are taught earlier and which will suffer from students not understanding them?</li>
</ol>

<p>I think it should be self-evident that pointers don't need to be taught in the first programming course: if it isn't, then consider that the first course may use e.g. Haskell, and it would be crazy to try teaching pointers using Haskell. (Of course, if the first programming course uses C then question 3 becomes relevant).</p>

<p>But a stronger statement can be made: it may be that the best course to teach them isn't a programming course at all. If pointers were mentioned at all in the university CS course I studied then it was either in <em>Computer Architecture</em> or <em>Comparative Programming Languages</em> (probably in the lecture on BCPL).</p>

<p>Question 1 is something that we can debate without additional context. But we can't answer questions 2 and 3 unless you supply considerably more detail about the curriculum. And since the question posed is really a subquestion of questions 2 and 3, I don't think we can give you a useful answer to the question as stated.</p>

CC BY-SA 3.0
2017-07-17T14:21:07.353Z
Yes, I was asking about the first course only. And agree with your comments. +1
Buffy
CC BY-SA 3.0
2017-07-17T14:15:48.983Z
2017-07-17T14:15:48.983Z
Peter Taylor
<p>Pointers as used in C and C++ are a fairly specific implementation of a general concept. The details of that particular implementation are mostly irrelevant--even to people using C and/or C++, many of the details are generally irrelevant.</p>

<p>The general concept is indirection (and dereferencing). Indirection arises in many forms; pointers are one version of it--but so are (for only one example) foreign keys in a SQL database.</p>

<p>The strength (and weakness) of pointers in C and C++ is that they're a relatively general implementation of indirection. On one hand, this means that when a student has learned them, most other (more restricted) forms of indirection are fairly easy and straightforward to deal with. On the other hand, it also means that they're a fairly daunting problem for many people approaching indirection for the first time. Pointers in C and C++ are also (for one example) a common place in which the pre- and post-increment and -decrement operators are used--so when students are supposed to be learning about indirection, it's easy for them to get side-tracked into truly ugly details about the degree to which C and C++ specify (and more to the point, mostly <em>don't</em> specify) sequencing of these operations.</p>

<p>Personally, I think I got somewhat lucky in my timing in learning about such things. The first language in which I was exposed to pointers was Pascal. It had (still has, for the relatively few who still use it) a relatively clean implementation of indirection. You can dynamically allocate an object, and what you get back is a pointer. You can then dereference that pointer to get to the object you allocated. You can do things like assigning and passing pointers as parameters--but that's pretty much it. You don't get into a lot of other details about things like pointer arithmetic that are fairly central to C, but basically irrelevant to the core concept of indirection.</p>

<p>Java, of course, is a poor choice of vehicles for teaching this concept (or much of anything else, but I digress). It attempts to hide the concept of indirection, which makes it more difficult to teach. At the same time, what it provides is (at best) an extremely leaky abstraction. A language that claims it doesn't use pointers, but does use <code>NullPointerException</code>s leads to confusion, not enlightenment.</p>

<p>Given that you're apparently already using Java, perhaps it wouldn't be too much of a stretch to provide your students with at least a little exposure to Clojure. This will let you do at least a little exploration of indirection without getting into a lot of ugly details about C and C++ that are difficult to avoid, but irrelevant to the underlying concept.</p>

CC BY-SA 3.0
2017-07-16T20:51:25.667Z
Hi Jerry! Welcome to [cseducators.se]! Thanks for this very interesting answer! I hope to see you around, doing more asking or answering!
thesecretmaster
CC BY-SA 3.0
2017-07-17T18:27:52.853Z
IMO a null reference exception is pretty easy to understand "You tried to use an object that didn't exist." That is, you *declared* it but you didn't *define* it. Pointers let you do god awful things like `int val = *somoeObj; val++; Object foo = &val` No really. Why would you do that. Why would you EVER BE ALLOWED TO DO THAT.
Draco18s no longer trusts SE
CC BY-SA 3.0
2017-07-18T03:15:22.713Z
@Draco18s, I wonder if you saw [my answer](https://cseducators.stackexchange.com/a/2737/1103)?  :)  I would enjoy listening to a conversation between you and Mel.
Wildcard
CC BY-SA 3.0
2017-07-18T13:04:49.430Z
@Wildcard I have now, and I can respect that opinion. Not sure how much I agree (at least half?)
Draco18s no longer trusts SE
CC BY-SA 3.0
2017-07-16T20:45:35.550Z
2017-07-16T20:45:35.550Z
Jerry Coffin
<p>No, you don't need to talk about pointers in an introductory Java class. You should talk about <strong>references</strong>, but even then you should keep it at a very high level.</p>

<p>The best tutorial on references I've seen is <a href="http://www.javaranch.com/campfire/StoryCups.jsp" rel="noreferrer">Cup Size -- a story about variables</a> and its follow up <a href="http://javaranch.com/campfire/StoryPassBy.jsp" rel="noreferrer">Pass-by-Value Please</a>. These talk about variables as cups that can hold different items, and references as remote controls that you can put in a cup. You can have two remote controls in two cups that control the same TV, and replacing one of the remote controls with another one that controls a different TV doesn't affect the first TV at all. This also clears up the misconception that Java is "pass-by-reference for objects" when in fact Java is always pass-by-value.</p>

<p>I think this kind of high-level language is what you should be using. You shouldn't get into the low-level details, and you shouldn't even use the word <em>pointer</em> at all.</p>

CC BY-SA 3.0
2017-07-17T16:30:30.890Z
I love those stories! I can imagine bringing various Starbucks cups into class for a physical demonstration.... welcome to [cseducators.se]. I hope we hear more from you in the future!
Ben I.
CC BY-SA 3.0
2017-07-17T16:23:01.693Z
2017-07-17T16:23:01.693Z
Kevin Workman
<p>Maybe you are thinking about memory management and pointer arithmetics. There is no need for that in the first course.</p>
<p>However I think that it is important to teach students that in Java object are created on heap and you have named pointers (which they call references) that you pass by value when you call a method (similarity with C language).</p>
<p>So Java does have pointers. What Java lacks, is pointer arithmetic.
For example if you define an object like this: <code>Integer pointsToAnInt = 5</code> that will create a pointer 'pointsToAnInt' to a location in memory that contains number 5.</p>
<p>If you say <code>pointsToAnInt = null;</code> and then call <code>pointsToAnInt.intValue();</code> you will get <strong><code>NullPointerException</code></strong> because that <strong>pointer</strong> points to null.</p>
<p>From the Java language specification:
<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html" rel="nofollow noreferrer">Chapter 4. Types, Values, and Variables</a></p>
<blockquote>
<p>An object is a class instance or an array. The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.</p>
</blockquote>
<p>So for marketing reasons Java didn't mention pointers and they called them references but essentially you use pointers and you can get <code>NullPointerException</code>.</p>
<p>On the other hand C++ can pass values by references which Java cannot because <a href="https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value">Java is pass by value</a>. So references should be something different but in Java a reference to an object is just a pointer to that object and you pass that pointer by value through stack while objects are created on heap and they are garbage collected when there are no more pointers that point to them.</p>
<p><strong>Edit:</strong>
By using <code>sun.misc.Unsafe</code> you can convert an int to an arbitrary address of an entity. In that case you can also have pointer arithmetic. In my personal experience telling people that Java does not have pointers did a great damage to understanding Java and introduced confusion among people to think that Java is pass-by-reference.</p>
<p>In C# you can pass by reference with <code>ref</code> keyword so you can make a swap function that you cannot make in Java <code>static void SwapStrings(ref string s1, ref string s2)</code>. If you omit keyword <code>ref</code> then you get the same behavior like in Java and that is <strong>pass by value</strong>.</p>

CC BY-SA 4.0
2019-05-30T05:08:26.697Z
"you will get `NullPointerException` because that **pointer** points to null." You mean, because that pointer does not point to anything. (Hence asking for a thing that it points to raises an exception.) As confirmed by the quote you put after that statement--"a special null reference, which refers to no object".
philipxy
CC BY-SA 4.0
2019-05-31T00:31:13.537Z
The value of pointer is usually zero (meaning null) in most implementations. That represents null value that indicates that the pointer does not refer to a valid object. That pointer is called Null pointer/reference or some people call it null object pointer.
Function pointer is a pounter that points to a function. Data pointer is a pointer that points to some data. In a similar manner Null pointer is a pointer that points to null value. Maybe you don't use the same syntax/wording, but semantic is the same and we think about the same thing.
CodesInTheDark
CC BY-SA 4.0
2019-05-31T00:32:37.477Z
"Does not point to anything" for you is the same as "points to null value" for me. I am not a native English speaker so I guess that formally you are correct. But it is important that people understand what I mean. I guess that I failed in that regard :(
CodesInTheDark
CC BY-SA 3.0
2017-07-17T04:49:18.727Z
If you read my answer you'll see I disagree with that answer about Java and pass-by-value (for object types). It's not worth arguing though because it's just saying the same thing two different ways.
CAD97
CC BY-SA 3.0
2017-07-17T04:50:47.700Z
Oh, and welcome to [Computer Science Educators](https://cseducators.stackexchange.com)! (I'm almost as new, am I qualified to say that?)
CAD97
CC BY-SA 3.0
2017-07-17T04:53:17.060Z
@CAD97 You certainly are :)  I hope we see more of both of you.
Ben I.
CC BY-SA 3.0
2017-07-17T05:01:57.270Z
Hi CAD97, thank you for your comment. I posted my answer to add additional things to your answer because I don't have enough reputation points to post a comments on other people's answers. Anyways you could copy from my answer a link to Java Language Specification where it says that references are pointers to objects. All the best.
CodesInTheDark
CC BY-SA 3.0
2017-07-17T14:15:36.440Z
CAD97, in C# you can pass by reference with `ref` keyword so you can make a swap function that you cannot make in Java `static void SwapStrings(ref string s1, ref string s2)` . If you omit keyword ref then you get the same behavior like in Java and that is pass by value. If you think that it is pass by reference then how you call it when you use `ref` keyword in C#?
CodesInTheDark
CC BY-SA 4.0
2017-07-17T04:44:16.053Z
2021-01-29T21:51:38.687Z
2021-01-29T21:51:38.687Z
CodesInTheDark
<p>Here is what it is important to know early.  </p>

<ol>
<li>Primitive type variables store their value directly (I say:  "Primitive types point directly at their values.")</li>
<li>Object type variables store the <em>location</em> of their objects in memory.  I say: "Object variables know <em>where</em> their object is in memory.   </li>
<li>Java is a strictly pass-by-value language in this sense:  functions get a <em>copy</em> of the value stored by the variable passed them.  </li>
<li>If you pass a variable pointing at a mutable object to a function, and the function changes that object's state (e.g. remove an item from an ArrayList), the object itself is changed.  Why?  Because you passed that object's location in memory to the function and the callee used a mutator method on that object.  BANG!  Object state is changed.</li>
<li>In reference to the last item, you can treat variables pointing to primitive types as if they were pointing at immutable objects, since a copy of the variable's value is made and the original cannot be changed.</li>
</ol>

<p>Knowing these things early saves a lot of confusion.</p>

CC BY-SA 3.0
2017-07-17T20:20:51.610Z
2017-07-17T20:20:51.610Z
ncmathsadist
<p>No. Java and Smalltalk were designed as true object oriented languages.  Bjarne Stroustrup who defined and wrote the C++ programming language also had the goal of object orientation but had to carry the baggage of the procedural and scripted C programming language due to the installed user base.  If he had gotten rid of pointers and other ool polluters, it would have involved a much greater overhaul of the compilers.</p>

<p>The compilers are the main workload when designing a new programming language since you have to write a customized compiler for each hardware and OS platform, which is very non-trivial.</p>

<p>I would avoid teaching not just pointers but all OOL polluters for the following reasons:</p>

<p>Times have changed and your students may be beginners now, but eventually they will be writing code to perform:</p>

<p>writing classes for inheritable exception handling, remember for each feature of a program, you have to typically write 5 - 10 exception handling classes. Well designed software would handle errors so well that they would be invisible to the user.  When things do go wrong, an analyst will have a much easier time with inheritable and extendable exception classes.</p>

<p>Object design for artificial intelligence </p>

<p>Both of the above require pure knowledge of OOL. Pointers would just confuse them.</p>

<p>You can teach pointers to a hacking class.</p>

CC BY-SA 3.0
2017-07-18T11:46:03.423Z
Welcome to [cseducators.se]! Nice insights here.
Ben I.
CC BY-SA 3.0
2017-07-18T01:51:33.363Z
2017-07-18T01:51:33.363Z
0tyranny0poverty
<p>This is a tricky issue and where I think  using a bit of formal semantics may help. Of course you don't want to introduce Greek letters and inference rules for undergrads but the concepts should be laid out clearly.</p>

<p>The most important thing I do early when presenting a programming language is to distinguish between syntax (how you write) and semantics (how things run. I later divide it into static semantics --typing-- and dynamic semantics). So here, as others have said, introducing <em>pointers</em> is not a good thing and goes against the spirit of Java (pointers don't exist). <em>But</em> you should present something namely what a <em>value</em> is in Java. The notion of value is fundamental. What is the result  when a particular piece of code (syntax) is evaluated.</p>

<p>In Java constants of primitive types are their own values, but Objects on the other hand evaluate to a unique identity (whether you want to say that this identity is the memory address depends on your students and their backgrounds). It's a bit abstract but it allows you to explain several behaviours of the language. For instance, if you pass an object as argument to a method and perform mutation, the object is mutated (although the language is "call by value", since the value of the object is its unique ID, the modification occur on this particular object, not a copy). Conversely, even if you create two instances of the same class with the same internal content (say <code>Point p1 = new Point(0,0)</code> and <code>Point p2 = new Point(0,0)</code>) both objects will compare unequal (with <code>==</code>).
Which then allows you to also introduce why you should compare String object with .equals and so on.</p>

<p>The fact that some languages allow to manipulate this unique identity (pointers, pointer arithmetic etc…) is orthogonal, and imho should not be used to justify the behaviour of Java. It can certainly help as an analogy if the students have prior background in C/C++ but introducing a foreign low-level concept is not way to go.</p>

<p>In summary, you should not introduce pointers <em>but</em> this is not an excuse to not to explain precisely what is going on (call by value semantics with value being unique identities for Objects).</p>

CC BY-SA 3.0
2017-07-19T12:54:04.067Z
2017-07-19T12:54:04.067Z
Kim Nguyễn
<p>As someone who is self-taught with Python, I'd say it depends on where your students are at. If they're beginning students - no, I don't think you need too. But as your students advance, it becomes a better idea. First, it's a good idea for programmers to understand multiple languages, including languages that use pointers. Second, the term is often thrown around on forums or in books - it's good to know the lingo. Finally, when I did learn the basics of what a pointer was, it was useful for understanding how memory worked - it's good to understand the basics of lower level actions the computer takes to make your program run.</p>

CC BY-SA 3.0
2017-07-16T12:59:08.360Z
2017-07-16T12:59:08.360Z
auden
<p>Many instructors teaching with Java started their education using earlier languages such as C or C++ in which pointers are essential. Pointers, however, are not a Java concept, though those same instructors may think of, for example, object references as pointers.</p>

<p><strong>How important is it to teach pointers in a first Java course</strong> assuming the students don't have much of a prior programming background?</p>

<p>If you think it is important, say why, but also say how much of pointers do you think should be taught. Just as a metaphor/analogy? Or also including, say, pointer arithmetic?</p>

<p>If you think it is not important say why also.</p>

<p>Note that both Python and Ruby are similar to Java in lacking the "pointer" concept. References might be implemented as pointers or not, but the definition of reference is actually abstract in these languages.</p>

<hr>

<p>Note that I take "pointer" to mean the actual machine address of some entity that might, in principle, be manipulated as an integer, whereas "reference" is a more abstract concept that implies that the entity may be accessed via the reference however implemented.</p>

<p>The Java language definition is careful not to discuss the implementation of references, explicitly disassociating them from the C-like notion of pointer.</p>

CC BY-SA 3.0
2017-07-16T14:14:04.763Z
Java and the other similar languages have garbage collectors. Leaving it undefined lets a reference cooperate with the garbage collector, depending on implementation. The "pointer" in the reference may not point directly to the object's storage but to something managed by GC. C has no need to do this.
Buffy
CC BY-SA 3.0
2017-07-17T00:40:57.617Z
Learning pointers is already quite hard ... but if you feel the need for an extra challenge, try learning what pointers are in a language which does not have pointers ...
Chris Burt-Brown
CC BY-SA 3.0
2017-07-17T01:04:50.287Z
Whatever you do, don't talk about pointers in Java. Java does not have pointers. You can teach references, that's fine and necessary. Especially don't try to teach about memory addresses or pointer arithmetic because *those are not things in Java*.
Criticize SE actions means ban
CC BY-SA 3.0
2017-07-17T02:34:56.250Z
If there are no pointers in Java, how do you get a NullPointerException? :)
nova
CC BY-SA 3.0
2017-07-17T05:08:01.243Z
@nova - that's my go-to example for how the whole "no pointers" thing in Java is a poorly thought out whitewash.
davidbak
CC BY-SA 3.0
2017-07-17T19:57:12.603Z
@nova NullPointerException (which I mention to my students too as proof that there are pointers deep down) is a leaky abstraction.
Ellen Spertus
CC BY-SA 3.0
2017-07-17T19:59:41.123Z
On the other hand, it is conceivable that the exception was badly named. I don't disagree with the comments here, but had it been named otherwise (invalid reference exception) would you still worry. But yes, Java made compromises in its model.
Buffy
CC BY-SA 3.0
2017-07-18T08:49:55.997Z
That's why C# calls the exact same thing a `NullReferenceException`.
Philipp
CC BY-SA 3.0
2017-07-18T12:55:44.457Z
I think it is important to use the Java terminology even when it doesn't match the rest of the industry.  So call it a "reference", not a "pointer" (even though it is much more like a C++ pointer than reference), it is important to teach the concept early, otherwise, comparing strings versus comparing int's makes no sense.
Guy Schalnat
CC BY-SA 3.0
2017-07-18T15:16:10.823Z
[JLS Section 4.3.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1) "The reference values (often just *references*) are **pointers** to these objects, and a special null reference, which refers to no object". Any assertion that Java doesn't have pointers is wrong. Maybe you want to just stick to the terminology of references but don't confuse the students with all the garbage about how Java passes objects by reference and primitives by value.  Everything is passed by value. The value of the references is a pointer.
JimmyJames
CC BY-SA 3.0
2017-07-18T16:49:36.187Z
I think my experience is quite different from yours. Also my conclusions. Everything is a Turing Machine, but I don't need to wind the tape.
Buffy
CC BY-SA 3.0
2017-07-18T21:21:59.507Z
@Buffy "The Java language definition is careful not to discuss the implementation of references, explicitly disassociating them from the C-like notion of pointer." I've provided the relevant section of the JLS that would seem to contradict this.  I'm curious as to why you aren't addressing that.
JimmyJames
CC BY-SA 3.0
2017-07-18T22:17:17.870Z
It is a question seeking answers such as yours. It isn't a treatise.
Buffy
CC BY-SA 3.0
2017-07-19T09:10:24.113Z
@nova That was named very, very early in Java's history, and Java has a tradition of not breaking API's.
Thorbjørn Ravn Andersen
CC BY-SA 3.0
2017-07-20T01:53:07.243Z
@nocomprende I agree entirely that they need to learn these concepts (and preferably early on), but Java isn't the language to do it in.  Students have a hard enough time understanding pointers in languages that *have* them (in a form other than implicit references).  If you *must* use Java to teach intro programming, it's more practical to hold off on teaching pointers until they switch to C.
Ray
<best-practice><object-oriented-paradigm><pointers>
Is it important to teach pointers in a first course using Java?
# Is it important to teach pointers in a first course using Java?

(Asked by: username_0 on 2017-07-15)

Many instructors teaching with Java started their education using earlier languages such as C or C++ in which pointers are essential. Pointers, however, are not a Java concept, though those same instructors may think of, for example, object references as pointers.

**How important is it to teach pointers in a first Java course** assuming the students don't have much of a prior programming background?

If you think it is important, say why, but also say how much of pointers do you think should be taught. Just as a metaphor/analogy? Or also including, say, pointer arithmetic?

If you think it is not important say why also.

Note that both Python and Ruby are similar to Java in lacking the "pointer" concept. References might be implemented as pointers or not, but the definition of reference is actually abstract in these languages.

---

Note that I take "pointer" to mean the actual machine address of some entity that might, in principle, be manipulated as an integer, whereas "reference" is a more abstract concept that implies that the entity may be accessed via the reference however implemented.

The Java language definition is careful not to discuss the implementation of references, explicitly disassociating them from the C-like notion of pointer.

**Tags:** best-practice, object-oriented-paradigm, pointers

> **Comments:**
> **username_0**: Java and the other similar languages have garbage collectors. Leaving it undefined lets a reference cooperate with the garbage collector, depending on implementation. The "pointer" in the reference may not point directly to the object's storage but to something managed by GC. C has no need to do this.  
> **username_1**: Learning pointers is already quite hard ... but if you feel the need for an extra challenge, try learning what pointers are in a language which does not have pointers ...  
> **username_2**: Whatever you do, don't talk about pointers in Java. Java does not have pointers. You can teach references, that's fine and necessary. Especially don't try to teach about memory addresses or pointer arithmetic because *those are not things in Java*.  
> **username_3**: If there are no pointers in Java, how do you get a NullPointerException? :)  
> **username_4**: @username_3 - that's my go-to example for how the whole "no pointers" thing in Java is a poorly thought out whitewash.  
> **username_5**: @username_3 NullPointerException (which I mention to my students too as proof that there are pointers deep down) is a leaky abstraction.  
> **username_0**: On the other hand, it is conceivable that the exception was badly named. I don't disagree with the comments here, but had it been named otherwise (invalid reference exception) would you still worry. But yes, Java made compromises in its model.  
> **username_6**: That's why C# calls the exact same thing a `NullReferenceException`.  
> **username_7**: I think it is important to use the Java terminology even when it doesn't match the rest of the industry.  So call it a "reference", not a "pointer" (even though it is much more like a C++ pointer than reference), it is important to teach the concept early, otherwise, comparing strings versus comparing int's makes no sense.  
> **username_8**: [JLS Section 4.3.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1) "The reference values (often just *references*) are **pointers** to these objects, and a special null reference, which refers to no object". Any assertion that Java doesn't have pointers is wrong. Maybe you want to just stick to the terminology of references but don't confuse the students with all the garbage about how Java passes objects by reference and primitives by value.  Everything is passed by value. The value of the references is a pointer.  
> **username_0**: I think my experience is quite different from yours. Also my conclusions. Everything is a Turing Machine, but I don't need to wind the tape.  
> **username_8**: @username_0 "The Java language definition is careful not to discuss the implementation of references, explicitly disassociating them from the C-like notion of pointer." I've provided the relevant section of the JLS that would seem to contradict this.  I'm curious as to why you aren't addressing that.  
> **username_0**: It is a question seeking answers such as yours. It isn't a treatise.  
> **username_9**: @username_3 That was named very, very early in Java's history, and Java has a tradition of not breaking API's.  
> **username_10**: @nocomprende I agree entirely that they need to learn these concepts (and preferably early on), but Java isn't the language to do it in.  Students have a hard enough time understanding pointers in languages that *have* them (in a form other than implicit references).  If you *must* use Java to teach intro programming, it's more practical to hold off on teaching pointers until they switch to C.  

---

## 20 answers

### Answer by username_25 on 2017-07-16. Score: 31 | Accepted answer

For a beginning course: ***no***.

I have helped clarify behavior for fellow students who got lost by an instructor who explained things in terms of pointers. I have programmed in C, and most of my current programming is done in Rust; I understand pointers and what problems they are best suited to solve. But in Java, you don't have any access to pointers, so explaining pointers only serves to muddy the waters for a student trying to grep the *way a computer thinks*.

I take the position that a intro-level course should only cover programming, and the actual science of computer science should be postponed to at earliest 102. But my college also lacks a Software Engineering track, and I would argue most people pursuing a CS education actually want that instead of the science.

In any case, Java uses *pass by reference*. I know exactly what anyone who cares about terminology and grew up in C/++ is thinking as soon as I say that: Java is *pass reference by value*. But this is inconsistent with Java's own mental model.

Here's the mental model I have shared multiple times to great effect with students who failed to understand Java's Objects the first time:

A variable is a binding to a value. Thus, when you do `Animal c = new Cat();`, `c` is a binding to the constructed `Cat`. This binding is transparent, and when you use it, you are talking directly to the bound object.

However, in order to facilitate resource sharing, when you pass this object as a parameter to a method, a new binding is created. This binding is to the same object, but is a new binding, so assignment to the binding does not effect the old one (the *pass by value*).

But because these two bindings are bound to the same object, there is *only one object*. This means that mutating this object by using its fields or methods will have the effect that the object the original binding is bound to also changes, because they are the same object.

Note that nothing about this mental model breaks on primitives (or the quasi-primitive String), since primitives can only be changed by reassigning. A slightly higher-level course, or even later in the course once students *understand* the shared resource concept, can mention that primitives aren't bindings but rather just their value.

Once binding misdirection gets multiple layers deep (Objects containing Objects containing etc), it can be useful to talk about and diagram name bindings as a pointer to a value, but that's as far as I go. Stack/Heap doesn't need to be discussed in a Java class: the GC and no stack allocated objects mean that just "somewhere in memory" is all that really needs to be mentioned on object storage until you're at an advanced level where cache coherency or GC overload matters.

---

Post Script:

I've called Java *pass by reference* here, which will (and has) riled up a bunch of people who want *pass by reference* to only mean what is expressed in C as `function(&name)`, which Java is not doing. As such, it may be better to call it *pass by resource sharing*, *pass by resource binding*, or *pass by binding*. In C's definition, you are passing a *copy* of the *reference* by *value* (`function(&*name)`). By my reading of Java, though, I argue that we are passing by the reference to the value, because the binding is not separate from the value. This is a terminology problem, and unfortunately, even in a field that relies on unambiguous interpretations, we do overload our terminology.

> **Comments:**
> **username_19**: Really wonderful answer. *"But my college also lacks a Software Engineering track, and I would argue most people pursuing a CS education actually want that instead of the science."* is exactly right. Come by the [chat room](https://chat.stackexchange.com/rooms/59174/the-classroom) to say hi, and welcome to [cseducators.se]!  
> **username_26**: I think using the phrase *Java uses pass by reference* is dangerous at best, especially when talking about an introductory class. Keep it high level, but if any students ask about the nitty-gritty, make sure they know that Java is pass by value, even for references.  
> **username_27**: I never did grok pointers and constantly had trouble with them when working in languages like C++ (I never could remember if I needed to `*` the variable or `&` and on which *side* that operator needed to go, because seriously, would it have *killed* someone to make that syntax consistent?). I *hated* pointers. Object references in languages like Java and C#? So easy to understand and use effectively.  
> **username_25**: @KevinWorkman As I said, it's a matter of definitions. When you have a Java binding, it _is_ the thing it's bound to; you don't have to `*` it to dereference the pointer. The way Java is implemented is by passing the pointer by value, but because the binding _is_ the bound value, you're passing the bound value by reference. C's pass-by-reference is a completely different thing to Java's, and it's a conflation of definitions. By C's definitions, Java is pass-reference-by-value, and I will never object to that, because it is correct. Just confusing if you don't know pointers inside out.  
> **username_26**: *"Just confusing if you don't know pointers inside out."* That's exactly my point. This is for an introductory class. The students do not know pointers inside out.  
> **username_28**: Did you mean "grok" when you typed "grep"?  That's a funny typo.  :)  
> **username_29**: This answer is misleading at best, and potentially dangerously wrong. Java most definitely does **not** have call-by-reference semantics. (Compare [this question on Stack Overflow](https://stackoverflow.com/questions/40480), and also the large amount of confusion in [this other Stack Overflow question](https://stackoverflow.com/questions/373419).) Too many people try to conflate "call-by-reference" with "reference types", so it's important to distinguish those concepts early, before a wrong mental model sets in.  
> **username_25**: @DanielPryden Did you read that paragraph? I've read that answer. I acknowledge immediately that Java is _pass reference by value_. The difference is that I (and Java, by my reading) consider a binding _to be indistinguishable from_ the bound value, so passing a reference is passing a reference to that bound value, not the binding itself, thus, passing the reference by value. It's not comparable to C/++ where a pointer/reference and the value itself are different things. EDIT: your grace period edit makes clearer what you mean. I don't disagree.  
> **username_29**: @username_25: I've edited my comment while you were responding. I think that that's exactly the crux of my point: I believe it's essential to distinguish between a binding and a bound value. The Java language makes this non-obvious, but that just serves to confuse students later when they discover values being mutated through multiple references. I think it's much better to address this source of confusion head-on.  
> **username_25**: @DanielPryden If the binding _is_ the value, and you pass the reference _to that value (by value)_ (`func(&*ptr)`), you get what Java does and what we're both describing. Coming from a pointer understanding, the question in question describes the exact behavior. Coming from Java's angle, though, my argument is that _binding is its value_ plus _pass by reference to that value_ plus _value lives somewhere in memory_ is the better way to explain it without leaking the abstraction away from pointers. But I'm not going to argue the point; we're in agreement with different terminology definitions.  
> **username_10**: If we're being properly pedantic, *C* does not have pass by reference.  `f(&x)` is explicitly passing the address of `x` by value.  It isn't passing `x` at all.  
> **username_25**: @username_10 I changed the wording of my Post Script slightly. Hopefully it doesn't imply anything incorrect anymore; it's supposed to drive away the pedants ;) (<joking tone marker>)  
> **username_23**: [Pass by reference](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference) means that a called method can reassign *the caller's* variables to a distinct value. A good litmus test is whether you can write a function that swaps the caller's variables. Java doesn't enable this style of programming. Yes, it shoves the object on the heap, and the object can be mutated. But that isn't what "pass by reference" means; it means that full access to the caller's local variable is given. At this point, though, the matter is so widely confused that I'm not sure the terms have value anymore.  
> **username_23**: In other words, contrary to your post script, the binding **is very much** separate from the value. And what's worse, understanding that the binding is a separate thing from the value is fundamental to understanding how Java works.  I can assign a list to `x`, add some elements, and then assign it `y`. Reassigning `x` to a new list and adding elements to that doesn't change the list bound to `y`. Also, how else could you make sense of the fact that two variables can be assigned the same value simultaneously?  
> **username_30**: username_25, of course the essence of your answer about pointers is more important then terminology you used and I agree with your answer but anyways I am curious about the terminology you use because it is not standard and it can confuse a lot of people. In C# you can pass by reference with ref keyword so you can make a swap function that is impossible to make in Java: `static void SwapStrings(ref string s1, ref string s2)` . If you omit keyword ref then you get the same behavior like in Java. If you call that default behavior pass by reference then how you call it when you use ref keyword in C#?  
> **username_25**: @username_30 Terminology is hard. The way I'd explain C#'s `ref` keyword is <del>by pretending it doesn't exist</del> probably saying that while `string s` is a binding to a string, `ref string s` is a binding to a binding to a string. So instead of passing the reference to the string, you're passing the reference to your binding to the string. (That's starting to sound like pointers... and `ref` (plus naming) is the one thing I don't like about C#.)  

---

### Answer by username_21 on 2017-07-16. Score: 44

Learning about references is important, but I don't feel that learning about pointers is that important for **beginning** Java students. Certainly intermediate students will need to understand them.

When I started learning about pointers, I had a hard time grasping them at all until I learned assembly language. Once I learned assembly (for any processor), pointers made sense. It helped that I learned PDP-11 assembly at about the same time I learned C. Since C is essentially structured PDP-11 assembly language, I was easily able to see the relationship between the pointer structures and the compiled code.

Java hides the concept of a pointer sufficiently deeply that I would be hard pressed to explain it with java. I can explain java structures in terms of pointers, but have difficulty expressing it the other way around. For teaching pointers and pointer concepts, I would probably use C (yep - plain old C, without the ++) and the x86 assembly language as a starting point.

After that, it's easy to explain that the JVM is built in C, and java object references are implemented as pointers.

> **Comments:**
> **username_22**: +1 I agree that pointers are sufficiently abstracted in reference based languages like Java, C#, and many others that they do not need to be covered in an introductory programming course.  However, one potential pitfall many institutions fall into is the next instructor (for intermediate courses) tends to assume they have already been covered in earlier courses.  
> **username_23**: Irrespective of the importance, I can't say I shared your experience. Even having never programmed in assembly or seriously in C/C++ (just a couple college projects well after I had learned Java used pointers), I had no trouble grasping the idea that Java has your object's data in a separate block (over on the heap) and that the variable I'm using at the moment actually just corresponds to an address pointing to that block. Granted, that's a bit simplistic, but I didn't find the basic concept of pointers that hard, and even that limited understanding made Java's behavior more sensible.  
> **username_24**: @LeeHiles C# also has pointers, so that's not quite as good an example. Not quite as raw as C's, but then again C's aren't quite as raw as assembly's. E.g. there's no null pointer in assembly, that's a C construct; a pointer in assembly isn't necessarily a single integer; two pointers can point to the same memory despite having different values (*and vice versa*); I've got more where those came from :P In contrast, I've seen plenty of programs in C or Pascal that avoided pointers almost entirely (not counting "indexing a statically allocated array" as "using pointers").  
> **username_21**: @jpm26 java was invented about 20 years after I learned about pointers. I came through BASIC that was still close enough to its Fortran roots to be recognizable as such (no scope, so no distinction between references and values),  into pascal and C. We have had different experiences for sure.  

---

### Answer by username_35 on 2017-07-16. Score: 16

No

Because of the way that you learn, you think of them as fundamental, to the way references work. They are not. References do not have to work this way.
[I would still agree that pointers are fundamental to understanding memory in Von Neumann / Harvard architecture.]

Java uses references. You can think of these as being pointers, that must point to a valid object of the correct type or to the null object. But there are other ways to thing of references, e.g. like indexes, or like references (in a book or urls). You don't even need to know what is inside.

Other languages don't have references. E.g stack based languages.

Therefore they are not fundamental in any way.

---

My thought on types of references in Object Orientated Programming. See <https://richarddelorenzi.wordpress.com/2009/08/10/types-of-reference/>

A reference is free or fixed:

* I fixed reference can not be reassigned.
  e.g. reference in (C++), const pointer (C++)
* A free reference can be reassigned.
  e.g. pointer in (C++), reference in (C#, Java, python …)

A reference is:

* not null-able: Can point to a valid object: e.g. Eiffel reference
* null-able: Can point to a valid object or null. e.g. Java, C#, python, Traditional Eiffel, Eiffel null-able reference
* radical: Can point anywhere. e.g. pointer, and even a reference in (C++)

A reference refers to something that is:

* Constant
* Mutable

> **Comments:**
> **username_35**: @nocomprende while I agree with what you are saying, we must be interpreting the results wrong. For how do we explain young children programming in scratch without first learning how a transistor works? I think the foundation that we build on can be, how it works (how in this language it is implemented). Or it could be based on, what it does. It is a reference, so it is like a URL, or an index entry in a book.  
> **username_14**: @alephzero (BenI. and richard and anyone else who wants to discuss) Feel free to continue this interesting conversation in [this new room in chat](http://chat.stackexchange.com/rooms/62334/discussion-on-answer-by-richard-is-it-important-to-teach-pointers-in-a-first-cou).  
> **username_36**: @nocomprende Surely learning abstractions first then delving into into the detail behind them is how we learn almost everything?  
> **username_36**: @nocomprende Ah I see, I think we're talking about slightly different things here. There's "abstracting" as in "discarding an irrelevant to detail to get a more general result". Like starting by adding apples, then moving to addition as a concept that works for anything. But there's also "abstracting" as in "hiding the inner workings". Like how if you know how to operate a VCR player, you also know how to operate a DVD player- the differences are abstracted behind a common interface. Natural sciences have a lot of examples of learning from more abstract -> more detailed in this second meaning  
> **username_36**: e.g. period table -> molecules and atoms -> quantum field theory. You certainly wouldn't want to do that in the reverse order, in large part because, as you say, it's better to start with concrete, accessible examples. And I'd suggest that learning about the workings of a computer is similar. Scratch exists because creating simple programs is accessible and concrete. Building understanding all the way up from transistors would be the opposite.  
> **username_36**: @nocomprende I made a similar comment in the chat link above, but you shouldn't conflate *what* you teach somebody with *which order* you teach it. I wouldn't hire a software developer who knew about transistors but had no conception of writing code, either, but that's not a position anyone's promoting.  
> **username_35**: @nocomprende BenAarenson is discussing the order of teaching, not what to teach. Also can you use the chat room http://chat.stackexchange.com/rooms/62334/discussion-on-answer-by-richard-is-it-important-to-teach-pointers-in-a-first-cou . I will ask a question on order of teaching in a few days. And invite (via chat room) you all to contribute.  

---

### Answer by username_34 on 2017-07-17. Score: 13

What is important is to teach students the difference between Java objects, and Java variables. There are thousands of questions on [Stack Overflow](https://stackoverflow.com) asked by students and by junior developers who do not understand the difference.

When we write `Foobar f = new Foobar(...)`, it's *much* easier to say that `f` *is* a `Foobar` than it is to say that `f` *holds a reference to* a `Foobar`---I am guilty of taking that shortcut all the time---but nobody can get past the beginner stage until they learn that non-primitive Java variables only ever hold object references, and that the objects themselves only exist in a far-away place called "the heap."

> **Comments:**
> **username_19**: Nice point, and welcome to [cseducators.se]. I hope we hear more from you in the future!  
> **username_37**: [Stack Overflow it is](http://stackoverflow.com/legal/trademark-guidance), not StackOverflow (see the last section).  

---

### Answer by username_28 on 2017-07-17. Score: 11

A related (rhetorical) question:

**Should C students be taught the [machine language] idea of reusing a pointer as a CPU instruction if the value happens to line up?**

The speaker in a Functional Programming talk I recently saw discussed part of the history of programming languages, and the opinion *seriously held* by some at one time that *assembly language* was too far abstracted because it didn't allow you to reuse CPU instruction codes as pointers and vice-versa if the values lined up. :)

Also related (classic): [The Story of Mel](http://www.catb.org/jargon/html/story-of-mel.html).

Then, the follow-up: **How is that fundamentally different from teaching Java students pointer arithmetic?**

---

Of course, this is a trick answer, because I **do** think both concepts (pointer arithmetic and reusing pointers as instructions) should be taught to Java students *as ideas.* As part of the *history* of the subject, and the layers of abstraction underneath the level they're working at.

But you shouldn't make them actually *do* any pointer arithmetic. It's totally sufficient that they understand that there is such a thing and have some idea about roughly how it was done. It's just a significance that they're not going to actually *use* in Java, so it's good background, but don't overdo it. It's not closely related to what you're teaching them to **DO.**

Your students need to have:

1. An excellent mastery on the *practical* skills they need to code in Java, and
2. A clear enough *understanding* of the theory and underlying concepts and background of what they are doing that **they** won't become obsolete after some new CS breakthrough or new language or new industry direction.

Does the concept of pointer arithmetic belong in a *FIRST* class on Java? That depends considerably on how long the course is.

I would say in a full semester course it would deserve perhaps a ten minute discussion at some point fairly well into the course, just for some comparative approach to Java's references and to emphasize that pointers *are* still used under the hood. And so that your students understand that there *are* other ways to do things than how Java does them.

---

(The balance between theoretical and practical knowledge I am advocating here is well conveyed in [Mr. Hubbard's Study Technology](http://www.appliedscholastics.org/results.html), which I highly recommend for all educators and students.)

> **Comments:**
> **username_27**: Oh yes, I remember that story of Mel. Is a cute story but code like that is fundamentally unmaintainable, which the story also shows. Real software can't work like that because (unethical or not) change requests come in and you can't just add a new feature to golf'ed code.  

---

### Answer by username_14 on 2017-07-16. Score: 9

As someone who learned to program with ruby, I think that the concept of how a reference to an object works under the hood is vital. Having the knowledge that "under the hood" my variables may be represented as pointers to values makes certain things much easier to understand. For example, in ruby:
a = Object.new
b = a.clone
c = a
c == b #=> false
c == a #=> true

Behavior like this could be seen as mind boggling: Why are 2 empty Objects the same, but the other 2 are not? But when given the conceptual knowledge that a pointer is a reference to a value this can be understood because a and c both point to the same Object in memory, while b points to a different object. Thus they have different Object IDs (a.object_id == b.object_id #=> false) and:
# Define a setter and getter for the test variable
a.instance_exec { def self.test; @test; end; def self.test=(new_val); @test=new_val; end }
a.test = "Foo"
c.test == "Foo" #=> true
b.test == "Foo" #=> NoMethodError

In summary, I think that it's very important to include the concept of what a pointer is in the class, but there's no need to go into the down and dirty details unless the students will actually have to work with pointers.
The basics of what a pointer is (an integer memory address) should still be mentioned, because that gives basis to the otherwise abstract concept of a "reference". Students tend to find it useful to actually understand what's going on in hardware in that case.

> **Comments:**
> **username_31**: This doesn't require knowledge of pointers.  It's rather easy to explain to students that you can have two different objects that are identical, but are just copies of each other.  That way, `Object.new` creates a new, identical function reference.  (Which, incidentally, is basically how Java does it)  
> **username_31**: I wasn't saying that we are copying function references.  Rather that they are "copies" (meaning that they look identical).  That said, "duplicates" is likely a better word.  
> **username_32**: How would the explanation be harder to understand if we said "*this can be understood because `a` and `c` both **reference** the same Object in memory, while `b` **references** a different object*"?  
> **username_33**: While I love Ruby and hence any mention of it in an answer, it has no pointers, only references. So not the right answer for the question at hand.  
> **username_34**: There's nothing "under the hood" in your example.  You merely are illustrating the difference between Ruby objects and Ruby variables.  
> **username_34**: Re, "Why are 2 empty Objects the same, but the other 2 are not?"  There's no "other 2" in your example:  It only creates two objects.  `a`, `b`, and `c` are _not_ objects.  They are _variables_.  They _refer to_ objects, and in particular, `a` and `c` refer to the same object, while `b` refers to a different object.  

---

### Answer by username_26 on 2017-07-17. Score: 8

No, you don't need to talk about pointers in an introductory Java class. You should talk about **references**, but even then you should keep it at a very high level.

The best tutorial on references I've seen is [Cup Size -- a story about variables](http://www.javaranch.com/campfire/StoryCups.jsp) and its follow up [Pass-by-Value Please](http://javaranch.com/campfire/StoryPassBy.jsp). These talk about variables as cups that can hold different items, and references as remote controls that you can put in a cup. You can have two remote controls in two cups that control the same TV, and replacing one of the remote controls with another one that controls a different TV doesn't affect the first TV at all. This also clears up the misconception that Java is "pass-by-reference for objects" when in fact Java is always pass-by-value.

I think this kind of high-level language is what you should be using. You shouldn't get into the low-level details, and you shouldn't even use the word *pointer* at all.

> **Comments:**
> **username_19**: I love those stories! I can imagine bringing various Starbucks cups into class for a physical demonstration.... welcome to [cseducators.se]. I hope we hear more from you in the future!  

---

### Answer by username_38 on 2017-07-17. Score: 7

I think you're asking the wrong question. In my opinion the right questions are:

1. Is it important to teach pointers at some point in the curriculum?
2. If so, which courses in the curriculum are most suitable for teaching them? (Plural to cover cases where some of the courses are optional, or where students may not grasp the concept the first time and may need reinforcement later).
3. Are there any courses which are taught earlier and which will suffer from students not understanding them?

I think it should be self-evident that pointers don't need to be taught in the first programming course: if it isn't, then consider that the first course may use e.g. Haskell, and it would be crazy to try teaching pointers using Haskell. (Of course, if the first programming course uses C then question 3 becomes relevant).

But a stronger statement can be made: it may be that the best course to teach them isn't a programming course at all. If pointers were mentioned at all in the university CS course I studied then it was either in *Computer Architecture* or *Comparative Programming Languages* (probably in the lecture on BCPL).

Question 1 is something that we can debate without additional context. But we can't answer questions 2 and 3 unless you supply considerably more detail about the curriculum. And since the question posed is really a subquestion of questions 2 and 3, I don't think we can give you a useful answer to the question as stated.

> **Comments:**
> **username_0**: Yes, I was asking about the first course only. And agree with your comments. +1  

---

### Answer by username_39 on 2017-07-16. Score: 6

Pointers as used in C and C++ are a fairly specific implementation of a general concept. The details of that particular implementation are mostly irrelevant--even to people using C and/or C++, many of the details are generally irrelevant.

The general concept is indirection (and dereferencing). Indirection arises in many forms; pointers are one version of it--but so are (for only one example) foreign keys in a SQL database.

The strength (and weakness) of pointers in C and C++ is that they're a relatively general implementation of indirection. On one hand, this means that when a student has learned them, most other (more restricted) forms of indirection are fairly easy and straightforward to deal with. On the other hand, it also means that they're a fairly daunting problem for many people approaching indirection for the first time. Pointers in C and C++ are also (for one example) a common place in which the pre- and post-increment and -decrement operators are used--so when students are supposed to be learning about indirection, it's easy for them to get side-tracked into truly ugly details about the degree to which C and C++ specify (and more to the point, mostly *don't* specify) sequencing of these operations.

Personally, I think I got somewhat lucky in my timing in learning about such things. The first language in which I was exposed to pointers was Pascal. It had (still has, for the relatively few who still use it) a relatively clean implementation of indirection. You can dynamically allocate an object, and what you get back is a pointer. You can then dereference that pointer to get to the object you allocated. You can do things like assigning and passing pointers as parameters--but that's pretty much it. You don't get into a lot of other details about things like pointer arithmetic that are fairly central to C, but basically irrelevant to the core concept of indirection.

Java, of course, is a poor choice of vehicles for teaching this concept (or much of anything else, but I digress). It attempts to hide the concept of indirection, which makes it more difficult to teach. At the same time, what it provides is (at best) an extremely leaky abstraction. A language that claims it doesn't use pointers, but does use `NullPointerException`s leads to confusion, not enlightenment.

Given that you're apparently already using Java, perhaps it wouldn't be too much of a stretch to provide your students with at least a little exposure to Clojure. This will let you do at least a little exploration of indirection without getting into a lot of ugly details about C and C++ that are difficult to avoid, but irrelevant to the underlying concept.

> **Comments:**
> **username_14**: Hi Jerry! Welcome to [cseducators.se]! Thanks for this very interesting answer! I hope to see you around, doing more asking or answering!  
> **username_27**: IMO a null reference exception is pretty easy to understand "You tried to use an object that didn't exist." That is, you *declared* it but you didn't *define* it. Pointers let you do god awful things like `int val = *somoeObj; val++; Object foo = &val` No really. Why would you do that. Why would you EVER BE ALLOWED TO DO THAT.  
> **username_28**: @Draco18s, I wonder if you saw [my answer](https://cseducators.stackexchange.com/a/2737/1103)?  :)  I would enjoy listening to a conversation between you and Mel.  
> **username_27**: @username_28 I have now, and I can respect that opinion. Not sure how much I agree (at least half?)  

---

### Answer by username_30 on 2017-07-17. Score: 4

Maybe you are thinking about memory management and pointer arithmetics. There is no need for that in the first course.

However I think that it is important to teach students that in Java object are created on heap and you have named pointers (which they call references) that you pass by value when you call a method (similarity with C language).

So Java does have pointers. What Java lacks, is pointer arithmetic.
For example if you define an object like this: `Integer pointsToAnInt = 5` that will create a pointer 'pointsToAnInt' to a location in memory that contains number 5.

If you say `pointsToAnInt = null;` and then call `pointsToAnInt.intValue();` you will get **`NullPointerException`** because that **pointer** points to null.

From the Java language specification:
[Chapter 4. Types, Values, and Variables](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html)

> An object is a class instance or an array. The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

So for marketing reasons Java didn't mention pointers and they called them references but essentially you use pointers and you can get `NullPointerException`.

On the other hand C++ can pass values by references which Java cannot because [Java is pass by value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). So references should be something different but in Java a reference to an object is just a pointer to that object and you pass that pointer by value through stack while objects are created on heap and they are garbage collected when there are no more pointers that point to them.

**Edit:**
By using `sun.misc.Unsafe` you can convert an int to an arbitrary address of an entity. In that case you can also have pointer arithmetic. In my personal experience telling people that Java does not have pointers did a great damage to understanding Java and introduced confusion among people to think that Java is pass-by-reference.

In C# you can pass by reference with `ref` keyword so you can make a swap function that you cannot make in Java `static void SwapStrings(ref string s1, ref string s2)`. If you omit keyword `ref` then you get the same behavior like in Java and that is **pass by value**.

> **Comments:**
> **username_25**: If you read my answer you'll see I disagree with that answer about Java and pass-by-value (for object types). It's not worth arguing though because it's just saying the same thing two different ways.  
> **username_25**: Oh, and welcome to [Computer Science Educators](https://cseducators.stackexchange.com)! (I'm almost as new, am I qualified to say that?)  
> **username_19**: @username_25 You certainly are :)  I hope we see more of both of you.  
> **username_30**: Hi username_25, thank you for your comment. I posted my answer to add additional things to your answer because I don't have enough reputation points to post a comments on other people's answers. Anyways you could copy from my answer a link to Java Language Specification where it says that references are pointers to objects. All the best.  
> **username_30**: username_25, in C# you can pass by reference with `ref` keyword so you can make a swap function that you cannot make in Java `static void SwapStrings(ref string s1, ref string s2)` . If you omit keyword ref then you get the same behavior like in Java and that is pass by value. If you think that it is pass by reference then how you call it when you use `ref` keyword in C#?  
> **username_12**: "you will get `NullPointerException` because that **pointer** points to null." You mean, because that pointer does not point to anything. (Hence asking for a thing that it points to raises an exception.) As confirmed by the quote you put after that statement--"a special null reference, which refers to no object".  
> **username_30**: The value of pointer is usually zero (meaning null) in most implementations. That represents null value that indicates that the pointer does not refer to a valid object. That pointer is called Null pointer/reference or some people call it null object pointer. Function pointer is a pounter that points to a function. Data pointer is a pointer that points to some data. In a similar manner Null pointer is a pointer that points to null value. Maybe you don't use the same syntax/wording, but semantic is the same and we think about the same thing.  
> **username_30**: "Does not point to anything" for you is the same as "points to null value" for me. I am not a native English speaker so I guess that formally you are correct. But it is important that people understand what I mean. I guess that I failed in that regard :(  

---

### Answer by username_20 on 2017-07-17. Score: 4

Here is what it is important to know early.

1. Primitive type variables store their value directly (I say: "Primitive types point directly at their values.")
2. Object type variables store the *location* of their objects in memory. I say: "Object variables know *where* their object is in memory.
3. Java is a strictly pass-by-value language in this sense: functions get a *copy* of the value stored by the variable passed them.
4. If you pass a variable pointing at a mutable object to a function, and the function changes that object's state (e.g. remove an item from an ArrayList), the object itself is changed. Why? Because you passed that object's location in memory to the function and the callee used a mutator method on that object. BANG! Object state is changed.
5. In reference to the last item, you can treat variables pointing to primitive types as if they were pointing at immutable objects, since a copy of the variable's value is made and the original cannot be changed.

Knowing these things early saves a lot of confusion.


---

### Answer by username_40 on 2017-07-18. Score: 3

No. Java and Smalltalk were designed as true object oriented languages. Bjarne Stroustrup who defined and wrote the C++ programming language also had the goal of object orientation but had to carry the baggage of the procedural and scripted C programming language due to the installed user base. If he had gotten rid of pointers and other ool polluters, it would have involved a much greater overhaul of the compilers.

The compilers are the main workload when designing a new programming language since you have to write a customized compiler for each hardware and OS platform, which is very non-trivial.

I would avoid teaching not just pointers but all OOL polluters for the following reasons:

Times have changed and your students may be beginners now, but eventually they will be writing code to perform:

writing classes for inheritable exception handling, remember for each feature of a program, you have to typically write 5 - 10 exception handling classes. Well designed software would handle errors so well that they would be invisible to the user. When things do go wrong, an analyst will have a much easier time with inheritable and extendable exception classes.

Object design for artificial intelligence

Both of the above require pure knowledge of OOL. Pointers would just confuse them.

You can teach pointers to a hacking class.

> **Comments:**
> **username_19**: Welcome to [cseducators.se]! Nice insights here.  

---

### Answer by username_41 on 2017-07-19. Score: 3

This is a tricky issue and where I think using a bit of formal semantics may help. Of course you don't want to introduce Greek letters and inference rules for undergrads but the concepts should be laid out clearly.

The most important thing I do early when presenting a programming language is to distinguish between syntax (how you write) and semantics (how things run. I later divide it into static semantics --typing-- and dynamic semantics). So here, as others have said, introducing *pointers* is not a good thing and goes against the spirit of Java (pointers don't exist). *But* you should present something namely what a *value* is in Java. The notion of value is fundamental. What is the result when a particular piece of code (syntax) is evaluated.

In Java constants of primitive types are their own values, but Objects on the other hand evaluate to a unique identity (whether you want to say that this identity is the memory address depends on your students and their backgrounds). It's a bit abstract but it allows you to explain several behaviours of the language. For instance, if you pass an object as argument to a method and perform mutation, the object is mutated (although the language is "call by value", since the value of the object is its unique ID, the modification occur on this particular object, not a copy). Conversely, even if you create two instances of the same class with the same internal content (say `Point p1 = new Point(0,0)` and `Point p2 = new Point(0,0)`) both objects will compare unequal (with `==`).
Which then allows you to also introduce why you should compare String object with .equals and so on.

The fact that some languages allow to manipulate this unique identity (pointers, pointer arithmetic etc…) is orthogonal, and imho should not be used to justify the behaviour of Java. It can certainly help as an analogy if the students have prior background in C/C++ but introducing a foreign low-level concept is not way to go.

In summary, you should not introduce pointers *but* this is not an excuse to not to explain precisely what is going on (call by value semantics with value being unique identities for Objects).


---

### Answer by username_42 on 2017-07-16. Score: 3

As someone who is self-taught with Python, I'd say it depends on where your students are at. If they're beginning students - no, I don't think you need too. But as your students advance, it becomes a better idea. First, it's a good idea for programmers to understand multiple languages, including languages that use pointers. Second, the term is often thrown around on forums or in books - it's good to know the lingo. Finally, when I did learn the basics of what a pointer was, it was useful for understanding how memory worked - it's good to understand the basics of lower level actions the computer takes to make your program run.


---

### Answer by username_11 on 2017-07-19. Score: 2

Some people use the term "pointers" to describe Java references. References definitely do need to be described (though they should be called references rather than pointers). Fields, variables, and parameters of class type are often treated as though they hold instances, but they never actually do.

Reference-type variables can hold four different kinds of things:

1. A reference to an object *that will never change* (often an immutable type like `String`), which is used to encapsulate the contents thereof.
2. A unshared reference to an object, which could be mutable, used to encapsulate the contents thereof.
3. A reference to an object that is "owned" by the entity holding the reference, but which may also identified by references held by other entitites that don't own it.
4. A reference to an object that is "owned" by some other entity.

The Java language makes no distinction among these different categories of references, but one cannot reasonably expect to write code which is efficient and correct without knowing which category every reference belongs to. In the first two situations, code may treat a reference-type variable as though it holds the object identified thereby, but a programmer must know which of those two situations applies.

If field `arr` of some object holds a reference to an `int[]` containing {1,2,3}, and one wants `arr` to hold a reference to an array holding {1,2,4}, there are two ways of accomplishing that: change the third item of the `int[]`, or create a new `int[]` holding {1,2,4} and store a reference to that in `arr`. Either approach may be correct, but if one doesn't know into which category `arr` belongs, one won't know which approach to use.

> **Comments:**
> **username_12**: Putting words in quotes does not make clear the idiosyncratic meaning you intend but do not give.  
> **username_11**: @username_12: Are you talking about "owned"?  The idea there is that in cases where references to a mutable object are shared, only one entity--the "owner"--will hold a reference that it would be expected to use in any way it sees fit, and all other entities that hold references would be expected to use them only to perform actions on behalf of that "owner".  For example, if a GUI object that displays a list subscribes to an update event from an "observable list" object, that list object will need to hold a reference to a delegate which will in turn hold a reference to the GUI object.  
> **username_11**: The sole purpose of the delegate will be to invoke a method which was designated by the GUI object, on the GUI object, when it's necessary to notify it that the contents of the list have changed.  Calling that method will likely modify the GUI object, but the GUI object wouldn't be "owned" by the observable list object but instead by the GUI window/form object in which it appears.  
> **username_11**: @username_12: I didn't want to fall into the rabbit hole of trying to describe why entities might hold references to objects whose state they don't regard as their own, perhaps you might offer some idea how to convey that concept in more detail than just the term "own", but without getting bogged down?  

---

### Answer by username_13 on 2017-07-16. Score: 1

Learning pointers is not vital for learning Java, although references become very important once arrays or class instances are introduced given the importance between a reference type or a native type makes when cloning instances (shallow vs. deep copying), passing parameters into methods, or discussions regarding instance hash writing (needed for some of the ordered containers).

> **Comments:**
> **username_14**: Hi username_13! Welcome to [cseducators.se]! I hope to see you around, asking and answering.  

---

### Answer by username_15 on 2017-07-20. Score: 1

You need to teach about the references, regardless how you call them.
Even if you do not see the reference as a pointer, you absolutely need to explain what the reference is, as otherwise no student will understand the things going on behind 
a.x = 1;
b = a;
b.x = 2;
a.x == // WTF?

or, with arrays:
a[0] = 1;
b = a;
b[0] = 2;
a[0] == // WTF?

And it is really not the best idea just to keep secret from the students how the values would change. These cases are frequent in Java code, they are far from the corner cases nobody needs to care about.
And the reference is easiest to explain in terms "it is the address in computer memory". Maybe a reference is also something deeply fundamentally else but I still need to see the easier understandable explanation and, well ... it just is, unless we start talking abut the physical, virtual address, address translation, handles that need to be resolved into addresses and other advanced concepts.

> **Comments:**
> **username_16**: Welcome to [CSEducators.se]! Wow! This is a wonderful answer. I hope we'll be hearing more from you.  

---

### Answer by username_17 on 2021-02-03. Score: 1

The following sentence from JLS Section 4.3.1

> "The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object".

is sometimes exhibited as an "proof" that Java actually has pointers.

Putting it in context:

* Language specification documents are not the kind of material beginners are expected to learn programming from ;
* at the time (90's), "serious programmers" (the intended readers of language specifications) were probably familiar with mainstream programming languages of the time.

Before Java, most programming languages (C, C++, FORTRAN, Cobol, ...- counter-examples are SmallTalk and Lisp) shared the notion of a variable as a name for a memory chunk **containing** the binary representation of some information.

Java has some obvious similarities (syntax) with C++, but drastically differs on that notion : a variable refers to **a value** (of primitive type) or an object. An object is not *contained* in a variable.

So assigning an object in Java doesn't involve the duplication of that object.

It's a point to be stressed (heavily) when explaining Java to confused C++ programmers. And a simple way to do it is to say Java variables contain references, which are like **C++** pointers containing addresses of objects (and are magically de-referenced without a star).

But it's only a way to illustrate concepts of Java with a metaphor, borrowing from a different world. It only helps if you know C++ beforehand. Having to teach pointers first makes the thing more complicated.

The basic explanation is

* objects exist somewhere in the memory space,
* references indicate where they are,

---

Actually pointers are not a "very hard" subject (addresses as first class data). The beginner's difficulties come from the algorithmic side of linked data structures.


---

### Answer by username_18 on 2017-07-18. Score: 1

I think, no and yes. Students should know that somewhere in Memory lies an object with the values involved. They don't need to know that an internal representation is likely a memory address. Concepts that are alien to Java such as offsets and such can be ignored.

> **Comments:**
> **username_19**: Also, welcome to [cseducators.se]!  

---

### Answer by username_20 on 2021-02-21. Score: 1

This is too long to be a comment:

Java is a pass by value language. You must understand that what variables store in Java. Primitives store their values directly. Object types store heap memory addresses. In either case, when you pass that an argument to a function that argument is evaluated, and then it is assigned to the function's parameter and it behaves like a local variable.

So, if you are passing a variable to a function the evaluation process causes a copy of the bit pattern it is storing to be made. In the case of an object, that's a copy of the memory address. This is why I carefully explain the idea of memory address to my beginning programming students. Python operates similarly, but it has no primitive types. All Python data are objects stored on the heap.


---

