Search code examples
javac++language-switching

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.


Solution

    • 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.