Is there a concept of "pointers" or "unsafe code" in Java? - java

Yesterday I was attending a talk by a CTO of a reputed European Company, and he told until recently he did not know that java has pointers. On confronting him he said he is absolutely sure about existence of pointers/unsafe code in java.

There's a class called sun.misc.Unsafe, that much is true. But it doesn't use pointers in Java code (because Java has no pointers, although I agree that java references are similar in concept), most of it is implemented using native code.
As I mentioned in the comments, this is not part of the public API and shouldn't be used by client code. However, you can see it at work when you look at the sources of the Atomic* classes in the java.util.concurrent.atomic package.

There are no pointers in Java, only safe references. Unfortunately your highly reputed CTO was wrong.
Unsafe code is integrated through JNI.
http://en.wikipedia.org/wiki/Java_Native_Interface

Java has pointers.
The confusion whether Java has pointers or not is strongly related to the discussion whether Java is call by reference or call by value.
Uninformed people think that Java has no pointers, and since a method can change an object that's passed in with the effects of this change vissible to the caller, they reason it must be call by reference.
This is not correct however.
What happens is that in Java pointers are passed by value. There are no other kinds of variables in Java for objects than pointer variables and there is no call by reference.
The "unsafe" story is quite something else. This normally is distinct from the question of whether Java has pointers or not. Java's pointers are safe; they point to objects and using the normal language constructs they can not be manipulated to point to arbitrary memory locations.
There is however JNI, but then native code does potentially unsafe things, not Java code.
There is also Real-time Java (jsr-1), where you absolutely can get access to specific memory locations in your system. This however is a very specific and rather rare version of Java that's mostly used for embedded purposes. If this was meant I guess it would have been explicitly mentioned.

Java has no pointers, only references to objects. A reference is similar to a pointer, because it points to a variable, an object, but you cannot view or edit the address memory of this reference, which you can do in C.
Another thing. In C, you can manage pointers with the referencing/dereferencing operation, putting a * first of the name of pointer. In Java, this operation, referencing/dereferencing, is completely absent, because it's totally automatic, hidden to the user.
Other info on Wikipedia and Oracle.

Pointer is the concept of pointing to the reference. In C and C++ you could access the pointer explicitly but in java we use reference to point the objects. For example If you are passing the an instance to a method, Its reference passing we know but ultimately pointer is passed. when you change state of the instance within the method it reflects when that instance is used after the completing the method call.
We use reference in java which is pointer with respect to JVM.
When we use new operator it create the instance in heap and returns the address to the reference its pointing.
I believe this would answer your question if not you could comment on my answer.

You can call native functions in Java (JNI), so in this sense you can use pointers. But other than that - no, there are no pointers in Java.

He may have a slight confusion with call-by-value and call-by-reference. If he comes from C, he may think that call-by-reference is equal to a pointer. Just a guess.

Related

Doesn't java have pointer? [duplicate]

My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?
Thanks :)
A reference is sort of like a pointer that you can't do arithmetic on... although it's more opaque. While the underlying bits may be an address in virtual memory, they don't have to be. They're just a way of getting to an object (or representing the null value). So while they're not exactly the same, if you're used to thinking of a pointer as "a way of identifying an object or navigating to it" (in some sense) then yes, those thoughts apply to references too.
Java doesn't have pointers as such (unlike, say, C# which has references and pointers - the latter being used in "unsafe" code).
The terms "reference" and "pointer" are basically equivalent. Much of the literature I've seen about the basics of Java claims that Java has no pointers. But if you try to use a null reference you get a NullPointerException. So it's all semantics.
(The real difference is, in C or C++ the term "pointer" strictly means an integer that happens to be the memory address of some data. Whereas in Java the term "reference" more closely matches the C++ "reference" concept. You can't work with the memory address directly even if you want to, but you use it the same way.)
Cat x = new Cat();
This line creates a Cat object in memory and stores a reference to it in x.
x now contains a reference to the Cat object, but if you were to do:
x = x + 1;
This would not give the next memory address like in C, but would give a compiler error. Java doesn't allow control to the reference or memory location.
If we think of references or pointers as a kind of means to access or handle the object in memory, they are much the same. However, they are different in terms of implementation. Following are the differences:
Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.
Pointers are less strongly typed and references are more strongly typed. By this I mean the code is much simple in case of references and slightly less formal in case of pointers. You need to make use of reinterpret_cast kind of things to use pointers casts and on the other hand, references support easy casts of the kind of primitive kind of casts in "C".
Pointers are unsafe and references are safe. If you have an option between the two select references. In languages like C#, you have this freedom.
Pointers exists in C/C++ and references exist in Java. Do not confuse references in C/C++ with references in Java. References in C/C++ is a kind of synonym used for the rvalue of a pointer in C/C++.
No, Java does not have pointers. The fundamental concepts in Java are "values" vs "references".
A reference is a pointer that you can't normally see the value of (i.e., the memory address). The only operations allowed are to set it (from another reference) and to reference through it to the referred-to object. It can be set from a reference-valued expression, such as the new operator, or from another reference (which is syntactically a simple reference-valued expression).
In terms of Java syntax - it's true, that Java doesn't have pointers, but to clarify situation - Java Runtime has pointers.
Every time GC occurs, there is a big chance, that your object stored in the heap will physically change it's memory address. This is achievable only by using what is really called Pointer. As you come from C++ world - you know reference restrictions. But it doesn't mean that JVM doesn't use references =).
For further information take a look at Ordinary Object Pointer
So, as you have brief understanding of core JVM memory management, you can consider Java Reference term as Pointer at runtime.
No, there is no pass by reference at all. Only pass by value, since the real Java method argument is a copy of Java Reference, therefore - another Pointer.
So, in syntax usage way - Java Reference is closer to C++ Reference, but in real Runtime world it's close to Pointer.
P.s. for more clarification it's better to read more articles about Ordinary Object Pointer or take a loot at oop.hpp.
As Java does not support pointers. It may appear that references are special kind of pointers. But we must note the key difference: with a pointer, we can point any address (which is actually a number slot in a memory). So, it is quite possible that with a pointer, we can point an invalid address also and then we may face surprises issues during runtime. But reference types will always
point to valid addresses or they will point to null.
pointer only contain the address but Reference does not contains address if we say frankly then
address of the object is assigned to the index or we say can hash code and case code is given to the reference variable if we will see the content of the reference variable it starts with class Name # and after it some Hexadecimal Code. These nos are not address it is a index value or hash code.
second point
we can not perform any Arithmetic operations on values the Content of reference value

Pointer Model that Java has over C++

The single biggest difference between Java and C/C++ is that Java has
a pointer model that eliminates the possibility of overwriting memory
and corrupting data.
This is a quote from a textbook. I always assumed that it was C++ that used pointers and not Java. Can someone please elaborate on this?
I would argue against ever using the word "pointer" in describing a Java program. I always say "object reference" (or just "reference") instead.
A pointer, in C or C++, identifies a location in the process's virtual address space, and the virtual address space basically is a giant, typeless array. Given a pointer, you can add an offset to it, and get a pointer to a different location in the array. Given two pointers, you can compute the offset between them.
You can't do any of that with Java object references. A Java object reference identifies an object on the heap. The address of that object can (and probably does) change from time to time, but it's identity always is unique.
You can't "add an offset" to an object reference and get a different object reference. It doesn't make any sense.
They both use pointers.
In C++, pointers are actual memory addresses, meaning you can use one (via pointer arithmetic) to identify arbitrary memory locations.
In Java, pointers are opaque: knowing the value of one doesn't give you any information about anything other than the object it is pointing to.
Javas "reference system" is its pointer system. They're basically pointers without the possibility of casting to an incompatible type. It also does not allow you to use pointer arithmetic and like C and C++ do. In C++ you can corrupt your data by:
class SomeClass {
private:
int a;
public:
SomeClass(int a): a(a) {}
};
Later you can corrupt an object of the class by basically doing this:
SomeClass victim(2);
unsigned char *hazardousPointer = (unsigned char *) &victim;
for (int i = 0; i < sizeof(SomeClass); i++)
hazardousPointer[i] = 0;
This piece of code just allowed us to violate the private access rights and allowed to change its state (it could be also const, that does not matter). This happened due to the fact that C/C++ pointers are just memory addresses which pretty much behave like integers with some restrictions. Furthermore hazardousPointer[i] is just C/C++ syntactic suggar for *(hazardousPointer + i) which is not the case with Java, where arrays are objects which can even be returned from methods and have their own methods.
Furthermore Java has a garbage collector which cares about memory leaks, where C++ relies on its system stack and wrappers or smart pointers.
C++ uses pointers/references and it's the programmers responsibility to acquire and release dynamic memory allocations.
Java also does internally but in order to keep track of memory java uses a reference count which is in most simplest terms the evil Garbage Collector!
Java hides the pointers from the programmer and C++ doesn't thus making C++ far more powerful, but also dangerous. With Java you cannot allocate user defined objects on the stack (only primitives like int...) but in C++ you can use new keyword to allocate a user defined object on the heap or on the stack.
In java everything is references. so you can create as many aliases of a variable and if you update any one of it, it will be reflected in all the alias variable.
On the other hand, C++ has pointers and references both.

What is the difference between a pointer and a reference variable in Java?

My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?
Thanks :)
A reference is sort of like a pointer that you can't do arithmetic on... although it's more opaque. While the underlying bits may be an address in virtual memory, they don't have to be. They're just a way of getting to an object (or representing the null value). So while they're not exactly the same, if you're used to thinking of a pointer as "a way of identifying an object or navigating to it" (in some sense) then yes, those thoughts apply to references too.
Java doesn't have pointers as such (unlike, say, C# which has references and pointers - the latter being used in "unsafe" code).
The terms "reference" and "pointer" are basically equivalent. Much of the literature I've seen about the basics of Java claims that Java has no pointers. But if you try to use a null reference you get a NullPointerException. So it's all semantics.
(The real difference is, in C or C++ the term "pointer" strictly means an integer that happens to be the memory address of some data. Whereas in Java the term "reference" more closely matches the C++ "reference" concept. You can't work with the memory address directly even if you want to, but you use it the same way.)
Cat x = new Cat();
This line creates a Cat object in memory and stores a reference to it in x.
x now contains a reference to the Cat object, but if you were to do:
x = x + 1;
This would not give the next memory address like in C, but would give a compiler error. Java doesn't allow control to the reference or memory location.
If we think of references or pointers as a kind of means to access or handle the object in memory, they are much the same. However, they are different in terms of implementation. Following are the differences:
Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.
Pointers are less strongly typed and references are more strongly typed. By this I mean the code is much simple in case of references and slightly less formal in case of pointers. You need to make use of reinterpret_cast kind of things to use pointers casts and on the other hand, references support easy casts of the kind of primitive kind of casts in "C".
Pointers are unsafe and references are safe. If you have an option between the two select references. In languages like C#, you have this freedom.
Pointers exists in C/C++ and references exist in Java. Do not confuse references in C/C++ with references in Java. References in C/C++ is a kind of synonym used for the rvalue of a pointer in C/C++.
No, Java does not have pointers. The fundamental concepts in Java are "values" vs "references".
A reference is a pointer that you can't normally see the value of (i.e., the memory address). The only operations allowed are to set it (from another reference) and to reference through it to the referred-to object. It can be set from a reference-valued expression, such as the new operator, or from another reference (which is syntactically a simple reference-valued expression).
In terms of Java syntax - it's true, that Java doesn't have pointers, but to clarify situation - Java Runtime has pointers.
Every time GC occurs, there is a big chance, that your object stored in the heap will physically change it's memory address. This is achievable only by using what is really called Pointer. As you come from C++ world - you know reference restrictions. But it doesn't mean that JVM doesn't use references =).
For further information take a look at Ordinary Object Pointer
So, as you have brief understanding of core JVM memory management, you can consider Java Reference term as Pointer at runtime.
No, there is no pass by reference at all. Only pass by value, since the real Java method argument is a copy of Java Reference, therefore - another Pointer.
So, in syntax usage way - Java Reference is closer to C++ Reference, but in real Runtime world it's close to Pointer.
P.s. for more clarification it's better to read more articles about Ordinary Object Pointer or take a loot at oop.hpp.
As Java does not support pointers. It may appear that references are special kind of pointers. But we must note the key difference: with a pointer, we can point any address (which is actually a number slot in a memory). So, it is quite possible that with a pointer, we can point an invalid address also and then we may face surprises issues during runtime. But reference types will always
point to valid addresses or they will point to null.
pointer only contain the address but Reference does not contains address if we say frankly then
address of the object is assigned to the index or we say can hash code and case code is given to the reference variable if we will see the content of the reference variable it starts with class Name # and after it some Hexadecimal Code. These nos are not address it is a index value or hash code.
second point
we can not perform any Arithmetic operations on values the Content of reference value

What's inside a reference variable in Java?

We know that the object reference variable holds bits that represent a way to access an object.
It doesn't hold the object itself, but it holds something like a pointer or an address.
I was going through the Head-First Java (2nd edition) book and in the book it is written (in Chapter 3, page 54) that
In Java we don't really know what is
inside a reference variable. We do
know that whatever it is, it
represents one and only one object.
And the JVM knows how to use the
reference to get to the object. -
I want to ask:
Do an object reference variable holds pointer, address or what?
How does JVM interpret that?
It's entirely up to the JVM to determine what goes inside a reference.
In the simplest case it would just be a pointer (i.e. an address). In more sophisticated cases, the VM may use different representations depending on the situation - for example, you may want to read the paper on "Compressed oops in HotSpot" to see how the HotSpot VM can avoid doubling the size of references in some (but not all) places when running as a 64-bit VM.
The important thing is that you should neither know nor care. As far as you're concerned as a programmer, it's just an opaque set of bits - its only purpose is to let you get to the object in question (or identify a null reference).
That's up to the JVM. A Java reference isn't guaranteed to have any semantics besides that you can access an object through it. Sunacle might do that differently to IBM as well.
In practice it may often be a pointer of some sort, though maybe not directly to the object since that can be moved by the GC.
It's entirely JVM specific. It may be an address, a pointer, or something more complicated. You don't have, or need, any harder guarantees than the fact that you can get an Object using the reference.
It's up to the JVM to decide exactly how the reference is implemented.
Having said that, any "sane" implementation would probably use either a direct pointer or some form of compressed pointer for performance reasons. I believe this applies to all current production JVMs.

What are some common Java pitfalls/gotchas for C++ programmer?

As the question says, what are some common/major issues that C++ programmers face when switching to Java? I am looking for some broad topic names or examples and day to day adjustments that engineers had to make. I can then go and do an in-depth reading on this.
I am specifically interested in opinions of engineers who have worked in C++ for years and had to work with Java but any pointers from others or even book recommendations are more than welcome.
In C++ you'd use destructors to clean up file descriptors, database connections and the like. The naive equivalent is to use finalizers. Don't. Ever.
Instead use this pattern:
OutputStream os;
try {
os = ...
// do stuff
} finally {
try { os.close(); } catch (Exception e) { }
}
You'll end up doing stuff like that a lot.
If you specify no access modifer, in Java the members are package-private by default, unlike C++ in which they are private. Package-private is an annoying access level meaning it's private but anything in the same package can access it too (which is an idiotic default access level imho);
There is no stack/heap separation. Everything is created on the heap (well, that's not strictly true but we'll pretend it is);
There is no pass-by-reference;
The equivalent to function pointers is anonymous interfaces.
My biggest hurdle crossing from C++ to Java was ditching procedural code. I was very used to tying all my objects together within procedures. Without procedural code in java, I made circular references everywhere. I had to learn how to call objects from objects without them being dependents of each other. It was the Biggest hurdle but the easiest to overcome.
Number 2 personal issue is documentation. JavaDoc is useful but to many java projects are under the misconception that all that is needed is the JavaDoc. I saw much better documentation in C++ projects. This may just be a personal preference for documentation outside of the code.
Number 3. There are in fact pointers in java, just no pointer arithmetic. In java they are called references. Don't think that you can ignore where things are pointing at, it will come back with a big bite.
== and .equals are not equal.
== will look at the pointer(reference) while .equals will look at the value that the reference is pointing at.
Generics (instead of templates), specifically the way they were implemented using type erasure.
Since you mention book recommendations, definitely read Effective Java, 2nd ed.—it addresses most of the pitfalls I've seen listed in the answers.
Creating a reference by accident when one was thinking of a copy constructor:
myClass me = new myClass();
myClass somebodyElse = me; /* A reference, not a value copied into an independent instance! */
somebodyElse.setPhoneNumber(5551234);
/* Hey... how come my phone doesn't work anymore?!?!? */
No multiple inheritance, and every class implicitly derives from java.lang.Object (which has a number of important methods you definitely have to know and understand)
You can have a sort of multiple inheritance by implementing interfaces
No operator overloading except for '+' (for Strings), and definitely none you can do yourself
No unsigned numerical types, except char, which shouldn't really be used as a numerical type. If you have to deal with unsigned types, you have to do a lot of casting and masking.
Strings are not null-terminated, instead they are based on char arrays and as such are immutable. As a consequence of this, building a long String by appending with += in a loop is O(n^2), so don't do it; use a StringBuilder instead.
Getting used to having a garbage collector. Not being able to rely on a destructor to clean up resources that the GC does not handle.
Everything is passed by value, because references are passed instead of objects.
No copy constructor, unless you have a need to clone. No assignment operator.
All methods are virtual by default, which is the opposite of C++.
Explicit language support for interfaces - pure virtual classes in C++.
It's all the little bitty syntax differences that got me. Lack of destructors.
On the other hand, being able to write a main for each class (immensely handy or testing) is real nice; after you get used to it, the structure and tricks available with jar files are real nice; the fact that the semantics are completely defined (eg, int is the same everywhere) is real nice.
My worst problem was keeping in mind the ownership of memory at all times. In C++, it's a necessary thing to do, and it creates some patterns in developer's mind that are hard to overcome. In Java, I can forget about it (to a very high degree, anyway), and this enables some algorithms and approaches that would be exceedingly awkward in C++.
There are no objects in Java, there are only references to objects. E.g :
MyClass myClass; // no object is created unlike C++.
But :
MyClass myClass = new MyClass(); // Now it is a valid java object reference.
The best book of Java "gotchas" that I've read is Java Puzzlers: Traps, Pitfalls, and Corner Cases. It's not specifically aimed at C++ developers, but it is full of examples of things you want to look out for.
Specifying a method parameter as final doesn't mean what you at first think it means
private void doSomething(final MyObject myObj){
...
myObj.setSomething("this will change the obj in the calling method too");
...
}
because java is pass by value it is doing what you're asking, just not immediately obvious unless you understand how java passes the value of the reference rather than the object.
Another notable one is the keyword final and const. Java defines the const as a reserved keyword but doesn't specify much of its usage. Also
object1=object2
doesn't copy the objects it changes the reference
All methods are virtual.
Parameterized types (generics) don't actually create code parameter-specific code (ie, List<String> uses the same bytecode as List<Object>; the compiler is the only thing that complains if you try to put an Integer in the former).
Varargs is easy.

Categories