Sign in to follow this  

Differences between Java and C++

This topic is 3288 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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........

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Quote:
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.
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).

Quote:
3. Java templates are basically a poor hack of the C++ version.
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).

Share this post


Link to post
Share on other sites
Quote:
Original post by godsenddeath
1. there is the final keyword, same thing
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++.

Quote:
2. their templates are pretty much the same, just called generics instead.
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Quote:
Original post by godsenddeath
1. there is the final keyword, same thing
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++.


Don't forget that if you declare a const pointer in C++ you can still modify the referred object(or primitive\struct\array).

Share this post


Link to post
Share on other sites
Quote:
Original post by someboddy
Quote:
Original post by ToohrVyk
Quote:
Original post by godsenddeath
1. there is the final keyword, same thing
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++.


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]

Share this post


Link to post
Share on other sites
Quote:
Original post by phresnel
int foo = 42;
int const* const_pfoo = &foo;
int * 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.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Quote:
Original post by phresnel
int foo = 42;
int const* const_pfoo = &foo;
int * 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?

Share this post


Link to post
Share on other sites
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<int*>(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<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object


You can look for the standard draft online.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
ToohrVyk: Many thanks.

Quote:
Original post by ToohrVyk
You can look for the standard draft online.

Ahhh, the draft. I really forgot about it, thanks :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Quote:
Original post by Bregma
(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.


I am not really sure why you had to do this. Java doesn't have something as powerful as RAII, but it is has the 'finally' block, which is where the housecleaning operation are usually performed, and which is far less horrible than what you describe.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
3. Java templates are basically a poor hack of the C++ version. 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).


While I fully agree with your previous statement about the heap allocation, I have to disagree with this one.

Java generics are severely limited. C++ templates employ structured typing instead of the nominative one Java uses. This, along with the metaprogramming facilities, is a big reason why C++ templates are superior. (Though I agree that the metaprogramming language syntax is atrocious.) Look up "generic programming" and "concepts". As it turns out, this "type-system friendliness" is a short-sighted design. Example:


template < typename Iterator, typename Function >
void for_each(Iterator begin, Iterator end, Function function)
{
for (; begin != end; ++begin)
function(*begin);
}


cannot be done in Java, because there is no way to have concepts. In here, the concepts are Iterator and Function, modeled as template parameters. The Iterator concept expects the "!=", "*", "++" operators, the Function concept expects the "()" operator, with one parameter, which equals the result of Iterator's "*". This is the key difference: since concepts are structural types, they don't really care about the type's name, but they do care about its semantics. This would result in nontrivial overhead at runtime, but here it is done at compile-time, which is perfectly OK.

Another example is the C++ STL's transform() function. In fact, the entire STL is an example of this. It is impossible to fully replicate the STL in Java without enforcing certain interfaces, e.g. demanding that any actors inherit from these very interfaces.

One very simple way of making Java generics more powerful is to remove the type erasure. This would allow for stuff like:


class Foo < T >
{
public void do_something(T t)
{
t.some_method(); // without type erasure, this is perfectly OK to do
}
};


There. NO interfaces for bound generics are necessary.

Quote:
Original post by bulgurmayo
I am not really sure why you had to do this. Java doesn't have something as powerful as RAII, but it is has the 'finally' block, which is where the housecleaning operation are usually performed, and which is far less horrible than what you describe.


True, finally is a good thing to have. But RAII is actually the optimum, since you don't have to remember writing anything (unlike with the finally way, where the finally block has to be written explicitely).

Share this post


Link to post
Share on other sites
Both Sun Java and Microsoft C#.NET take hints from C++ as to how they implement Object-Oriented Programming structures. These structures however did not originate with C++, and as such should not be accredited to the language. These structures have been around much longer than C++. Some of the thing that you will notice throughout all three languages include structured types, such as Classes, Enumerations, and Structs (C# includes all if these, Java does not have Structs because Classes mean the same thing, and C++ contains all of these).

The fact that every object-type in Java reduces to the common factor comes from the Object Design Pattern, which is common sensical design pattern among most Object-Oriented programming languages. In fact C# uses this pattern also. Both C# and Java have "native types" such as short, long, double, float, and char, but C# implements these as aliases to object types in reality, so you can use them either like a native or an object type. For example the type int in C# is an alias for Int32. Java does not have type aliases like this, so an int is always an int, however they do supply object types for native types such as Character for char, Integer for int, and Double for double.

To battle the non-deterministic object destruction problem, C# supplies the IDisposable interface which implements the Dispose method, which enables you to keep object lifetime to a minimum. Most classes in C# do not implement this method unless they could be unsafe, such as IO stream classes, and memory buffer classes. You can also implement it in any class that you want to ensure gets disposed of in garbage collection as soon as possible. You use it like this:


using(DisposableType object = new DisposableType)
{
// Use the object in this scope.
}


I was looking over the Java API documentation again this morning and I didn't notice any similar interface available in it, but that doesn't mean that one doesn't exist. I just don't know what it would be called. However I do know that Java does NOT have a using construct in which to place such a class. In Java if you want something to get collected quickly, you set it to null. This is considered a good practice anyway among all Object-Oriented languages, especially since the garbage collection utility of their environments does what it can when it can without impacting performance significantly.

Both C# and Java have single inheritance models for classes, but both Java and C# classes may inherit multiple interfaces. This is a better inheritance model than C++'s because it is more controlled and ensures the is-a and has-a inheritance models. It also eliminates the confusion of having the same method or field in different classes meaning different things and the order of which one overrides the other one.

Both C# and Java implement visibility in the forms of public, private, protected, abstract, static, and internal (C# only). The default if you don't include a visibility parameter on a method or field in Java is public, but in C# it is private.

C# has the notion of Properties, which encapsulate fields and provide a better way of managing class variables. For example.


public class Automobile
{
private int _fuelRemaining;

public int FuelRemaining
{
get { return _fuelRemaining; }
set { _fuelRemaining = value; }
}
}


Java however relies on the same techniques that C++ utilized, namely "getters and setters" or accessors and mutators. Basically in Java you must provide a separate method for each operation, as in:


public class Automobile
{
private int fuelRemaining;

public int getFuelRemaining()
{
return fuelRemaining;
}

public void setFuelRemaining(int fuelRemaining)
this.fuelRemaining = fuelRemaining;
}
}


Generics are the C# and Java answers to C++ templates, though they are not the same as has been pointed out. Microsoft has a good document (http://msdn.microsoft.com/en-us/library/c6cyy67b(VS.80).aspx) on their differences, but generally speaking, generics like templates supply a method of type-safety among collections and methods. There are many more ways to properly use generics however, than templates. But this is one of the major things that C++ developers get hung up on, so if you're thinking of learning either Java or C#, then you MUST know the differences between them. It is important to note that both C# and Java introduced generics fairly recently. C# introduced them in .NET 2.0 and Java introduced them late in 1.4 and fully in Java 5.

A run-down of the meaning of const, readonly (C# only), and final (Java only) is given in this (http://en.wikipedia.org/wiki/Const_correctness) Wikipedia context on Const-correctness. It is enough to say that they are handled differently across the three languages (C++, C#, and Java).

Both Java and C# implement the Interface Design Pattern, which is similar to C++ requirement for a definition (header files) and an implementation (code files), but it is not the same. Generally in both C# and Java the definition and implementation occur in the same file.

Java requires that the file name containing a class be named exactly the same as the class. For example if your file contains the class MyClass, then the file must be named MyClass.java. C# does not require this, but it is considered a best practice and a good idea because it clarifies the meaning and provides self-documentation in the process. Both Java and C# provide the possibility for inner classes (nested classes in C++), which may be public, private, protected, static, or internal, and inner classes do not affect the naming requirement in Java.

Both C# and Java implement the Model-View-Controller pattern for the graphical user interface components, which means they have events, data, and graphics parts to them. C++ uses the Windows API, which similarly abstracts a model, view, and controller, but they are not part of the components themselves in the Windows API as they are in both Java and C#.

C# and Java both provide interfaces with native code, but they are handled differently. I think that C#'s method makes more sense, but Java using JNI, and I think there is another method, works just as well.

Both C# and Java have the notion of namespaces, which is similar to C++'s notion of namespaces. Java's variant of namespaces is called packages, but it is important to note that Java's packages are NOT the same as C++'s or C#'s namespaces, though they are similar. In Java there is a naming requirement for namespaces, namely namespaces look like com.nathandelane.mypackage, and the folder structure to a class in that package must look like com/nathandelane/mypackage. In C# namespaces encapsulate classes, and there is no naming requirement in C#. To include functionality in Java from other Java packages, you use the import construct. This must occur before the local package name and before any class definitions. In C# you use the using construct to include functionality from other C# namespaces. Here are two examples:


// Java
import java.io.*;

package com.nathandelane.mypackage;

public class MyClass
{
//...
}



// C#
using System.IO;

namespace Com.Nathandelane.MyPackage
{
public class MyClass
{
//...
}
}


Pointers are generally frowned upon when using both Java and C#, and have been replaced by objects, but sometimes still you require a pointer, specifically when interfacing with native code. In Java you can use JNI to get pointers from native code, but generally you just use object- or reference-types as with the Object Design Pattern, pointers are no longer required and they break the management of the Java environment. Similarly C# provides you with everything you really need in reference-types that you would ever use a pointer for, however C# takes you a little further by including pointer-types such as IntPtr, which is a reference-type that allows you to do things with pointers. However once again pointers are a general no-no for both C# and Java and you generally don't need them for any reason.

One last important thing to point out that is different between C# and Java and C++ is the Collections framework. Generics are a part of Collections. Java supplies the java.util package which supplies collections such as ArrayList, List, LinkedList, HashMap, Hashtable, Stack, Queue and TreeMap. C# supplies the System.Collections and System.Collections.Generics namespaces which provide collections and collection interfaces such as IList and List<T>, Dictionary<Tkey, Tvalue>, Stack<T>, Queue<T> and ICollection. These are similar to C++'s vector<T> collection. Because C# and Java supply these constructs it is rare that you need to program them, as they have been optimized for their environments. You no longer need to program a linked list, because these collections operate at a higher level of readability and efficiency.

In general, it is good to learn Java from Sun, C# from Microsoft, and C++ from Bjarne Stroustrup, since they are the originators of these languages and know how they're supposed to work and do things. It is common for people to try and compare C++ and Java, or Java and C#, and so on, but the fact remains that they are not 100% comparable, and certain things are just plain different. As an example you can't really compare namespaces to packages, because they don't even work the same way. You can't compare pointers to reference-types because they're different. And you can't compare IDisposable to setting an object to null for or calling a destructor for garbage collection, because they aren't the same thing even though they are supposed to produce the same result.

I prefer all of these languages depending on my requirements and what I'm programming. So should you also do.

Nathandelane.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Quote:
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.
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).


That's an interesting point--I assume the JVM creates some sort of memory pool to do this?

Assuming that is the case, what happens when the allocation pointer reaches the end of the pool? Does it degrade into the C++ method of searching for available memory?

Share this post


Link to post
Share on other sites
Quote:
Original post by WhatsUnderThere
Quote:
Original post by ToohrVyk
Quote:
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.
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).


That's an interesting point--I assume the JVM creates some sort of memory pool to do this?

Assuming that is the case, what happens when the allocation pointer reaches the end of the pool? Does it degrade into the C++ method of searching for available memory?


It does something that C++ cannot - because it can move objects in memory and update the references.

My understanding is that it groups objects into three categories. The long lived objects, medium lifespan and then short lived. The short lived ones are in a stack of sorts. Allocation is just a pointer increment. If the stack is filled, then run some garbage collection. Objects in the stack that aren't garbage are promoted to the medium lifespan heap. The stack is then compacted (the objects are relocated and references updated). Similarly, garbage collection runs on the medium lifespan heap could promote some to long term objects.

This is a simplified view, but you get the gist.

Share this post


Link to post
Share on other sites
Sign in to follow this