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

14

7

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.

Drool answered 11/1, 2009 at 22:22 Comment(0)
S
15
  • 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.
Selfinterest answered 11/1, 2009 at 22:36 Comment(2)
Pass by reference / value is worth reading about: yoda.arachsys.com/java/passing.htmlMeteor
Note that Java 7 has the try-with-resources mechanism where you can write a class that integrates with it by implementing AutoCloseable.Handed
F
6

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.

Following answered 11/1, 2009 at 22:45 Comment(2)
can you please explain the type of circular references you can use in C++ but not in Java?Flannel
I will edit to clarify. What i was trying to say was that when I first started coding in java I started making circular references because I could not code procedurally. It is considered, as least by the developers that I know, bad form to make circular references.Following
N
5

Generics (instead of templates), specifically the way they were implemented using type erasure.

Nitza answered 11/1, 2009 at 22:39 Comment(0)
N
5

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

Nitza answered 11/1, 2009 at 23:22 Comment(1)
Second this. This a great little book that is written to answer the questions you have (pitfalls, gotchas and best practices).Avelar
S
5

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?!?!?  */
Susurrant answered 24/2, 2010 at 23:53 Comment(1)
I imagine that a C programmer is one of the most equipped to understand this, given their intimate relationship with pointers and reference values.Fording
S
4
  • 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.
Soule answered 12/1, 2009 at 1:18 Comment(1)
Plus: no option to 'pass by value' for objects.Hackathorn
D
3

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

Dipnoan answered 11/1, 2009 at 22:27 Comment(0)
C
2

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.

Coleman answered 11/1, 2009 at 23:0 Comment(0)
K
2

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

Kenneth answered 12/1, 2009 at 17:45 Comment(0)
C
2

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.
Crow answered 25/2, 2010 at 0:9 Comment(0)
L
1

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.

Laevo answered 11/1, 2009 at 23:32 Comment(0)
S
0

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.

Sublingual answered 12/1, 2009 at 1:7 Comment(0)
B
0

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.

Brainstorm answered 25/2, 2010 at 0:41 Comment(0)
G
0

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

Gibberish answered 25/10, 2013 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.