Jan 26 2012

Java stuff that you should know:What are the differences between C++ and Java?

Category: English posts,Miscellaneous,TechnicalIuliana @ 16:48

Java vs. C++ Because somebody brought up this subject here I decided that this is the question I should answer next. I am a developer from the old generation,at least this is how we call it here in Romania. Turbo Pascal was my first, (red cheeks :D) then I learned C, C++, Php, Java and .Net. With Java and C++ I have had the longest and most stable relationships. So I think I am able to answer this one, though I have to mention that nowadays you could be asked to compare Java to other languages too.

Again this can considered to be a difficult question mostly because there are a lot of differences between these two languages. That’s why you want to start your answer with the differences that remove any doubt that you know both languages pretty well, and usually this means getting technical. This is the how I would answer this question:

  • Java is multi-threaded, C++ is not
  • In Java primitive and reference data types are always passed by value, C++ uses also references and pointers.
  • Java has no pointers, C++ does
  • Java has implicit memory management through garbage collector, in C++ memory management is explicit
  • Java does not allow operator overloading,  C++ does
  • Java does not need destructors, C++ does
  • Java does not have type struct and union, C++ does
  • In Java, types cannot be overridden, in C++ we can do that.
  • Java does not provide multiple inheritance using classes (or virtual inheritance), C++ does
  • In Java, arrays have fixed sizes and attempt to read from an index bigger that size -1, will cause an exception. In C++ attempt to read from an index bigger that size-1 might even succeed and the value returned is the current value stored int that memory block.
  • Java programming model is totally compatible with OOP programming. C++ also supports functional programming, procedural and template programming.
  • Java is a WORA/WORE – write once run anywhere/everywhere (any compatible JRE ) , C++ is a WOCA – write once compile anywhere
  • Java has built-in support for comment documentation
  • Java has no native support for unsigned arithmetic, C++ does. (Has anybody used that in C++, ever?)
  • In Java there is no need for scope resolution operator (::)

Of course there’s more, but this should be enough at an interview. Fell free to add anything you might consider important. As always I am eager to learn new stuff.

Tags: ,

11 Responses to “Java stuff that you should know:What are the differences between C++ and Java?

  1. b.m says:

    Iulia, you’re so wrong I don’t even know where to start. Lets go point by point:

    * Java is multi-threaded, C++ is not.

    The only “multi-threaded” support in Java is the synchronized/Object.* methods, the rest comes via classes that are part of the JRE or extension libraries. While C++ does not offer out of the box multi-threaded support, there are many libraries that do offer this support. Multi-threading might come as a surprise, but is a platform and not a language feature.

    * Java does not need destructors, C++ does

    You probably meant java does not _have_ destructors. Anywho Java has “finalize()” which is very-very close to a destructor, and since it doesn’t need destructors you’ll be amazed to see the try{ … } finally{ … } blocks for closing streams, thread locals, or generally anything that expires after a block. See the new “try” extensions on the Java 7, this might tell you that maybe, … just maybe, Java kinda needed destructors.

    * Java programming model is totally compatible with OOP programming. C++ also supports functional programming, procedural and template programming.

    This phrase above makes no sense whatsoever. Java also supports also functional programming (e.g. anonymous object calls), procedural (e.g. static methods on objects, static blocks, static variables, or generally static things :) ). You’re right that it doesn’t supports template programming.

    Continuing still I fail to see how C++ is NOT “totally compatible with OOP programming”. Is it missing something, like, I don’t know, objects?

    * Java has built-in support for comment documentation

    What the heck am I reading? This is a convention, is not by any means a language feature. You can have comment documentation in pretty much any decent programming language. It’s a tooling thing. You know, like the IDE, xdoclet, or whatever. Google “doxygen” for future references.

    * Java has no native support for unsigned arithmetic, C++ does. (Has anybody used that in C++, ever?)

    OMG! You do know that the type “char” in Java is unsigned, and last time I check you can do arithmetic on it, right? Furthermore, if you ever attempt to do bit level processing – might happen from time to time too, I don’t know … on embedded devices, network protocols, etc – the inability of the language to support byte level unsigned operations comes back and bytes you. I don’t know too many video codecs implemented in Java btw.

    * In Java there is no need for scope resolution operator (::)

    Because what, they use . (dot) for everything? Is this an argument? It turns out that you kinda need it, since if you want to call the “this” from the parent of an anonymous class, you end up writing something like: Foo.this.blah – I fail to see the difference on how this is better that the resolution operator. E.g. Foo::blah.

  2. Iuliana says:

    If you want to speak 30 minutes and bore the hell out of people at an interview you could say it like you said it. :) I prefer to say it short and only when asked elaborate and give examples.
    *Java has both language and standard library support for multi-threading. The synchronized keyword in Java provides simple and secure mutex locks to support multi-threaded applications, though synchronized sections have to be left in LIFO order. Java also provides robust and complex libraries for more advanced multi-threading synchronization. In C++ there is currently no defined memory model for multi-threading; however, third party libraries provide support roughly equivalent to that of Java; obvious difference being the non-uniformity of these C++ libraries.(Dear Wikipedia …)
    *Finalize is close to a destructor, but is not a destructor. Java does not need destructors, because any class inherits the finalize method from the Object class and you can put your clean up code in it’s overridden implementation.
    *Functional programming, anonymous objects… Let me think, you create an an anonymous object which contains a method … how is this functional programming? In what universe? On the static stuff, you’re quite right, I’ll investigate more. You could have also mentioned primitive types, since you touched this subject.
    *Java has built-in support for comment documentation – I did not say C++ does not have that. But, in Java there are some specially written comments /** … */ (which support html formatting) which can be stripped using javadoc application and packed up into a really pretty documentation.
    *Why would anyone ever add chars? Especially when the result is int.
    *In Java there is no need for scope resolution operator (::) … quote from b.m. “Because what, they use . (dot) for everything?” Exactly my dear WHATson! (get it? WHAT-son … :D)

    See it’s just a different point of view and way of explaining stuff.

  3. b.m says:

    You did read my post beside the WHATson part, right? Anyway, let me go over them again:

    * “Java has both language and standard library support for multi-threading. ” – this is what I said, restated with different words. You said: “Java is multi-threaded, C++ is not.” which is blatantly false.

    * “Finalize is close to a destructor, but is not a destructor. Java does not need destructors, …” – Now you simply restate what I said, but you give no argument in any way. Read again what I wrote. Java does need destructors or a similar concept and that’s why Java 7 has the new try() support, and why the try/finally pattern is so widely spread. You should almost not ever use finalize() btw.

    * “Let me think, you create an an anonymous object which contains a method … how is this functional programming? In what universe?” – You missed what functional programming really is. The idea is that you can send code as data, so Java does support functional programming via this approach. You’re not forced to use pointers to functions in order to have functional programming. Really. Even Java 8 adds now closures, that are… tadahh… simple objects. I’ll guess even then it won’t be functional programming to your reasoning, because they are anonymous objects with a method – obviously not functional enough. You still missed to present how C++ is NOT OOP compatible, while Java is, which was pretty much your original (wrong) statement.

    * “Java has built-in support for comment documentation ” – this is a convention, not, I repeat, not a language/platform feature. Javadoc is a tooling application, as such you have doxygen for C++ that surprise, also works on /** … */ with HTML formatting.

    * “Why would anyone ever add chars?” – this is just an ignorant comment. So I’ll answer with because. Get it? BECAUSE :P I can only guess it’s probably just to prove you’re wrong.

  4. skyrape says:

    Unele post-uri sunt in romana, altele in engleza, hm, OK!

    Nu programez in Java decat de cateva zile, dar in C++ de cativa ani si pot sa zic ca ai omis cateva chestii. Ca de exemplu
    1) faptul ca Java e Big Endian si trebuie sa faci jonglerii imense pentru a rasturna bitii unui float de exemplu
    2) Java intelege = ca assignment de referinta, dar la nivel de variabile de baza asta inseamna de fapt assignment de valoare. Asta inseamna ca n-o sa pot sa am pointeri la variabile de baza, ups !
    3) faptu ca identificatorul de acces nu are efect de cascada pentru urmatoarele variabile sau functii; e un pain in the butt cand convertesti cod din C++ sa pui la fiecare functie public/private/etc; nu stiu cui ii place asta.
    4) pentru clase private e ok sa ai 5 clase intr-un fisier, pentru una publica, e musai sa aibe acelasi nume cu fisieru si sa fie unica in fisier; mai vrea omu o enumerare pentru o clasa, musai un fisier nou… for only 3 lines like ? really ?

    Mi-au placut comment-urile elocvente facute de b m si subscriu la parerile lui despre lumea unsigned. Aplicatiile high performance sau cele care au nevoie de informatii la nivel de bytes/biti o sa aibe intotdeauna nevoie de unsigned types. In DirectX/OpenGL index-urile n-au niciodata nevoie sa fie signed si se pune problema, pentru un mesh care are intre 32767 si 65535 vertex-uri de ce sa folosesti UINT si sa-ti creasca bandwith-ul cu 100% ?

  5. Iuliana says:

    *In C++ there is currently no defined memory model for multi-threading; however, third party libraries provide support roughly equivalent to that of Java;

    *finalize() is a method not a destructor. A destructor has no return type declared (finalize has void, the “no-type” type ). A destructor has the same name with the class with ~ in front of it. The finalize method has basically the same purpose and that’s why there is no need for destructors in Java, because you have this method. Destructors have to be called explicitly, the finalize method does not. The Java 7 thing that you mentioned it’s called ARM and it’s core component it’s the AutoCloseable interface.

    *The anonymous classes allow indeed to simulate functional programming, but as long as the parameter given is an object and you call the method of that object OOP principles are respected. Do not talk to me about closures and other crap programmed to be implemented in Java 8, I really hope Oracle will realize the stupidity of turning Java in the second .Net by stealing everything from anywhere!

    skyrape – 4) I think they are planning to change that in Java 8.

  6. skyrape says:

    This is funny, tocmai am dat peste inca o diferenta subtila. In for-uri poti declara multiple variabile si pune incrementori/decrementori multipli dar mai mult de o conditie n-ai voie sa pui, genial ! Sunt sigur ca exista o explicatie logica pentru asta

  7. Iuliana says:

    Cuplează condițiile cu &&. E acelasi lucru cu condițiile cu “,” între ele din C++ și mult mai logic dacă stai să te gândești, pentru că bucla se execută cât timp c1&& …&& cn este evaluată ca true.

  8. b.m says:

    seaqxx, you’re threading argument is bogus, also the one for finalize() and also the one for closures. Basically fully your last post.

    To your credit though, I realized that “Java has built-in support for comment documentation” is true, but not relevant anymore. Yes javadoc is part of the platform, no is not part of the API, no it isn’t a “difference” from C++.

    Also very likely “Java has no native support for unsigned arithmetic” is also true. Even if you just copy/pasted this argument from somewhere (I assume most of them were not your original arguments).

  9. b.m says:

    skyrape

    1) faptul ca Java e Big Endian si trebuie sa faci jonglerii imense pentru a rasturna bitii unui float de exemplu
    Da și nu prea. Faci o clasă utilitară și ai terminat. E mai complicat, true. Pe de altă parte ia zi drept câte #ifdef-uri faci ca să îți meargă treaba cu float-ul independent de platformă?

    2) Java intelege = ca assignment de referinta, dar la nivel de variabile de baza asta inseamna de fapt assignment de valoare. Asta inseamna ca n-o sa pot sa am pointeri la variabile de baza, ups !
    Mai puțin dureros decât pare. Mai dureros e când ai array-uri de chestii că nu le poți aloca pe stivă, ci tot timpul ajung în heap. În java se merge mult pe wrappere (ai o clasă care îți încapsulează referința/metoda/etc). Pe de altă parte alocatorul de memorie din java (de la Oracle cel puțin) e ahead of its time, și se prinde uneori în funcție de scopul variabilelor să le aloce pe stack, deși le aloci cu new. În C++ întotdeauna ajung în heap. Personal prefer să le poți aloca și pe stack, dar dacă nu se poate, nu se poate :).

    3) faptu ca identificatorul de acces nu are efect de cascada pentru urmatoarele variabile sau functii; e un pain in the butt cand convertesti cod din C++ sa pui la fiecare functie public/private/etc; nu stiu cui ii place asta.
    Nu contează. Aș putea comenta de namespace-urile din C++ că trebuie să identezi de mori, dar din nou… nu contează.

    4) pentru clase private e ok sa ai 5 clase intr-un fisier, pentru una publica, e musai sa aibe acelasi nume cu fisieru si sa fie unica in fisier; mai vrea omu o enumerare pentru o clasa, musai un fisier nou… for only 3 lines like ? really ?
    Nu chiar. În Java poți avea clase interne – clasă în clasă – care pot fi exportate (public), vezi Map.Entry din java. Ideea e ca să ai clasele publice în fișiere distincte și să nu ai clase parțiale (conținut al aceleiași clase definite în 14 fișiere distincte). Idem convențiile de numire, package-urile (a se citi namespace-urile din C++) trebuie să se afle în foldere cu același nume. Not bad dacă mă întrebi pe mine.

  10. Iuliana says:

    Of course I copied/pasted everything. In fact I am not even a Java developer, I have never been to a Java interview for a developer position and passed. In fact they always hired me because I was pretty and gave me a lot of money to just sit at a desk and browse the internet for girly stuff.

  11. b.m says:

    It’s not how many interviews you’ve been to that matters, it’s the passes / total interviews that counts.

Leave a Reply