C++ vs Java
java
cpp
Memory Allocation
- In C++, you can allocate any type of variable on the stack as well as heap with use of pointers for manual memory management
- In Java, only primitive type variables and references can be allocated on the stack and the pointed data by the references is stored in heap. The garbage collector handles deallocation of unused variables
Type-inference
The var
keyword in Java and auto
keyword in C++ are used for type-inference
Equality Check
- The
==
operator in C++ checks if the values at both variables are the same - The
==
operator in Java checks if both variables point to the same location. To check if the values at both variables are the same, use the.equals()
method
Arrays
Arrays are passed by reference to functions in Java as well as C++. Arrays are of fixed size and store only one type of elements in both
If we have an array arr
of integers, it’s size is given by:
- In C++ :
int n = sizeof(arr) / sizeof(int)
when array is created on stack - In Java :
int n = arr.length
… an array is also an object in Java having properties likelength
to it
Note: There is no way to calculate size of dynamic array in C++
In resizeable arrays like vector
of C++ and ArrayList
of Java, the number of elements is given by the .size()
member function
2D Arrays
Both C++ and Java codes above produce the output:
Jagged 2D arrays
We can create jagged arrays in C++ but there is no automatic way to print them since we cannot calculate the number of elements present in a particluar row as that array is dynamic array. Vectors might be more suited in this case.
In Java, however, we can easily create and traverse jagged arrays