You are here: Home » C++ vs. Java

Why C++?  Why not Java?

Because Java has become the standard teaching language, it would seem sensible that this introductory text would write code in Java.  However, there is no Java-MPI standard, so most people do not use Java when running programs under MPI. 

Although C and C++ have their share of teaching barriers, simple C/C++ programs, when compared to Java, are pleasantly similar.  This is particularly true when, as in Supercomputing Simplified, the housekeeping aspects of C/C++ are already laid out and can be copied by the beginning programmer. 

Java vs. C++: A Comparison


Below are two programs comparing C/C++ to Java:


Hello World

These programs screen print the string: "Hello world!" and give a carriage return

In Java In C++

public class Hello {   

public static void main(String [] args) {
           System.out.println("Hello world!");
         } 
}


#include<iostream.h>  

 int main()
    {
        printf("Hello world!" \n);
        return 0;
    }

Factorial Generation

These programs generate and print, one value per line, the factorials of 1 through 7.

In Java In C++


public class Factorial {

    public static void main(String [] args) {
        int[] A = new int []{1,1,1,1,1,1,1};

        for (int j=1; j<7; j++)
        {
           A[j] = A[j-1]*j;
           System.out.println(A[j]);  
        }   
    }
}


#include <iostream.h>


int main() {
       int A[7] = {1,1,1,1,1,1,1};

       for (int j=1; j<7; j++)
       {
          A[j] = A[j-1] * j;
          printf( "%i \n", A[j] );
       }
       return 0;
}


Summing Variable Number of Addends

These programs prompt the user for number of entries to be summed.

In Java In C++

import java.util.*;

public class SumFun {   
   
    public static void main( String[] args ) {
        
        int sum = 0;

        System.out.print( "How many numbers are there? " );

        Scanner keyboard = new Scanner( System.in );
         int n = keyboard.nextInt();


        System.out.print( "Enter " + n + " numbers: " ) ;

        for (int i=0;  i < n; i++ ) {
            int currentNumber = keyboard.nextInt();

            sum = sum + currentNumber;

        }

        System.out.println( "The sum of your numbers: " + sum ) ;
    }
}


#include <iostream.h>

int main() {

 int n=0, sum=0, currentNum=0;

 printf("How many numbers are there? \n");

 std::cin >> n;
 

printf("Enter %i numbers : \n",n);

 for (int i=0; i < n; i++) {
   std::cin >> currentNum;    

   sum = sum + currentNum;   

 }

 printf("The sum of your numbers is %i \n",sum);

 return 0;
}