Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
omermuhammed Avatar asked Jan 11 '09 22:01

omermuhammed


3 Answers

  • 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.
like image 194
cletus Avatar answered Nov 16 '22 22:11

cletus


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.

like image 35
WolfmanDragon Avatar answered Nov 17 '22 00:11

WolfmanDragon


Since you mention book recommendations, definitely read Effective Java, 2nd ed.—it addresses most of the pitfalls I've seen listed in the answers.

like image 24
Hank Gay Avatar answered Nov 17 '22 00:11

Hank Gay