Java vs C++: The Most Important Differences
In this post, we feature a comprehensive article about Java vs C++ and their most important differences. Java and C++ are the object-oriented programming languages. C++ is platform dependent and Java is platform independent language. In this tutorial, we see the features of Java and C++ to see the differences.
Table Of Contents
1. Overview
We look at the comparison of Java vs C++ languages in this article. They can be used for developing software and executing the code. Java code is converted into bytecode after compilation. The java interpreter runs the bytecode and the output is created. C++ has a specific compiler for an operating system. C++ code is converted into machine level language. A binary file is created and executed for creating the output in C++.
2. Java vs C++
2.1 Prerequisites
Java 8 is required on the linux, windows or mac operating system. Eclipse Oxygen can be used for this example. Eclipse C++ is necessary on the operating system which you want to execute the code.
2.2 Download
You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site. Eclipse C++ is available at this link.
2.3 Setup
2.3.1 Java Setup
Below is the setup commands required for the Java Environment.
Java Setup
JAVA_HOME=”/jboss/jdk1.8.0_73″ export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
2.3.2 C++ Setup
Eclipse C++ installation sets the environment for C++ development and project building.
2.4 IDE
2.4.1 Eclipse Oxygen Setup
The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
2.4.2 Eclipse C++ Setup
The ‘eclipse-cpp-2019-06-R-macosx-cocoa-x86_64.dmg’ can be downloaded from the eclipse C/C++ website. After installing the application on macos, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
2.5 Launching IDE
2.5.1 Eclipse Java
Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screen shot below:
You can select the workspace from the screen which pops up. The attached image shows how it can be selected.
You can see the eclipse workbench on the screen. The attached screen shot shows the Eclipse project screen.
Java Hello World
class prints the greetings. The screenshot below is added to show the class and execution on eclipse.
2.5.1 Eclipse C++
C++ code is created to print “Hello World” and executed on Eclipse C++. The screen shot below shows the Hello World in C++ and the printed output.
2.6 Memory Management
Java language has features related to memory management and it is a memory safe language. Garbage collection is a feature which helps in collecting the resources which are free and released. C++ allows dynamic memory allocation which causes problems due to developer defects. Developer in java cannot go beyond the allocated memory, whereas in C++, developer can access beyond the allocated memory. In java, it throws an error and C++ allows the access which leads to defects in the code.
2.7 Exceptional Handling
In Java, exception handling is possible by using try, catch and finally blocks. C++ language has features for try and catch to handle the exceptions. In java, exception classes can be extended and created for various errors. In C++, standard library has exceptions which need to be derived for handling various errors. If a method throws an exception in Java, try and catch has to be created to handle the exception while invoking the method. In C++, the invoking can exclude the try and catch block.
2.8 Multiple Inheritance
Multiple inheritance is supported in C++. Let us take an example to see how it is handled in Java and C++. Truck is an vehicle and a machine.
Java does not support multiple inheritance. Each class is able to extend only on one class but is able to implement more than one interfaces. The sample code shows below Truck
class implementing interfaces Machine
and Vehicle
.
Interfaces
public interface Machine { int velocity=50; public int getDistance(); } public interface Vehicle { int distanceTravelled=100; public int getVelocity(); } public class Truck implements Machine, Vehicle { int time; int velocity; int distanceTravelled; public Truck(int velocity, int time) { this.velocity = velocity; this.time = time; } public int getDistance() { distanceTravelled= velocity*time; System.out.println("Total Distance is : "+distanceTravelled); } public int getVelocity() { int velocity=distanceTravelled/time; System.out.println("Velocity is : "+ velocity); } public static void main(String args[]) { Truck truck = new Truck(50,2); truck.getDistance(); truck.getVelocity(); } }
In C++, multiple inheritance is a feature where you can inherit multiple classes. The constructors of the classes inherited are invoked in the order of inheritance. In the example below, Machine
will be called before the Vehicle
when Truck
object is instantiated.
C++ Inheritance
#include using namespace std; class Vehicle { public: Vehicle() { cout << "Vehicle's constructor is invoked" << endl; } }; class Machine { public: Machine() { cout << "Machine's constructor is invoked " << endl; } }; class Truck: public Machine, public Vehicle { public: Truck() { cout << "Truck's constructor is invoked " << endl; } }; int main() { Truck truck; return 0; }
2.9 Threads
Java has in built classes to create threads. To create a new thread, a class has to extend a Thread
class and the run method has to be overridden. In C++, commercial libraries are provided for thread support till C++11.
Java Threads
public class NewThread extends Thread { public void run() { System.out.println("Thread running now"); } public static void main(String args[]) { NewThread newThread =new NewThread(); newThread.start(); } }
Java provides another way to create Threads. A class which implements Runnable
can be instantiated and passed as a parameter to the Thread
class. Sample code is provided below:
Java Thread Object
public class ThreadObject implements Runnable { public void run() { System.out.println("ThreadObject running"); } public static void main(String args[]) { ThreadObject threadObject =new ThreadObject(); Thread thread =new Thread(threadObject); thread.start(); } }
C++11 has a thread class. A developer can create a new thread object. The callable method can be passed as constructor’s argument. A thread is started when the thread object is instantiated.The code sample below shows how to create threads using function pointer, lambda expression and function object.
Threading in C++
#include #include using namespace std; void invoke_method(int Z) { for (int i = 0; i < Z; i++) { cout << "Thread - function pointer as callable method\n"; } } class thread_object { public: void operator()(int x) { for (int i = 0; i < x; i++) cout << "Thread - function object as callable\n"; } }; int main() { cout << "Threads 1 and 2 and 3 and 4 " "operating independently" << endl; thread thre1(foo, 4); thread thre2(thread_object(), 4); auto g = [](int x) { for (int i = 0; i < x; i++) cout << "Thread - lambda expression as callable\n"; }; thread thre3(g, 4); thread thre4(foo,4) thre1.join(); thre2.join(); thre3.join(); thre4.join(); return 0; }
2.10 Portability
Java language is interpreted by the java interpreter on the computer independent of the operating system. C++ code needs to be compiled by the compiler specific to the operating system.
C++ code needs to be compiled, linked and loaded by the operating system specific versions. Preprocessing of the code is also operating system specific.
2.11 Types
Java language has primitive and object types. Java has features related to autoboxing which converts the types automatically. The java.lang.Object
class is the base class for all the classes and Java follows the single root chain of command. In C++, single root chain of command is not there.
C++ data types are categorized as primitive, derived and user defined. The derived data types are array, pointer and reference. User defined data types are struct, union, class and enumeration.
2.12 Libraries
Java packages help in packaging classes. Package scope is another feature in Java language. Java archives help in grouping the package of classes for execution and installation purposes.
C++ libraries are code packages and they can be static or dynamic. C++ library has a header and a precompiled binaries. C++ library is packaged with binaries, static libraries, shared libraries and resources.
2.13 Runtime Errors
In java, runtime errors are presented by the compiler and the interpreter. In C++, developer takes care of the runtime errors by programmatically checking and validating the code.
2.14 Documentation
Java has feature to support comments which can be used for documentation generator. In C++, documentation can be generated using Doxygen from the comment blocks.
2.15 Mobile & Web & Desktop
Java language can be used for mobile, web and desktop application development. C++ can also be used for mobile and desktop native applications. ISAPI and C++ web based applications are popular on microsoft stack.
3. Conclusion
Overall, Java has great benefits over C++. The comparison table below captures the differences between Java and C++.
Comparison Table
Feature | Java | C++ |
Memory Management | Garbage collection is a feature in Java.Pointers are not there in Java. Java programs consume more memory compared to C++ programs. | C++ has features related to pointers, structures and union. The initial footprint of the C++ program will be small and increase if there is any dynamic memory allocation. |
Inheritance | Interfaces can be used for multiple inheritance. Single Inheritance is supported in Java. | It has support for multiple and single inheritance. |
Threads | Java has class Thread and interface Runnable to use threads. | C++ does not have this feature and commercial libraries are needed. |
Portability | Java byte code is platform dependent. | C++ code needs to be compiled by the platform specific compiler. |
Access Control | Encapsulation helps in access control of the class variables and properties in java. | C++ has better protection of the class variables and properties. |
Types | Single root chain of command pattern is used in Java. | C++ does not have single root chain of command. |
Libraries | Java archives are used for building java libraries. | C++ libraries are created using binaries and header files. |
Runtime error | Runtime errors are detected in compilation and execution stages in Java | In C++, developer needs to check and validate for runtime errors. |
Performance | Java performance is slower compared to C++ as it is a byte code intrepreted and executed. | C++ is around 5 times faster than Java. |
4. Download the Source Code
You can download the full source code of this example here: Java vs C++: The Most Important Differences
This entire article was obviously written from a Java enthusiast perspective. Just a few items not mentioned. 1. Processor independence of Java only exists if someone has written a Java interpreter for the platform. This is not the case for embedded systems nor for some operating systems. 2. Performance of a native compiled language over a bytecode interpreted language are significant no matter what environment you run in. If you want to argue that Java can be compiled to binary as well then you throw out all your arguments for processor independence of Java. Arguments for speed of bytecode interpretation… Read more »