See also WhenShouldWeUseCeePlusPlus and WhenShouldWeUseJava. ---- '''''Java is different from C++ because...''''' * They eliminated manual memory allocation and deallocation and added automatic GarbageCollection * They introduced true arrays and eliminated PointerArithmetic * They substantially reduced the possibility of confusing an assignment with a test for equality in a conditional (as in CompareConstantsFromTheLeft) * They eliminated MultipleInheritance, replacing it with a notion of ''interface'' derived from ObjectiveCee * No pre-processor, no include files, no macros (although it is possible to find preprocessor extensions for Java, for example http://www.google.com/search?q=java+preprocessor) * Mapping of fully-qualified ClassName''''''s to a directory and file structure. This means when the Java compiler needs to read in a specified class file, it always knows where to find it * Universal use of UniCode * Java strictly defines the size and signedness of its types. An int is always 32 bits. * Java's pointers can be compared for equality to another pointer or to null. * An object must be dynamically allocated on TheHeap * Arrays are FirstClass objects (yet notice the 'should' in JavaArraysShouldBeFirstClassObjects). * Language support for thread protection with the ''synchronized'' keyword * Built-in network awareness * Java forces you to deal with exceptions (see JavaExceptionHandling). * Java handles resource management automatically for memory only; other resources must be released explicitly each time they are used. '''''There are pros and cons to all of these, of course. Java and C++ fill somewhat different niches:''''' * With C++, you can control what version of build tools will run your compiler. This gives you a lot more control than Java, where you may not know which version of whose JavaVirtualMachine/JIT your code is going to have to work with. * Despite all that JIT stuff, C++ code is still much faster on average (this point is not so clear cut; discussion at IsJavaSlow). * C++ is standardized by a committee, and is not a political football (see CppStandard). * C++ makes at least an attempt to provide genericity with its "templates", which are, although horribly difficult to use, at least better than casting from "Object" all the time (see UsingTemplates). ''This has been improved in Java 1.5 with it's generic/parameterized types.'' * On a related vein, C++'s collection classes work at least with all basic types, no need for silly wrappers around "int" as if any half-semi-intelligent compiler couldn't provide them automatically. ''This has been improved in Java 1.5 with auto-boxing.'' * In C++, OperatorOverloading makes it possible to create custom types that behave like the built-in ones, whereas Java's built-in types are obviously God's last message to humankind, so they are set in stone. Of course, if you really want to fake your own class in C++ with an "int"-like protocol, you often end up overloading the assignment operator, the CopyConstructor, and a whole herd of assignment-like things like +=, -=, etc. * Integration with LegacyCode is far easier. Today, some CeeLanguage coders even bother to make their headers "CeePlusPlus safe". * Whereas C++'s standard lib doesn't handle things like GUI's and networking, it at least cares about basic functionality like formatting floating-point numbers. ''(Java has had java.text.DecimalFormat since forever, and printf since Java 1.5)'' * C++ has idioms for reliable resource management without need for explicit close/release methods, and treats memory the same as any other resource. ''You mean rely on object destruction instead of release? You could do that but if you did start using GC its likely that all the non-memory resources would be exhausted first, java doesn't have release()-less resources explicitly because it uses GC. You can write code in java so that there is no ''public'' release() on a resource though.'' 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 A''''''rrayIndexOutOfBoundsException'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 UnitTest''''''s 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 * Macros are good. Macros are our friends. The usual syntactic convention of making them all upper case is enough to direct the eye to the relevant definitions. Like any powerful feature of a language they can be abused, but they're very seldom a cause of any significant trouble. The only shame with macros is that, unlike typedefs, BjarneStroustrup doesn't like 'em and won't let 'em be scoped to a class. For shame! * Array boundaries are easily protected; SgiStl and most other modern STL implementations provide a debug-time bounds checking facility. Likewise most modern STLs will give you neat reference-counting pointer types, courtesy of operator-overloading, that prevent trouble. And anyway, who doesn't purify their code as a FunctionalTest? * Just like macros, operator overloading is good. It's our friend. It lets us put good syntactic sugar in our code. It's even easier to abuse, but that's what ProjectStandards prevent. * Unions and typecasts ... well, okay, you got me there. Language warts. Necessary on occasion because of assymetries inherited from C. But minimize and encapsulate their usage, and they're no trouble either. 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...'' ---- DeviceDriver''''''s. 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