Java Vs Cpp

See also WhenShouldWeUseCeePlusPlus and WhenShouldWeUseJava.


Java is different from C++ because... There are pros and cons to all of these, of course. Java and C++ fill somewhat different niches:

The moral of the story: Java and C++ both suck. Please use a RealLanguage. ;-)


Car Analogy

Using C++ over Java is analogous to driving a manual car over an automatic one for car racing. A manual car is used because it has more control to make tighter turns to go faster, similarly C++ has more lower and finer level of control and can run much faster than Java. Its much more easier to use Automatic for the purposes to get to the final destination, similarly using Java can develop higher level applications much more easily. One can easily misuse a manual car compared to an automatic one just as you can easily crash in C++.

Java provides garbage collection; C++ must account for all objects created/destroyed. Although, it's much easier to forget objects, it adds overhead of tracking objects, costing the software in size and memory.

Objects are referenced in Java where C++ has in addition pointers and value objects. Simplifying to have all referencing makes things easier but altogether passing by references, pointers and values are still valid and can be more convenient. Pointers can be much faster than references generally as it has little overhead especially when it is scaled. This is a confusing mishmash of potentially wrong information. Java "references" are much more analgous to pointers than CeePlusPlus's references. "Value objects" have nothing to do with pointers or references, it's an OO pattern (ValueObject). "Pointers can be faster than references" isn't true in any case that I know of, because a pointer must be de-referenced before it can become a reference.

Java has simple single inheritance with multiple interfacing whereas C++ has multiple inheritance. It can resolve some problems of multiple inheritance and dilute the complexity, but multiple inheritance can still be more appropriate.

I enjoy and drive a 4x4 C++ but sometimes prefer to cruise along in a brand new Java. What type of vehicle do you prefer?


Having significant OOA/OOD experience I still choose Java over C++ because it makes me much more productive and lets me write safer, more bug-free code faster. In the cases where I don't need the speed and generic programming, it's a great choice. Its true that Java can't transform a bodge-job into a good project but that the facts that it forces you to deal with exceptions for instance and checks things like array bounds and forces you to think and write OO code make you write better programs. Is it the savior and the end-all of computer languages as Sun promotes? No. But one must separate Sun's hype from the reality. And the reality I've seen is projects written with Java instead of C++ are developed on the order of 4-5 times faster and have less errors. -- AnonymousDonor (...and EvilCppBigot?, when he's being honest.)

All this can be fixed with AlternateHardAndSoftLayers. A balanced combination of python and C++ will go at least as fast as a java development. -- PeterMerel


I know C++ pretty well (or did) and Java a little. I too would choose Java over C++ in a second. You're right, people can write bad code in any language, and many of them will. That's why there are opportunities out there for guys like you who know how to make things work. -- RonJeffries

Thanks

The more I know about both languages (which is not much, given my limited experience), the more JavaVsCpp feels like ApplesVsOranges? to me, despite the similar syntax. -- FalkBruegmann

As a programmer, I prefer to use C++; it gives me great power and control. As a project manager, I prefer Java, as it's easier to get skilled developers and harder to shoot yourself in the foot. -- JeffGrigg

As a programmer, I prefer to use Java, for exactly the same reason: C++ gives me great power and control; But it also makes me pause more often and deliberate on the non-essential things. C++'s power is like carrying a cannon - very powerful, but rarely usable... I'd rather carry a swiss-army knife (Java) - does all the routine stuff quickly, and fits in my pocket. -- ArnonKlein


ApplesVsOranges? it most definitely is! The comparison is over simplified. Example: "They eliminated manual memory allocation and deallocation" - is this a good or bad thing? If you answered good - you're wrong, if you answered bad - you're wrong. It just isn't that simple. You have to decide these things on a case by case basis, which C++ does allow BTW (not so much allow as require). The comparison implies that OO is always good, and other paradigms are always bad. If you think this, I would suggest you break out of your OO tunnel-vision, and read a few more books.

And start using AdaLanguage, since that's the only language (AFAIK) that allows and encourages you to use GarbageCollection, but doesn't require you when it is inappropriate!

As does ModulaThree, and the language spec's only 50 pages. ;-) SteveFreeman

Why is CppBashing so popular these days - especially amongst OO/Java people. What goes around comes around, how many times would one hear "oh, that _interpreted_ language? ha!" not-so-many years ago?

There was an argument on this page about ObjectOrientedPurity, which someone else deleted. So I'm adding in a page about that.
"Java. The elegant simplicity of C++; the blazing speed of Smalltalk." -- JanSteinman
"Java is C++ without the C." Attribution unknown - I first heard it from MichaelDonnelly?. -- WayneConrad
If reading the paragraphs I've written below, note that mostly I've written a lot of Java code, and continue to do so - as a *language*, Java is weaker than C++, but as a framework it's stronger. The real considerations when choosing between Java and C++ for a project are nothing to do with the language features as such: stability of specifications (favours C++), availability of tools (probably now favours Java for many situations, but C++ for others), availability of competent developers (I don't know which way that goes), internal politics (CTOs are more likely to feel comfortable with the marketing-driven Java for some reason), and of course, irrational opinions. That said...

"Java has no pointers" is untrue in any real sense. User-defined types in Java can be accessed via pointers only, never by value. NullPointerException's name gives the game away. Java does not have arithmetic operations defined for pointers, which does avoid a large class of common C/C++ errors, but C++ has value semantics for UDTs, which avoids a large class of common Java errors (as well as often helping performance).

"Java forces you to deal with exceptions" is somewhat true, but misleading. The most common exception to plague Java code is a NullPointerException (because Java lacks a way to express within the type system the non-null nature of a pointer, whereas C++ can express it just fine), and NullPointerException is one of the many exceptions which are "unchecked" in Java. Others include array bounds violations; in general, Java pushes checking off to run-time where C++ prefers to do it at compile time. One exception is that C++ doesn't do much compile-time checking of exception specifications, but Java doesn't do it in most of the important cases either. -- JamesDennett

Usually, NullPointerException isn't common: either your objects are expected to be null, and you can simply check it without exceptions (if(foo==null){...}), or your code is flaky or untrusted and you need a condom around it.

Yes, not checking NullPointerException and the other RuntimeException's is a good feature to have around. You shouldn't always need to write code that expects ArrayIndexOutOfBoundsException's. Every method that accessed an array would have to declare (or catch) it.
This LanguagePissingMatch stuff is worthless. Both Java and C++ are excellent languages (as is C#, Smalltalk, and others) that each have very distinct and different roles in someone's toolbox. -- sg


You People should not forget, that Java is a _platform_, same as Win32 or Linux or Mac. Java, that people generally relate to, is a programming language, a platform, and a big class library. Java was introduced with tremendous marketing efforts, and obviously a lot of people have fun programming it. So it all comes down to the decision whether your solution has to run on the Java platform, so you use the Java language. Java has a stronghold on the serverside lately, J2EE seems to take over very fast, and for me, when thinking of web-apps, I think about the Java platform and its advantages. The argument about Javas class libraries and its richness is quite an odd one, since a C++ user basically can use *any* API he wants to, from C to real C++ libs. So, it's nice to have a standard GUI, but on the other hand, how many GUIs are there for the Java platform in comparison to the GUIs available for a C++ Developer?

The biggest advantage of java is the stability of the runtime (I know it leaks every now and then) and the ability to find a lot of developers quickly that can communicate on a same level.

The biggest disadvantage is the platform itself, and the limitations of real-life problems I can solve and real-life products I can sell on the java platform.

C++ obviously has to be backward compatible all the time. Just look at how much code on your desktop is C or C++.

Use whatever language that solves your problem best!

-- Amanjit Gill


Beauty lies in the eyes of the beholder. It matters how you use Java. Any language is a beautiful, marvellous creation of genius and allegorical brilliance, and just like a plastic toy can be destroyed or well-used by a baby, it is the acumen of the user/programmer/developer to make the flexibilty of the language. So, in my opinion, C++ and Java are having equal grades and so is any language.

You've never coded in intercal, have you?

-- RaviShankar

Pro-Java:

While CeePlusPlus enjoyed a (fortunately) brief period of ascendency during the period between the peak of its MarketingHype? and the later widespread awareness of its PragmaticReality?, CeePlusPlus is now being largely superseded by the JavaLanguage, also known in some quarters as SmalltalkMinusMinus.

A related effort was called ObjectiveCee (in WikiSpeak).

Pro-CeePlusPlus:

You go write a DeviceDriver in JavaLanguage and then come back and talk to us. There are many, many, many situations where C++ is a fine choice of language, and a better choice than JavaLanguage. Hell, there are very few situations where JavaLanguage is an adequate choice. Inside Oracle ... wait, StoredProceduresAreFaster?. EJB ... maybe, if most of your target boxes aren't MicroSoft ... unlikely in most deployments. Cross-platform ... yeah, if you can find two JVMs that work the same way twice ... good luck. Applets ... ROTFL.


What most people think is that Java has to Run in a VM somehow running on top of an OS. Well, the aJile Microsystems aj100 microcontroller executes Java byte codes directly. It's microcode has some minor extensions for house keeping. The best part is that it does thread context switches in, drum roll please, less than 1micro-second (~800ns). So, heck yes, it does a fine job with DeviceDriver code, heck, that is what it is for.

What is missing is the fact that people still think that you need an OS to run your VM on to do Java. It just ain't so!

-- GreggWonderly
I know, I know, I'll calm down. you can do good work in JavaLanguage. But AllPanaceasBecomePoison, whether they're CeePlusPlus or anything else. HorsesForCourses. -- PeterMerel


Threads:

I would never write a DeviceDriver in JavaLanguage ... but neither would I write it in CeePlusPlus. Instead, I have written most of mine in plain C. -- TomStambaugh

Plain C is far more dangerous than Java or C++. Still, some mighty fine systems were built with it once. Perhaps if you CodeUnitTestFirst, none of the safety concerns are very relevant. Sure you can corrupt memory with C and its derivatives, but that's why debugging was invented. The main thing is to build enough UnitTests fast enough to make sure your system can grow faster than its bug-set.


C++ is just as dangerous as C! almost all truly useful tools can be dangerous.

C++ is more dangerous than C - and more useful.

C makes it easy to shoot yourself in the foot. C++ makes it easier to avoid shooting yourself in the foot, most of the time, but when something goes wrong, it blows your entire bloody leg off.

Who can verify the stored procedure speed comment above? I though I had just read something citing the significant speed advantage of stored procedures in Java as compared to the same in PL/SQ.

Yeah, I agree with the pro-Java dude. CeePlusPlus has things like text-based macros that write all over anything before it compiles. And it lets you walk off array boundaries, and it even defines the result in some circumstances. And it lets you overload operators and such to invent a little app-level language. And you can union or typecast anything into anything else as raw bits.

CeePlusPlus just gives too damn much freedom.

Freedom isn't a BadThing. Sometimes it's essential. Of course, CeePlusPlus isn't the perfect language for all applications, but then neither is Java or indeed anything else. -- BurkhardKloss

Typecasts are not warts, they are necessary for the tasks that C/C++ are designed for. Ok, C pointers confuse three different concept - language-level pointers, low level addresses and iterators - but the basic mechanisms are available in all system programming languages.

However, the best implementation of pointers vs addresses is that of Modula-3. One needs to import a specific module to be able to get and manipulate the low-level addresses of objects. Also, modules can be marked as safe or unsafe, depending on whether the API allows one to break the type system by using these low-level features.


LiveFreeOrDie

Slight discomfort before dishonor...


DeviceDrivers. Gotta love 'em. I've written them in Assembler, C, and C++ (oh, yes, also Forth).

Actually prefer assembler (oh, yes, and Forth).

Have used C for more (and more varied) drivers than I have assembler, but still, assembler is *the* driver language (oh, yes, along with Forth).

C++ (IMO) really wasn't made for driver stuff, although it acquits itself well in that context. I've done some multi-threaded stuff in it for serial and sockets data acquisition, and I could just have easily written that in C. However, when I had to write an XML DOM package, C++ began to make more sense.

The idea that an abstraction *must* be better than having pointers leans too much in the "protect silly programmers from their own shortcomings" direction.

It is my belief that you're not supposed to have unskilled programmers. Yes, give me a tool that can pull a bearing without forcing all the mechanics of that exercise on me, but don't hide all my drills, wrenches (spanners), and screwdrivers in the process.

-- GarryHamilton

The main problem with Java is that it enables automatic managament for memory, while making automatic managament for other resources practically impossible. See http://www.hackcraft.net/raii/

Not true! Locks are also cleaned up automatically using syncrhonized blocks.

Although, when it comes to system programming like device driver, C++ is must, I like structured and standard ways of dealing with string and other utility classes in java.


I don't know what it is about Java - it just feels too much like an interpreted language to me, due to the whole code to bytecode transformation. How is reading the bytecode really any different to reading the source? It's just like separating between reading human-readable codes and reading machine-readable code. Byte-code is called "machine independent", but machine independent code generated from one source requires that source to be machine independent too! In essence, unless there are levels of hardware which read the Java byte-code for themself (as someone mentioned above), it's practically an interpreted language. It just feels wrong to me. -- ArlenCuss?

How is reading the bytecode really any different to reading the source?

Try reading TheDragonBook, it may change your perspective...

Actually according to TheDragonBook (chapter 1.1) interpreter is a program that takes as input some source program and its input and executes it to produce output. So by this definition Java virtual machine is definitely an interpreter. Well, you save execution time because you don't do syntactic and lexical analysis, but no one said the compiler must do them either. -- YakovGalka?


CategoryJava CategoryCpp CategoryComparisons CategoryProgrammingLanguageComparisons

EditText of this page (last edited June 23, 2013) or FindPage with title or text search