would that explain why sometimes Java code runs faster than C++?
people say that the JVM is pretty good in that
A carefully crafted C/C++ program by a skilled programmer can beat Java's performance any time. But this is not to discount average day to day Java programs running faster. There are many reasons for this. The JIT compiler can optimize and compile bytecodes better than a C/C++ compiler because it has access to information that a C++ compiler doesn't. Also a JIT compiler and a JVM can do a much better job with populating cachelines when running on a target machine with better specs than the host machine on which your code is natively compiled. The folks working on Java's JVM are much better than most of the average day to day C++ programmers which makes it a easy task for Java's speeding up. And the garbage collector can prevent defragmentation of memory which would again help with the data caches. A skilled C++ programmer can do the same with a custom allocator.
But like I said before, if you sit down a skilled C++ programmer with a skilled Java programmer, then you can be sure that her C++ programs will atleast run as fast as the equivalent Java programs if not faster.