🔒 Locked
Differences between Java and C++
Advertisement
Original Post
I consider myself a fairly experienced C++ programmer, with a good knowledge of the fundamentals and the techniques that should (theoretically) carry over pretty well to another language. Now I am being required to use Java for a computer science class I'm taking, and having never played with the language before, I thought I'd ask here for pitfalls to watch out for. I'm not looking for the things that are called out in the numerous "Java for C++ Developers" tutorials on the net, just stumbling blocks that have been encountered by real-world people. Thanks in advance, everybody. P.S. I also have some C# knowledge. I've heard they're similar?
Coding in java is nothing more than writing atrocious C++ code.
1. It encourages the use of 'new' without any considerations. Obviously, no 'delete's are necessary because of the garbage collection, but in C++, using heap memory is something you would typically want to avoid when you can use the stack.
2. There is no 'const'. This is one of the greatest features of C++.
3. Java templates are basically a poor hack of the C++ version.
4. All objects are automagically treated as references.
5. No operator overloading.
As far as pitfalls go, just be sure to bring a nose plug. When coding in java, you may find a hideous stench rising from your keyboard.
1. It encourages the use of 'new' without any considerations. Obviously, no 'delete's are necessary because of the garbage collection, but in C++, using heap memory is something you would typically want to avoid when you can use the stack.
2. There is no 'const'. This is one of the greatest features of C++.
3. Java templates are basically a poor hack of the C++ version.
4. All objects are automagically treated as references.
5. No operator overloading.
As far as pitfalls go, just be sure to bring a nose plug. When coding in java, you may find a hideous stench rising from your keyboard.
Watch out for multiple inheritance hierarchies that use inner classes or interfaces.......
Also keep in mind that JAVA treats boolean values differently from integer values(a very common mistake i used to make)...something like while(20)...; is a n invalid statement in JAVA but pretty natural if youre working on C++....
Also some class hierarchies may seem a bit illogical to you but keep in mind that JAVA stores classes separately....id advise you to google up anonymous inner classes and adapter classes .......also keep in mind that in JAVA objects are passed by reference to functions and not by value........
Also keep in mind that JAVA treats boolean values differently from integer values(a very common mistake i used to make)...something like while(20)...; is a n invalid statement in JAVA but pretty natural if youre working on C++....
Also some class hierarchies may seem a bit illogical to you but keep in mind that JAVA stores classes separately....id advise you to google up anonymous inner classes and adapter classes .......also keep in mind that in JAVA objects are passed by reference to functions and not by value........
Quote:
Original post by EmrldDrgn
I'm not looking for the things that are called out in the numerous "Java for C++ Developers" tutorials on the net, just stumbling blocks that have been encountered by real-world people.
The biggest difference that I've ever encountered between Java and C++ programming is the IDE. With C++ I can use Visual Studio and Visual Assist X. Visual Studio is an amazing IDE with a powerful debugger and while it certainly has its flaws, no other language boasts a better IDE.
With Java, you have NetBeans, which admittedly is reminiscence of Visual Studio, but I never cared for their setup. Then there is Eclipse, which is often toted as one of the main IDEs you should know for cross language development, but like NetBeans, quite a few things just seem naturally "backwards" there. That view of course, could be from having used the way Visual Studio organized and architectured its projects. There is also JCreator, which I personally loved because it was very simple, lean, and had some nice syntax highlighting features, auto-complete, documentation integration, etc...
It's been about 2 years since I've had to write Java code though, so those views above were from a few year of Java development. I'm sure there are more IDEs today and those mentioned have been upgraded quite a bit, but I can't remember how great the debugging systems were. I know I had to use a lot of console.out.printlns though haha!
Anyways, that was and certainly would be one of the biggest issues I'd say you can see going from any Windows C++ development to another language. You get so used to having certain features that when they are no longer there, you feel your productivity decrease.
One thing to look out for: No structs.
As in if you need a copy of a collection of data (which will usually be a class) you need to explicitely call clone on it.
This has bitten me more than once, when i had a collection of objects. I took one of them, modified it for local uses, but that also changed the object inside the collection.
C# has this very useful distinction, all objects behave like references, while structs are really copied on an assignment.
As in if you need a copy of a collection of data (which will usually be a class) you need to explicitely call clone on it.
This has bitten me more than once, when i had a collection of objects. I took one of them, modified it for local uses, but that also changed the object inside the collection.
C# has this very useful distinction, all objects behave like references, while structs are really copied on an assignment.
Most of what people said can be boiled down to this:
Everything is a primitive or an object. Objects are always references.
Remember that and most of the pitfalls go away.
Everything is a primitive or an object. Objects are always references.
Remember that and most of the pitfalls go away.
Quote:
Original post by WhatsUnderThere
Coding in java is nothing more than writing atrocious C++ code.
1. It encourages the use of 'new' without any considerations. Obviously, no 'delete's are necessary because of the garbage collection, but in C++, using heap memory is something you would typically want to avoid when you can use the stack.
2. There is no 'const'. This is one of the greatest features of C++.
3. Java templates are basically a poor hack of the C++ version.
4. All objects are automagically treated as references.
5. No operator overloading.
As far as pitfalls go, just be sure to bring a nose plug. When coding in java, you may find a hideous stench rising from your keyboard.
this sounds like someone who has no meaningful experience in java. to rebut:
1. there is the final keyword, same thing
2. their templates are pretty much the same, just called generics instead.
3. they're not references in the C++ sense, they're just called references in java.
4. yeah, i wish java let you overload operators, but thats hardly a huge reason to hate it.
and by the way, there is no reason why using the heap is better than using the stack, and in C++ you should try avoiding dynamic memory(using the heap) whenever you can anyways, since it's probobly the most expensive operation you can do. And using new with no consideration? that is because it doesn't have the same implications as it does in C++.
all this being said, I am a C++ programmer, and I do prefer using C++. I know java because I'm in school
Quote:Bear in mind, however, that heap allocation in Java is faster than heap allocation in C++ (in fact, it can get quite close to stack allocation speed) precisely because it's garbage collected: on a compacting garbage collector, allocating memory is done simply by incrementing a pointer (whereas in C++, heap allocation requires traversing the heap looking for some free space).
Original post by WhatsUnderThere
1. It encourages the use of 'new' without any considerations. Obviously, no 'delete's are necessary because of the garbage collection, but in C++, using heap memory is something you would typically want to avoid when you can use the stack.
Quote:Java does not have templates. Java has generics, which are a fairly different concept. C++ templates, in addition to providing correct yet obfuscated metaprogramming functionalities, also make a poor attempt at emulating generics (sadly, without all the type-system friendliness generics have).
3. Java templates are basically a poor hack of the C++ version.
Quote:Nope. In C++, a const variable prevents you from altering the object represented by the variable (this forbids calling non-const methods, among other things), whereas in Java, a final variable prevents you from assigning to the variable more than once (this allows calling any kind of method afterwards). There is no way in Java to specify "You Shall Not Modify This Object", unlike in C++.
Original post by godsenddeath
1. there is the final keyword, same thing
Quote:Generics and templates are different beasts (mostly because templates were a first initial attempt at implementing generics, but computer science wasn't advanced enough yet to handle the complex type algebras this implies). A generic will know whether an array-of-base is an array-of-derived or vice-versa, whereas a template has no way to do so. Arguably, Java generics are still quite primitive.
2. their templates are pretty much the same, just called generics instead.
Quote:
Original post by godsenddeath
this sounds like someone who has no meaningful experience in java.
...
Quote:
1. there is the final keyword, same thing
No. See internet.
Quote:
2. their templates are pretty much the same, just called generics instead.
No. See internet.
Quote:
4. yeah, i wish java let you overload operators, but thats hardly a huge reason to hate it.
No. If Java had templates, operator overloading would be a great benefit. You could even write a EBNF implementation in Java, like it exists for C++ (boost spirit).
Quote:
all this being said, I am a C++ programmer, and I do prefer using C++. I know java because I'm in school
Java? School? Meaningful experience? Insulting people? And then, just claims that are provably (and widespread known as) false?
edit: Was your meaningful experience in Java really back in school, or did you learn it in your now first year at the university? Just curious.
Quote:
Original post by ToohrVyk Quote:Nope. In C++, a const variable prevents you from altering the object represented by the variable (this forbids calling non-const methods, among other things), whereas in Java, a final variable prevents you from assigning to the variable more than once (this allows calling any kind of method afterwards). There is no way in Java to specify "You Shall Not Modify This Object", unlike in C++.
Original post by godsenddeath
1. there is the final keyword, same thing
Don't forget that if you declare a const pointer in C++ you can still modify the referred object(or primitive\struct\array).
Quote:
Original post by someboddy Quote:
Original post by ToohrVyk Quote:Nope. In C++, a const variable prevents you from altering the object represented by the variable (this forbids calling non-const methods, among other things), whereas in Java, a final variable prevents you from assigning to the variable more than once (this allows calling any kind of method afterwards). There is no way in Java to specify "You Shall Not Modify This Object", unlike in C++.
Original post by godsenddeath
1. there is the final keyword, same thing
Don't forget that if you declare a const pointer in C++ you can still modify the referred object(or primitive\struct\array).
How?
int main () { int foo = 42; int* pfoo = &foo *pfoo = 42; // okay int const* const_pfoo = &foo *const_pfoo = 42; // "error: assignment of read-only location" int *const pfoo_const = &foo *pfoo_const = 42; // okay int const* const const_pfoo_const = &foo *const_pfoo_const = 42; // "error: assignment of read-only location" int * unconst_pfoo = const_pfoo; // "error: invalid conversion from `const int*' to `int*'" int * static_cast_unconst_pfoo = static_cast <int*> (const_pfoo); // "error: invalid static_cast from `const int*' to `int*'" int * const_cast_unconst_pfoo = const_cast <int*> (const_pfoo); // okay *const_cast_unconst_pfoo = 42; // undefined behaviour if referencee would be const int &rfoo = foo; rfoo = 42; // okay int const &const_rfoo = foo; const_rfoo = 42; // "error: assignment of read-only reference `const_rfoo'" int &unconst_rfoo = const_cast <int&> (const_rfoo); // okay unconst_rfoo = 42; // undefined behaviour if referencee would be const}edit: Forgot an example for structs:
int main () { struct X { int x; }; X x = { 42 }; X const& const_rx = x; const_rx.x = 42; // error: assignment of data-member `main()::X::x' in read-only structure struct Y { mutable int y; }; Y y = { 42 }; Y const& const_ry = y; const_ry.y = 42; // okay}edit: As for the const_casts<>(), their primary reason for existence is compatiblity to existing C codebases. Generally, nothing should be const_cast<>()'ed and written to again. See ToohrVyk below.
[Edited by - phresnel on January 16, 2009 5:05:52 AM]
Quote:
Original post by phresnel int foo = 42;int const* const_pfoo = &fooint * const_cast_unconst_pfoo = const_cast <int*> (const_pfoo); // okay*const_cast_unconst_pfoo = 42; // epic fail: undefined behaviour
The behaviour is defined, as per the standard (7.1.5.1 §5). The basic idea is that foo is a non-const integer, and can therefore be modified through non-const references, which the const_cast allows you to build. Of course, if foo was a const integer, then this would be indeed undefined.
Quote:
Original post by ToohrVyk Quote:
Original post by phresnel int foo = 42;int const* const_pfoo = &fooint * const_cast_unconst_pfoo = const_cast <int*> (const_pfoo); // okay*const_cast_unconst_pfoo = 42; // epic fail: undefined behaviour
The behaviour is defined, as per the standard (7.1.5.1 §5). The basic idea is that foo is a non-const integer, and can therefore be modified through non-const references, which the const_cast allows you to build. Of course, if foo was a const integer, then this would be indeed undefined.
Epic fail for me, then. Thanks for clarifying!
Is there any way of getting a copy of that paragraph?
Quote:
Original post by phresnel
Is there any way of getting a copy of that paragraph?
Quote:
-5- [Example:
const int ci = 3; // cv-qualified (initialized as required)
ci = 4; // ill-formed: attempt to modify const
int i = 2; // not cv-qualified
const int* cip; // pointer to const int
cip = &i // OK: cv-qualified access path to unqualified
*cip = 4; // ill-formed: attempt to modify through ptr to const
int* ip;
ip = const_cast(cip); // cast needed to convert const int* to int*
*ip = 4; // defined: *ip points to i, a non-const object
const int* ciq = new const int (3); // initialized as required
int* iq = const_cast(ciq); // cast required
*iq = 4; // undefined: modifies a const object
You can look for the standard draft online.
Quote:
Original post by WhatsUnderThere
2. There is no 'const'. This is one of the greatest features of C++.
It will be implemented along with other contracts (e.g. non-null) as a pluggable validation in 1.7 as far as I'm aware.
Some pitfalls of Java that a C++ programmer should be aware of:
(1) Nondeterministic object destruction. Java classes do not have destructors. They have finalizers that may be called zero or more times, but at nondeterministic times. If you have any resources allocated save for memory, you're out of luck. RAII is not available in Java.
(2) A severely broken exception model. Unlike in C++ where you can rely on stack unwinding and deterministic destruction, and where you can throw an exception and let it be handled at an appropriate place. in Java you need to catch and rethrow exceptions all over the place. The Java exception model is an idirect way of implementing he class C-style status-return idiom, only unlike C you're forced to do something about the returned status (BTW that's an advantage of Java over C).
(3) A based type heirarchy. This is seen as good by "true OO" theorists, but its end effect is a weak type system. Java's generics are syntactic sugar to eliminate the hordes of explicit casts that seemed to make up a bulk of Java code back when I was paid to use that language. They allow the appearance of greater type safety but because everything can be converted to type Object, it's really just the appearance of type safety. The C++ template system enforces type safety by default and you need to go to extraodiary lengths to subvert it.
(4) C++ allows compile-time error detection. Java pushes a lot of error detection to run time. It is an ordr of magnitude more costly to fix problems detected at runtime than at compile time.
Of course, Java has some keen benefits over C++. For instance, because it's interpreted it has runtime reflection which is really cool. The extensive application library that comes with the runtime is handy if you're used to the centrally-planned economy model of workflow and does make Java skills more portable between employers. Because of reflection and the huge application library, there is a set of comprehensive integrated infrastructures built around Java for the development and deployment of applications that are portable between employers.
(1) Nondeterministic object destruction. Java classes do not have destructors. They have finalizers that may be called zero or more times, but at nondeterministic times. If you have any resources allocated save for memory, you're out of luck. RAII is not available in Java.
(2) A severely broken exception model. Unlike in C++ where you can rely on stack unwinding and deterministic destruction, and where you can throw an exception and let it be handled at an appropriate place. in Java you need to catch and rethrow exceptions all over the place. The Java exception model is an idirect way of implementing he class C-style status-return idiom, only unlike C you're forced to do something about the returned status (BTW that's an advantage of Java over C).
(3) A based type heirarchy. This is seen as good by "true OO" theorists, but its end effect is a weak type system. Java's generics are syntactic sugar to eliminate the hordes of explicit casts that seemed to make up a bulk of Java code back when I was paid to use that language. They allow the appearance of greater type safety but because everything can be converted to type Object, it's really just the appearance of type safety. The C++ template system enforces type safety by default and you need to go to extraodiary lengths to subvert it.
(4) C++ allows compile-time error detection. Java pushes a lot of error detection to run time. It is an ordr of magnitude more costly to fix problems detected at runtime than at compile time.
Of course, Java has some keen benefits over C++. For instance, because it's interpreted it has runtime reflection which is really cool. The extensive application library that comes with the runtime is handy if you're used to the centrally-planned economy model of workflow and does make Java skills more portable between employers. Because of reflection and the huge application library, there is a set of comprehensive integrated infrastructures built around Java for the development and deployment of applications that are portable between employers.
Quote:
Original post by EmrldDrgn
P.S. I also have some C# knowledge. I've heard they're similar?
I think that you might have more luck by looking for the difference between C# and java than between C++ and java wich are (syntax aside) very different languages. Instead, Java and C# share many different features (though they are far from equal).
IMO the main difference is the memory management, as already said in previous posts.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement