Java vs C/C++

Updated: 2018-11-29

Early Binding vs Late Binding

  • Java: Early binding, know the type during compiling
  • C++: Late binding, do not know the exact type during compiling, but know in run time. Use virtual.

Inheritance

  • Java: single rooted hierarchy, inherit from Object, does not support multiple inheritance
  • C++: multi-inherit

Memory

  • Java uses virtual machines(JVM), C++ could directly work on memory.
  • Java:

    • primitive on stack: boolean, char, byte, short, int, long, float, double, void. more efficient
    • all objects are created on the heap, using new
    • object reference on the stack
  • C++: Stack and heap

stack vs heap

  • stack: stack pointer move down to create new memory, move up to release. efficient.
  • heap: unlike the stack, the compiler does not need to know how long the storage must stay on the heap. dynamically create and release. Takes longer time than stack.

Garbage Collection

  • Java has built-in garbage collection
  • C++ has to manually free the memory.

Pass By Value vs Pass By Reference

  • Java parameters(including object's reference) are passed by value
  • C++ parameters could be passed by value, pointer or reference.

Type

  • Java does not support unsigned arithmetic, C++ does.

Operator Overloading

  • Java does not support operator overloading
  • C++ does.

Return Code

C

the integer returned from the main function is the process exit status, indicating if the code is successful

Java

Not the return code from main, instead System.exit(int status) has to be called.

public static void main(String[] args) {
  System.exit(1);
}

Actually, Java's main function has to return void, otherwise an error will be thrown:

Error: Main method must return a value of type void in class XXX, please define the main method as: public static void main(String[] args)