Does Java have pointers? if yes, how manipulate them? [duplicate] - java

This question already has answers here:
Does Java have pointers?
(12 answers)
Closed 9 years ago.
I am new to java and confused.
Does Java have pointers? if yes, how to manipulate them? how to perform operations like ptr++ etc?

Yes, java has pointers and they call them references.
But reference manipulation is not possible in java. That is, you can not do ref++ and things like that.
You can just allocate memory to an object and assign it to a reference, de-allocation too is done by garbage collector in JVM. So you are free of free.

Java doesn't have pointers, but you can make pointer manipulations with sun.misc.Unsafe: Java Magic. Part 4: sun.misc.Unsafe:
static Object shallowCopy(Object obj) {
long size = sizeOf(obj);
long start = toAddress(obj);
long address = getUnsafe().allocateMemory(size);
getUnsafe().copyMemory(start, address, size);
return fromAddress(address);
}
Though in my practice I have never wanted to do such things and they are considered a bad practice by community unless you're developing a super-fast library like Kryo.

You dont have pointers, or at least not how you are used to thed from C/C++/whatever. You have object references instead, but you cant ++ those.

The following examples are pointers set to reserved memory:
Object o = new Object();
int[] myInts = new int[32];
You can manipulate pointers like this:
Object myObject = otherObject;
...if both types match.
You cannot do pointer manipulation as you could in C, because these are usually dangerous operations. Java in general tries to reduce coding errors by disallowing dangerous operations as much as possible. In the beginning this feels restraining, but once you get to know Java and suddenly can write a whole page of code without a single bug, you understand why this is a core design of the language.

Related

Why there is no use of pointer concept in java? [duplicate]

This question already has answers here:
Does java really have pointers or not? [closed]
(9 answers)
Closed 9 years ago.
As we know that in c/c++ pointer concept are present and pointer concept is a very good one.Then, Why the java developers remove it and if we can't use in java the what is it's pros and cons.
Pointers are forbidden in managed languages by default to allow memory management to be opaque - for example, you can have a compacting garbage collector that moves objects closer together to free up larger blocks of free space and improve cache coherency, if there are no pointers. But if there are pointers, then every pointer would either need to be updated or become valid every garbage collection, which is infeasible.
(This is just one reason of course :) but an example of how allowing pointers drastically changes what your programming language can do )
In some managed languages, like C#, you can declare unsafe {} blocks, where you can used unmanaged memory and pointers, but only there.

Disadvantages of making Java objects immutable [duplicate]

This question already has answers here:
Downsides to immutable objects in Java? [closed]
(17 answers)
Closed 9 years ago.
An interviewer asked me about the disadvantages of making classes immutable. I gave an answer regarding the heap space that is occupied by immutable objects and how it brings down the performance of Java applications.
What are other disadvantages of making objects immutable in Java?
The disadvantage is that you must create a new object to change its "value". If your class is representing something that "changes" frequently, you'll create a lot of objects, putting load on the garbage collector.
You should also consider that it may be much more difficult to deserialize/materialize immutable objects, since it usually involves writing a class with no parameter-less constructor.
Lets take a BigInteger
BigInteger i1 = BigInteger.valueOf(1);
it has add method, but you cannot add 1 to it, it's immutable, so what you do is
BigInteger i2 = i1.add(i1);
that is, a new object is created each time, ie arithmetic with immutable BigInteger is very slow
If there is no application requirement that your object be mutable, there is no disadvantage to making it immutable and you should do so.
If there is an application requirement your object is mutable, then make it mutable.

Java: Find out memory size of object? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In Java, what is the best way to determine the size of an object?
In Actionscript I can usually just do:
var myVar:uint = 5;
getSize(myVar)
//outputs 4 bytes
How do I do this in Java?
If you turn off -XX:-UseTLAB you can check the Runtime.freeMemory() before and after. However in the case of local variables, they don't take space on the heap (as they use the stack) and you can't get it size.
However, an int is a 32-bit sign value and you can expect it will use 4-bytes (or more depending on the JVM and the stack alignment etc)
The sizeof in C++ is useful for pointer arithmetic. Since Java doesn't allow this, its isn't useful and possibly deliberately hidden to avoid developers worrying about low level details.
The only reason C had a sizeOf intrinsic (function? well something) was because they needed it for manual memory management and some pointer arithmetic stuff.
There's no need to have that in Java. Also how much memory an object takes up is completely implementation defined and can't be answered reliably, but you can try some statistics by allocating lots of the same object and averaging - this can work nicely if you observe some basic principles, but that's boring.
If we know some basics about our VM we can also just count memory, so for Hotspot:
2 words overhead per object
every object is 8byte aligned (i.e. you have to round up to the next multiple of 8)
at least 1 word for variables, i.e. even if you have an object without any variables we "waste" 1 word
Also you should know your language spec a bit, so that you understand why an inner class has 1 additional reference than is obvious and why a static inner class does not.
A bit of work, but then it's generally a rather useless thing to know - if you're that worried about memory, you shouldn't be using neither ActionScript nor Java but C/C++ - you may get identical performance in Java, but you'll generally use about a factor of 2 more memory while doing so...
I believe there is no direct way of doing this. #Peter Lawrey 's suggestion could be a close approximation. But, you cannot rely on calculating the object size by taking the difference between the available free memory before and after the Object buildup, as there could be lots of other allocations in background happening from other threads as well. Also, there could be a possibility that the garbage collector could fire up and free up some memory in between your opertions. Also specially, in a multithreaded environment relying in the memory difference is definitely not a solution.

How big is an Object? Why is there no sizeof? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
In Java, what is the best way to determine the size of an object?
sizeof java object
C has a sizeof operator, and it needs to have one, because the user has to manage calls to malloc, and because the size of primitive types (like long) is not standardized.
But in java cant we find the sizeof an object?
Also why java doesnot have sizeof operator or method?
You've kind of answered your own question, in c you manage memory in java the jvm does.
In c you're directly allocating the memory for the data structures you're storing (malloc) and so you often need to know the sizes of these things.
In java the memory system is largely abstracted away so you don't (usually) care you just call new and it'll do whatever it does and if different jvms do things differently the memory used by the classes you've declared may vary.
Sometimes it is useful to know how much memory your classes are taking up (say you're trying to reduce your memory footprint in a tightly constrained environment) but it's pretty rare that you'd need that sort of information at runtime.
Also why java doesnot have sizeof operator or method?
Answer #1 - because Java doesn't need this. In C, the sizeof operator is needed so that you can malloc objects of the right size, for doing certain kinds of pointer arithmetic, and so on. In Java, you don't need to (and can't) do those kinds of thing.
Answer #2 - the size of an object in Java is rather rubbery, and indeed can change through the lifetime of the object (at least, in some JVMs). Ergo, a sizeof operator would be problematic.
In c there is a lot of work with pointers. Programmer should manage memory by himself, so he should know the size of types. But in Java there is no manual memory management. JVM does all it, so no need in sizeof.
In C you have to manually manage memory usage, you stated as much in your question. Since you need to allocated space for an object and remove it, the sizeof operator is required to do this quickly and easily. In Java, memory management is taken care of by the JVM. You don't need to manually allocate and de-allocate memory so the sizeof operator isn't necessary.

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