LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Articles > Technical
User Name
Password

Notices


By Mister_Ex at 2006-11-02 00:22
Students.java or Students.cpp?
A review of C++ versus Java, and which should be used in classrooms

Sean Enck
Kettering University
Computer Science Undergraduate
enck6535[at]kettering.edu

<b>ABSTRACT</b>
This paper aims to compare C++ and Java in a university setting. The question posed among staff and students at some universities is: should we be teaching Java or C++ as the current programming standard? Both are viable options, but would students benefit more from either language? The following discussions of both C++ and Java will give a little background or history of the language. The pros and cons of both Java and C++ will be weighed against each other in a classroom setting, what is good for students when it comes to programming languages and what would make a student struggle? The next step involves an implementation of algorithms and coding which will be used to show the amount of iterations C++ and Java can do within a 1000 millisecond time interval. Several experiments have been designed to test different code in each language. These experiments include an integer assignment, an array filling assignment, a recursive method, generic system output, a bubble sort, and finally retrieval of the current directory. This same code will be reviewed to see how many lines of code it takes for Java and C++ to have done the same amount of work. These results will be interpreted as to which language is the better language as far as speed and ease of use. Once both Java and C++ have been covered the future languages that are available for teaching courses in the next several years will be reviewed briefly. Finally, the better teaching language will be discussed and the reasons for the choice will be given.

Keywords
<i>Executables</i> – Programs compiled into files that are attributed with the .exe file tag. These programs are mostly developed in accordance to Microsoft’s .NET Framework.
<i>JVM</i> – The Java Virtual Machine. Required to run any Java program. It is a code interpreter to run Java code on any machine acting as a gateway.
<i>Multithreading</i>– Sharing a single CPU between multiple tasks in order to minimize the time required switching threads. [5]
<i>JRE</i> – Java Runtime Environment. The basic runtime libraries for a Java program. The JRE libraries are required to run several Java programs.
<i>JDK</i> – Java Development Kit. The standard download at Sun Microsystems’ website to start creating Java applications or applets. Includes the standardized libraries.
<i>OOP</i> – Object Oriented Program. The use of objects as a major part of a programming language’s program development. The best example would be Java.
<i>Procedural Languages</i> – a programming language in which the programmer specifies an explicit sequence of steps that will be followed to produce a result.
<i>Programming Languages</i> – In this paper refers to a plethora of different languages, ranging from C++ to Python to Pascal

<b>1. INTRODUCTION</b>
Throughout the past several decades as computers have developed, so have the computer sciences. The computer sciences have changed with the times to create an easier development of applications on newer technology ranging from applications to hardware.

Whether it is Fortran, Pascal, Basic, C++ or Java, there is a good chance any programming language’s usefulness will end if it has not already. This leads universities to adopt a new programming language in order to keep up with the times. Some students feel cheated after being taught a dead language and all those courses they took have no practical use. So what language should a university choose? Today’s more likely candidates are C++ and Java. Both C++ and Java have proven they have the backing from a strong community and a good company. Neither language will die out any time soon. This paper will discuss the pros and cons of C++ and Java, implement algorithms in both C++ and Java to show differences in time complexity and the amount of coding required, and finally what may be coming up to replace C++ or Java as the new hot language.

<b>2. The Opposing Languages: C++</b>
<u>History</u>
First, we will start with a little history of C++. Comparing C++ and C shows that C++ adds a new programming philosophy to C [7]. The development of C++ started in the early 1980’s. Though some of the basics of C have remained in C++, it is a whole different programming language as it is an Object Oriented language and C is a procedural language. Object Oriented Programming in C++ is more about the data then it is about the algorithms [7]. This gives C++ a different look and feel then its predecessors.

<u>Pros of C++</u>
List 1 is a list of a few pros for C++ that will now be discussed.
The compilation of C++ is the first pro that will be looked at here. In C++, the program can be simply compiled and then run as an executable (though it depends on the platform). In Java this is not the case, compilation and interpretation slow down because of the Java Virtual Machine (JVM). The JVM ironically enough is not written in Java and thusly requires the code to be compiled and then interpreted by JVM prior to be run, which is three steps to run versus C++ with the two steps. Global variables in C++ allow for any easier pass of information across the program. In Java, no global variables requires that the variable is passed through a method, constructor or some other indirect path in order to move from one location to another. This requires some extra coding and more tracking of different variables. This can lead to more lines of code in Java for the same amount of work than C++. In C++, there is a combination of OOP and procedural where as Java requires all parts to be OOP based (or so it seems). There are no structs, unions or any of these programming concepts to be used in Java. Once again, this leads to more coding for the same amount of work in java versus C++. Developing a six-line struct in C++ would require another class in Java.

<b><u>List 1 - Characteristics regarding C++ and Java[4]</b></u><i>
Java
Combination of Compilation and interpretation
Slow execution when interpreted
No Global Variables
Pure Object-Oriented

C++
Compiled
Fast Execution
Global Variables
Hybrid between procedural and Object-Oriented</i>

<u>C++ in the Real World</u>
What about C++ use in real life situations?
C++ can be compiled into an executable and used mostly on a Window’s Platform. This is noticed by the heavy push of Microsoft’s Visual Studio 2005 and the .NET Framework. “Microsoft .NET is the Microsoft strategy for connecting systems, information, and devices through Web services so people can collaborate and communicate more effectively” [6]. It is developed by Microsoft along with other languages like C#, J#, and Visual Basic. The aim is that C++ applications will be developed more for the Windows Platform and not as much for platforms like Unix or different distributions of Linux. Though this does not prevent C++ applications from being developed for Linux, Mac OS X, or Unix it does create a noticeable bias. Since Windows is run on a large amount of computers, this increases the usability of C++ programs and executables. With so many people using Windows, C++ is very useful for certain Windows developers.

<b>3. The Opposing Languages: Java</b>
<u>History</u>
Java is a relatively new language started and initially developed during the 1990’s. Developed by Sun Microsystems to power consumer appliances, it has grown into a totally different language [1]. Though Java is based off of C and C++ it has grown into it’s own powerful language based on pure OOP. Unlike Sun Microsystems’ plan, Java has shown that system independence can be a key for programmers on any Operating System.

<u>Pros of Java</u>
Found in List 2 are some of the things Java has done better then C++ that will now be reviewed more in-depth.
Garbage collection isn’t really that key until dealing with very large amounts of data. However, when programming (unless in a classroom) the amount of data and algorithms used is extensive and thusly will almost assuredly require some amount of garbage collection. Forgetting to call garbage collection could lead to a slower program, but in Java garbage collection will be called if necessary, in C++ this call has to be made by hand.
Multithreading or a form of CPU sharing can truly increase the speed of a program. Where Java allows instructions to multithread and thusly creates a faster threading process, C++ doesn’t allow such CPU occurrences and thread tasking is left to a single and slower threading situation. Creating documentation, the key to future maintenance. In Java, documentation has one basic standard in Javadoc, not to mention HTML format documentation can be generated. In C++, though certain documentation standards do exist, there is no one creator of C++ and so any commenting style could be expected. This can lead to sloppy/a lack of commenting, which for any computer scientist can lead to confusion down the road when performing routine maintenance.

<b><u>Characteristics regarding Java and C++[4]</b></u><i>
Java
Automatic garbage collection
Supports multithreading
Automatic generation of documentation in HTML format

C++
No automatic garbage collection
No multithreading
No automatic documentation</i>

<u>Java in the Real World</u>
Now for Java in a real life situation.
Java is developed by Sun Microsystems and Sun Microsystems only (with 3rd party libraries open to the public). This helps maintain something Java can hold over C++ indefinitely, which is that Java is system independent. Any program written Java can be moved from one Operating System to another (assuming the JRE is installed if necessary) with no hassle. GUI’s programmed in Linux will look the same in Windows or Mac OS X (assuming the correct libraries are used to achieve this). Though Java programs are .java files, they can be compiled to self running .jar files to allow for clickable running in a given Operating System (similar to an executable file in Windows). This concept allows for a Operating System migration with Java programs to require little to no hassle compared to a C++ change.

<b>4. Java and C++ in the classroom</b>
Now that there is a little more of a background about each language, the student aspect can be discussed.

<u>Students and C++</u>
Why C++ could be used in classrooms.
- C++ is faster than Java. It doesn’t require a Virtual Machine to run and is very fast as a native program. Students using C++ would see a much faster program when compared to Java.
- It is highly useable on Windows, the more popular Operating System today. Even if Linux distributions are found on a campus, most students are likely going to be using a Windows Platform
- The tools are top-notch. Visual Studio 2005 makes programming in C++ a much easier task then before for anyone
- C++ is a closer relation to C. C was truly the gateway to current languages and system level operations. For Computer Engineers this sort of programming is very important.
- It is a proven language. C++ has been around for quite some time and has much support from big names like Microsoft but also a highly developed community. Finding help online would be much easier when working with a solid community

<u>Students and Java</u>
What about Java?
- Java has a very standardized library. Downloading the Java Development Kit provides the complete Java library for use in programming. This makes teaching Java much more standardized when it comes to libraries as only the IDE will change.
- It is system independent. The program can be written on a Windows Platform and moved to a Linux/Unix machine with little if any change in coding required for very complex or simple programs
- Java is the "safer" language. Instead of allowing a user to allocate memory, Java handles all pointers and only gives the user the chance to reference to objects. In C++ a miss allocation of memory can lead to a system failure, loss of work and reboot.
- Close resemblance to newer languages. Many Java programmers can easily shift away from Java and to a language like C# that is up and coming with a very similar syntax to Java.
- API Support. With each new release of a Java version, the information regarding each part of Java is updated and accessible at Sun’s website. This creates a very easy reference for new programmers.

<b>5. Evaluation of C++ versus Java</b>
In order to show the differences of C++ and Java, two programming experiments have been designed from the ground-up specifically for this paper:
- A Speed Analysis
- A Length Analysis
- A quick explanation of each program may be given in pseudo-code to clarify.

<u>Speed Analysis</u>
The first experiment deals with the speed of C++ and the speed of Java. There will be five different test programs; each program will run for a 1000 millisecond duration. During this time, the given assignment will be run and the number of runs will be calculated. The total amount of runs in 1000ms is the data that will be used. Each program will be given five runs and the average will be used as the data reference. The programs will be the same except for the specific syntax each language will require.

<i>Integer assignment</i>
The integer assignment will be very basic, something to the extent of: Integer x = 5

<i>Array assignment</i>
The array assignment will assign a value to 5 array slots. A for loop will be used to fill each slot in the array.
For(int y = 0; y < 5; y++)
X[y] = y * 5;
X[y] = y * 5;
X[y] = y * 5;
And so on for X[0,1,2,3,4,5]

<i>Recursive Method</i>
A basic recursive method will be written to count from 10 to 0
recursiveMethod(start)
if (start is 0)
return
start = start – 1
recursiveMethod(start)

<i>System output</i>
The system output will be very simple:
Output(“Hello World”);

<i>Bubble Sort</i>
A simple bubble sort will sort an array of 20 items in unsorted order. It will go through the list and switch an element if the current value is greater then next.

<i>Write to file</i>
A file will be created and the line “Hello World” will be entered into the file.
Open File
Write Line “Hello World!”
Close File

<i>Return the current working directory</i>
The program will find the current working directory of the computer and output the directory. This program includes two parts, finding the directory and then outputting the directory to the console.
Find the directory
Output(directory)

<u>Length Analysis</u>
The second experiment is not completing or running a program but determining how many lines of code were required to complete all the projects from the Speed Analysis.
- Lines with only brackets “{ }”, white space, or comments are not counted in the total amount of lines.

Example (in Java):

Class example{
Public static void main(String[] args){
Int five = 5;
//Comment or white space
System.out.println(five);
}

This example would result in a line count of 4.

<b>6. Results</b>
The results of each experiment are shown in List 3 and List 4.

<u>Speed Results</u>
The results shown in List 3 show that C++ is in fact faster.
In a 1000ms interval, C++ executed nearly twice as many times as Java did when dealing with Array Assignment, Recursive calls, and Bubble Sorts.
The closest Java came to matching C++ was when writing to a file. In that circumstance Java was able to execute about 80% of what C++ was able to execute.
When accessing system information like the current directory, Java was only 65% capable when compared to C++.
All and all Java proved to be much less capable over 1000ms when compared to C++.

<b><u>List 3 - Java and C++ Speed Results 1000ms (Averages)</b></u><i>
Integer Assignment
Java: 10982272
C++: 19737397

Array Assignment
Java: 7964085
C++: 19524412

Recursive Call
Java: 7848842
C++: 19870911

System Output
Java: 2163
C++: 3443

Bubble Sort
Java: 460193
C++: 1021053

Write to file
Java: 3598
C++: 4455

Current Directory
Java: 319
C++:484</i>

<u>Length Results</u>
The length results prove yet another interesting fact. In most cases C++ programs required a fewer number of lines for a program then Java did. Even when Java matched the same amount of lines, it still ran slower as shown above. Array assignment for both Java and C++ required 13 lines of code; Java failed to run the assignment even half as many times. For write to file (Java’s most comparable speed to C++) the amount of coding required 4 more lines then C++ did. So even when Java is moving close to C++ speed, the amount of coding seems to have gone up.

<b><u>Java and C++ Code Length Results</b></u>
<i>Integer Assignment
Java Lines: 11
C++ Lines: 10

Array Assignment
Java Lines: 13
C++ Lines: 13

Recursive Call
Java Lines: 16
C++ Lines: 15

System Output
Java Lines: 11
C++ Lines: 10

Bubble Sort
Java Lines: 40
C++ Lines: 39

Write to file
Java Lines: 19
C++ Lines: 15

Current Directory
Java Lines: 17
C++ Lines: 17</i>

<b>7. Other Languages</b>
There are plenty of other languages currently supported and used. Whether it is Visual Basic or C# they are viable options that could some day replace C++ or Java in the struggle for teaching dominance.

<u>C#</u>
C# is a newer .NET based programming language. In the near future it could replace C++ as the keystone language but it still has to overcome its infancy stages and a stronger community before it can really take off. C# is a resemblance of Java and C++ widely developed in Microsoft’s Visual Studio 2005 as a major part in the renovations of .NET.

<u>Python</u>
Python is another newer language. It has some similar syntax to BASIC yet is considered more powerful then BASIC. In many ways Python could be compared to Perl or Java with very extensible modules to increase its usefulness [3]. Python is an easier language to teach because of the syntax; however, its use still is questionable in “real world” applications.

<u>Visual Basic</u>
Visual Basic is a much simpler and visual-based language. Though its background may not show as much power as other .NET languages, it has its uses when dealing with creating applications where Visual themes are key. For GUIs and the like VB is the best call.

<u>C</u>
An older and still used language, C is not gone. Though some may say it is going to be phased out, it has still survived being “replaced” by other languages. For system programming, very few (if any) languages can match C’s best abilities.

<u>J#</u>
The follow-up to J++, it is a language with an amazingly similar syntax/library/ideology as Java. J# is Microsoft’s response to Java. It is basically an integration of Java into Visual Studio and the .NET framework without forcing Microsoft and Sun Microsystems to enter into a legal contract. Though J# may end in the same manner as its big brother J++ [2], it could also become something bigger in the future.

<u>Web-based (Perl, PHP…)</u>
Whether we discuss Perl, PHP or any other mostly web-based language, the question of portability begins. Though they are often fast and require only a server, they are also not as easy to set-up for single users without server access. Yes, Perl or PHP can be run on a single computer but this is no easy task. Often times this sort of task will require an Internet server to be installed along with other packages for a specific language.

<b>8. Students.java or Students.cpp?</b>
After reviewing the difference in Java and C++, which should “win” in the classroom? Currently, Java should be the winner overall, especially for students with little to no prior programming experience. Even after reviewing other articles, Java still maintains a few better attributes then C++ as shown in the paper:
- Java allows for less freedom, which is good for novices. Memory allocation, garbage collection, pointers are not left up to the programmer, thusly it gets a little harder to cause a complete system failure
- The Java library. The JDK comes with a complete library that should easily cover the first several programming courses and the subjects those courses would cover
- Develop anywhere. Java is much more portable and the transfer of code from one machine to another will require no change in the coding for the simpler concepts taught throughout lower lever programming classes. C++ is portable but is more likely going to require a few changes to insure the code will still run
- Java coding length is comparable to C++ length. Though Java executes slower than C++ for several assignments, it still has the benefit of being a safer language. The JVM may hinder Java’s speed, but it is also the reason Java truly could bet C++. In several cases, a bad segment of code in C++ could affect the whole computer, however Java’s JVM would be the only thing truly affected (minus lag for the computer from memory for the JVM). In the end killing the JVM is much better then rebooting the computer.

There are plenty of places C++ could be better for teaching. An engineering school, for example, would probably benefit from using C++ as there is a good chance a Computer Engineer would need to do system level programming which Java would not be as “friendly” to use for such operations. The transfer between C++ and Java is not seamless however it is not a complete change in mindset. Teaching Java could easily lead to moving towards C++ in later courses and vice versa. Using C++ in later courses would help when programs become more complex and timing algorithms may be key.

Finally, in the future, perhaps one of the discussed languages will take the throne as the best language to teach. As of Summer 2006, none of these languages have yet to prove themselves better then the current offerings, but only the future will show what is next.

<b>References</b>
[1] Java Technology. Java Technology: Brief History of Java Technology. Retrieved September 7, 2006, from java.com website (2005): http://www.java.com/en/about
[2] Kanellos, M., Shankland, S., & Wong, W. Sun, Microsoft settle Java suit. Retrieved September 5, 2006, from CNET.com website (2001):
http://news.com.com/Sun,+Microsoft+settle+Java+suit/2100-1001_3-251401.h...
[3] Kuchling, A. BeginnersGuide/Overview – PythonInfo wiki. Retrieved September 6, 2006, from Python.org website (2006):
http://wiki.python.org/moin/BeginnersGuide/Overview
[4] Levine, D. L. Java vs. C++. Retrieved September 3, 2006, from Washington University in St. Louis website (2000):
http://www.cs.wustl.edu/~levine/courses/cs342/c++/javaVcpp-index.html
[5] multithreading. The Free On-line Dictionary of Computing. Retrieved September 6, 2006, from Dictionary.com website: http://dictionary.reference.com/search?q=multithreading&x= 0&y=0
[6] .NET FAQ. .NET Frequently Asked Questions. Retrieved September 5, 2006, from Microsoft.com website (2005):
http://www.microsoft.com/net/basics_faq.mpsx#EWB
[7] Prata, S. C++ Primer Plus (5th ed.) Sams, Indiananpolis, IN, 2005.

by pda_h4x0r on Mon, 2006-11-06 15:58
Java is easier to teach and to understand than C++ (read: NO POINTERS, TOTAL encapsulation), but C++ is still the industry standard for application development (it's faster, more compact, takes advantage of hardware, closer to machine-level, etc.), and is a MUST-learn. Personally, I believe that they should be taught the same year--Java first semester, and C++ second semester.

by NullTerminator on Mon, 2007-02-19 17:49
Overall I enjoyed the article. The hard measurements reinforce our general conception that C++ is faster and closer to the hardware. Java is excellent for learning OOP, especially if you study the swing libraries and the Model-View-Controller architecture.

Another aspect to consider when deciding to specialize in java or C++ is the job market. Java was hot a couple years ago, but there are now loads of java programmers out there. You will need more than a programming language alone to compete in the job market.

Quote:
Executables – Programs compiled into files that are attributed with the .exe file tag.
These programs are mostly developed in accordance to Microsoft’s .NET Framework.
I would hesitate to say mostly with .net framework. I've been programming C/C++ for twenty years and yet to use .net runtimes. We also do a lot of OS400 programming in C++ with no .net available.

Quote:
<u>Java in the Real World</u>
Quote:
Though Java programs are .java files, they can be compiled to self running .jar files to allow for clickable running in a given Operating System (similar to an executable file in Windows). This concept allows for a Operating System migration with Java programs to require little to no hassle compared to a C++ change.
1) .java source files are compiled into class files. .class files are combined into an archive call a .jar file. If the jar file contains the proper manifest it can be considered an executable jar.
2) The idea of a 'self running' jar file is misleading. It still requires that a suitabl java runtime environment be installed.
3) It is only 'clickable' if the OS recognizes the .jar extension and has a proper java command line mapped to call the main class.

Quote:
Whether we discuss Perl, PHP or any other mostly web-based language, the question of portability begins. Though they are often fast and require only a server, they are also not as easy to set-up for single users without server access. Yes, Perl or PHP can be run on a single computer but this is no easy task. Often times this sort of task will require an Internet server to be installed along with other packages for a specific language.
1) perl and PHP ARE VERY portable.
2) perl in a cgi context is web based, but perl does very well as a scripting language without any web aspect. It is easy to set up on a single machine and extremely useful for programs requiring heavy text parsing/processing.
3) PHP is primarily a web based language, but a standalone interpeter can run scripts independently of the web.

by juvestar15 on Sat, 2007-03-24 09:56
I've just finished my university studies so hopefully I can add something useful.

A year or two before I started(2003) a Computer Science degree, the primary language taught was C++. The then changed to Java and restructured the entire course around it. First year we had Programming Java 1 and 2. Second year I did "Object Oriented Programming 1 & 2", it was pretty much Swing, threads, JSP and Servlets. In my 3rd and final year was the first chance to study C++( however it was optional). The lecturer got the labs setup with .NET but really didn't mind what we used to write the code. In my 4th year which I did a honours degree, they introduced a "Algorithms and Structures" subject for first years which was all C++.

They must have realised putting all their eggs in one basket(ie. use java exclusively) was a bad idea. As I look for jobs now there's pages and pages for J2EE/Java developers. The interesting ones (to me anyway ) are the ones that want C++ experience. Speaking to lecturers around he uni. though, they don't think it should be a Java vs. C++ debate(at first anyway). They're all for python or some type of scripting language then going on with something more complicated. Before uni. I had programming experience in VB so I found java/c++ quite easy. The important thing is to teach concepts first(using an easy language), then figure out which more difficult language to go with. I know time is tight and that's why they want a language that does everything AND be easy at the same time. From what I've seen, that just puts students off programming.

One extremely frustrating thing they never paid attention to was deployment of the programs we had just created. Sometimes I need to write a program up quickly for me or a friend and find myself in a hole. I spent 3 years learning java but was never taught about .jar files. That's fine, I'll pick it up myself. But lets says I sent my .class files to a friend, he then has to install all the java libraries and goto the command line or setup class paths. Same with C++ in .NET and all the .Net libraries. C++ has the advantage though because you don't need .NET to write C++ programs. That's pretty much why I'd lean towards C++. If you get an idea in your head and you put some code down, it'll be easily distributed.

by vki on Sun, 2007-04-01 21:52
I am personally of the believe that C is a far superior language than java. Having known and used C independently for some time then being taught java in the class room I have been able to distinguish some key elements that I dislike about java. For example the incredible ability of java to turn simple tasks into cumbersome blocks of code. A very simple example would be just doing standard io you have to make objects just to take in command line arguments, seems overly cumbersome to me :\ but maybe I'm just old school. I don't want to keep ranting at risk of sounding like a cynic

But to each his/her own...

by NullTerminator on Mon, 2007-04-02 18:34
vki,

Command line arguments? You mean like an array of Strings that's passed to main(String []args)? How simple is that?

Code:
// something like this?
public static void main(String []args) {
  for( int idx=0; idx< args.length; ++idx){
    System.out.println(args[idx]);
    }
}   // end main
If you want something fancier, there are many getOpt ports for java.

Java is great for network i/o, and servlets are a lot easier to code that C/C++ cgi. But, for windows gui applications I'd say C/C++ wins.

I don't think anyone will argue that java is faster than C, but development costs may be less with java depending on the project. Want to learn some patterns and MVC architecture - go with some swing lessons. It takes OO to a whole other level. Learning java is a great OO teaching mechanism. The whole idea of programming to interfaces and implementing in derived classes will give great background for future C++ learning and development.

Don't expect to succeed as a programmer with an either/or attitude. You will eventually need both, and maybe some vba and shell scripting thrown in. We do a lot with java web front ends and C stored procedures on the back end.

\0


  



All times are GMT -5. The time now is 03:04 AM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration