Papercomparison
Papercomparison
Although many languages are based on the same fundamental building blocks. Learning a
language should be seen more as a way of acquiring those concepts than language or machine
specific techniques. Good programmers are generally competent in more than one language
because it is naturally interesting and useful to find different ways of solving problems. It is
not necessary to master many different languages or even more than one. A programmer
could excel in one language and have only a vague working idea on how to program others. It
is useful to know many different methods for solving computer problems. Since computer
programming languages have so much in common, it is generally easy to learn a new
programming language once you have mastered another.
One reasonable technique would be to just pick a language and run with it. Unfortunately,
one cannot suggest what the right computer language might be for all people for all purposes.
There are over 100s of programming languages which can be used for instructions in first
course in computer programming such as: Java, C, C++, Python, PHP, Perl, Ruby, etc.
Considering Python and Java, a compare is made between the two, to find out which is best
fit for teaching newbies in computer programming.
Furthermore, the programs compared in this manner are sometimes extremely small and
simple. Some are narrow controlled experiments, e.g. (Lutz, 2000) and (Les, 2010) often
focusing on either a single language construct, e.g. (Bradley and Robert, 2010:227), or a
whole notational style, e.g. (Bradley and Robert, 2010:121) and (J’urgen, et al, 2012). Some
are empirical comparisons based on several and larger programs, e.g. (John, et al, 2002).
They discuss for instance defect rates or productivity figures. The problem of these
comparisons is lack of homogeneity: Each language is represented by different programs and
it is unclear what fraction of the differences (or lack of differences) originates from the
languages as such and what fraction is due to different programmer backgrounds, different
software processes, different application domains, different design structures, etc.
One of the biggest differences between Python and Java as opined by George (1999) is the
way that each language handles variables. Java forces you to define the type of a variable
when you first declare it and will not allow you to change the type later in the program. This
is known as static typing. In contrast, Python uses dynamic typing, which allows you to
change the type of a variable, by replacing an integer with a string, for example. Dynamic
typing is easier for the novice programmer to get to grips with, because it means you can just
use your variables as you want to without worrying too much about their types (Michael,
1995). However, many developers would argue that static typing reduces the risk of
undetected errors plaguing your program. When variables do not need to be explicitly
declared before you use them, it is easy to misspell a variable name and accidentally create a
whole new variable(Lutz and Unger, 1999) in Scanlan (2009).
Python is unusual among programming languages in that it uses indentation to separate code
into blocks. Java, like most other languages, uses curly braces to define the beginning and
end of each function and class definition. The advantage of using indentation is that it forces
you to set your program out in a way that is easy to read, and there is no chance of errors
resulting from a missing brace (Shiffrin and Nosofsky, 2004).
The great advantage of Java is that it can be used to create platform-independent applications.
Any computer or mobile device that is able to run the Java virtual machine can run a Java
application, whereas to run Python programs you need a compiler that can turn Python code
into code that your particular operating system can understand (Walton and Felix, 2007).
Thanks to the popularity of Java for web applications and simple desktop programs, most
devices already have the Java virtual machine installed, so a Java programmer can be
confident that their application will be usable by almost all users Walton and Felix, (2007) in
Lutz, (2000). The disadvantage of running inside a virtual machine is that Java programs run
more slowly than Python programs (Lutz, 2000). Most programmers agree that Python is an
easier language for novice programmers to learn. You will progress faster if you are learning
Python as a first language than Java. However, the popularity of Java means that learning this
powerful language is essential if you want to develop apps for Android (Jones, 1996) in Lutz,
(2000).
According to Dijkstra (2001), Python programs are generally expected to run slower than
Java programs, but they also take much less time to develop. Python programs are typically
3-5 times shorter than equivalent Java programs. This difference can be attributed to Python's
built-in high-level data types and its dynamic typing. For example, a Python programmer
wastes no time declaring the types of arguments or variables, and Python's powerful
polymorphic list and dictionary types, for which rich syntactic support is built straight into
the language, find a use in almost every Python program. Because of the run-time typing,
Python's run time must work harder than Java's. For example, when evaluating the expression
a+b, it must first inspect the objects a and b to find out their type, which is not known at
compile time. It then invokes the appropriate addition operation, which may be an overloaded
user-defined method. Java, on the other hand, can perform an efficient integer or floating
point addition, but requires variable declarations for a and b, and does not allow overloading
of the + operator for instances of user-defined classes.
In fact, the two together make an excellent combination. According to Hudak and Jones
(2013), components can be developed in Java and combined to form applications in Python;
Python can also be used to prototype components until their design can be "hardened" in a
Java implementation. To support this type of development, a Python implementation written
in Java is under development, which allows calling Python code from Java and vice versa. In
this implementation, Python source code is translated to Java bytecode (with help from a run-
time library to support Python's dynamic semantics).
3. General Translation Process of programming languages
The translation or compilation processes are the series of stages that the program passes
through in order to be converted from source code to object code. The translation process as
discussed in (Sebastian and Carlo, 2015) is outlined in figure 1; it involves three stages,
namely, lexical analysis, syntax analysis and code generation. All programming languages
implement this translation process, but not necessarily in identical ways; understanding how a
language implements this process therefore provides useful insight into the internal working
of the language.
Figure 1 depicts the conversion of instructions written in high level language program to
machine readable instructions for implementation. In Lexical analysis, the source code is
converted to a sequence of characters and terminal symbols from the character set of the
language. All symbols identified must be defined by the grammar of the language. These
symbols are loaded into the symbol table, which contains critical information relating to
identifiers, data items, subprograms and other program components. An example of symbol
table contents is depicted in table 1.
Table 1: Symbol table
In the syntax analysis stage, the syntax tree, a hierarchical representation of the source code is
produced based on the syntax of the language. The analysis determines whether the sequence
of symbols, given a certain grammar, belongs to the language. A finite state machine (FSM)
is useful to test the validity of an input string, but only for regular grammars. A deterministic
finite state machine (DFSM) may be an alternative to a syntax tree. A derivation tree is
depicted in figure 2.
The output of the lexical analysis is the input to the syntax analysis, and the output of the
syntax analysis is the input of the code generation. The process may occur via a single pass,
of multiple passes. Multiple-pass compilers typically use two or more passes to convert the
source code to optimized object code. In single-pass compilation, code anlysis and code
generation are done in the same phase. In two-pass compilation, code analysis is typically
done in the first phase and code generation in the second phase. In three-pass compilation,
two approaches are prevalent. In the first approach, pass one is used for source code analysis,
pass two for initial code generation, and pass three for code optimization (Foster, 2014).
The Java programming language makes use of three-pass compilation process by generating
an intermediate code before generating the final optimized code. The compiler would allocate
the memory location during the semantic analysis, leading to all declarations being processed
before their use. The benefit of being a multi-pass compilation is machine independence,
since the passes can be reused for different hardware and machines, and more expressive
languages. Translating efficiency in Java depends to some extent on the IDE being used.
Meanwhile, Python runs the advantage of interpreting code when a program first executes,
then having the code compiled into bytecode. When next time the program is run, Python
runs the bytecode, not the program file. Python only recreates the bytecode if you change the
program file. Thus, Python combines the advantages of both interpretation and compilation.
The Python translation process may also vary depending on the implementation of the
language. The bytecode can be interpreted (CPython) or JIT compiled (PyPy). Like Java,
Python IDEs tend to be interpretive.
Python is an object-oriented language, just like Javascript, C++, C#, Perl, Ruby, and other
key programming languages. For people planning to become software developers, learning
this type of programming in one area will help you adapt easily in other environments.
Companies such as Google, Yahoo!, Disney, Nokia, and IBM all use Python. In fact, among
programming languages, Python had the largest year-on-year job demand growth at 19% as
of March 2013. Notably, the overall hiring demand for IT professionals dipped year over year
by 5% as of January 2014, except for Python programmers which increased by 8.7%. In New
York, Python developers ranked #8 of the most in-demand tech workers, making an average
of $106k/year. On the other side of the Atlantic, Python programmers also enjoy a strongly
rising demand for their skills as shown by the following graph on figure 3 (Nuk, 2014).
On the other hand, Java remains a critical technology that attracts intense interest and
passion, as testified by the droves of developers gathered in San Francisco. You don’t have to
write Java to use Java. You can get all the benefits of the portable JVM runtime but scribble
away in the familiar environs of Ruby or Python. It can be faster too. Java development was
the most sought-after software-building skill by employers searching Dice.com in the first
quarter of 2014, the company said. Employers searched Dice thousands of times to look for
software developers, engineers, architects and leads. Java is naturally secure. Figure 5 is Java
programmer Job demand in the UK as of July, 2015. Source
(http://www.itjobswatch.co.uk/jobs/uk/java.do)
5.
Figure 6. Java 3-month Salary trend.
Source: (http://www.itjobswatch.co.uk/jobs/uk/java.do)
5. Algorithm design
An algorithm is defined as a logical step by step method of solving problems. We employed
the formulas for calculating Grade Point Average (GPA) and Commutative Grade Point
Average (see figure 7) and developed an algorithm for which was programmed using the two
programming languages (python and java), see figure 8.
1. Request Data
2. Process/Calculate GPA
3. Display GP
Using the technique of stepwise refinement, we can refine the steps where necessary as
follows:
1. Request Data
1.1 Register users
1.2 Register courses
1.3 Request scores (exam and CA)
2. Process/Calculate GPA
2.1 Calculate GP = GP +(Grade * unit)
2.2 Calculate count = count + 1
2.3 Repeat 1.3, 2.1, 2.2 until count = no. of registered courses
2.4 Calculate GPA = GP/no. of registered courses
3. Display GPA
Note
GP: Grade Point
GPA: Grade Point Average
The above algorithm is used to calculate the average of n scores which will be run on Python
and Java to determine the execution time, memory consumption, and program length/code
size, correctness/robustness, amount of commenting and reliability on each of the said
programming language.
6. Implementation Architecture
Figure 9 shows the logical view of the architecture for implementing the designed algorithm.
The architecture shows various logical flows at every module in the system.
Course User
Registration Registration
mySql
Connector
Staff Students
Data Store
Mysql
The execution of program or application is done with the intent of finding the software bugs.
The process also involves validating and verifying that the software program or application or
product meets the business and technical requirements that guided its design and
development such as:
meets the requirements that guided its design and development,
responds correctly to all kinds of inputs,
performs its functions within an acceptable time,
is sufficiently usable,
can be installed and run in its intended environments, and
Achieves the general result of its stakeholder’s desire.
100000
Memory Consumption (bytes)
80000
60000
40000
20000
0
Python Java
Programming language
7.2 Comparison of Python and Java in terms of program length/ code size
The same program (code) was created in Python and Java, code that was used to implement
that algorithm for the computation of CGPA and table 3 shows the result of the comparison.
Table 3: Result of comparison of Python and Java in terms of program length/code size
50000
40000
30000
20000
10000
0
Python Java
Programming Languages
From Table 4, it is concluded that Python programming language executes faster than Java
programming language based on N = 12 courses and 300 students. Figure 12 shows the graph
of the summarized result of the comparison.
16
14
12
10
8 Figure 12
6
4
Comparison of
2 Python and Java
in 0 terms of
Python Java
Running/
Programming Language Execution time
//--------- constructor #3
-------------
public Employee(String
EmployeName,
inttaxDeductions,
String
maritalStatus)
{
this.employeeName =
employeeName;
this.taxDeductions =
taxDeductions;
this.maritalStatus =
maritalStatus;
}
...
From Table 5 above, we conclude that Java is more robust than Python programming
language
if ( a > b ) if a > b :
{ a=b
a = b; b=c
b = c;
}
The Java code on the left has 5 control characters: ( ) { } ; where the corresponding Python
code has only one control character, the colon. (Or two, if you count indentation).Omitting or
duplicating such characters is easy to do accidentally, and constitutes a severe error in the
code. It really cuts into productivity and creative energy when spending much time just trying
to satisfy the compiler. Java encourages multi line commenting with the help of (/*…*/)
while python does only single line commenting with the help of (#).
7.6 Comparison of Python and Java in terms of reliability
When a wrong value is entered in the program designed with any of the programming
languages, it throws an exception. An exception is an event, which occurs during the
execution of a program that disrupts the normal flow of the program's instructions.
7.6.1 Exception in Java
When an error occurs within a method in a Java program, the method creates an object and
hands it off to the runtime system. The object, called an exception object, contains
information about the error, including its type and the state of the program when the error
occurred. Creating an exception object and handing it to the runtime system called throwing
an exception.
After a method throws an exception, the runtime system attempts to find something to handle
it. The set of possible "somethings" to handle the exception is the ordered list of methods that
had been called to get to the method where the error occurred. The list of methods is known
as the call stack (see the figure 4.7).
Figure 13 The call stack.
The runtime system searches the call stack for a method that contains a block of code that can
handle the exception. This block of code is called an exception handler. The search begins
with the method in which the error occurred and proceeds through the call stack in the reverse
order in which the methods were called. When an appropriate handler is found, the runtime
system passes the exception to the handler. An exception handler is considered appropriate if
the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the next figure, the runtime system (and, consequently, the
program) terminates.
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
Catching exceptions
In order to handle errors, exception handling blocks is set up in the code. The
keywords try and except are used to catch exceptions. When an error occurs within
the try block, Python looks for a matching except block to handle it. If there is one,
execution jumps there. The code snippet in figure 4.10 handles that.
try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero, you're silly."
8. Conclusion
Programming languages are used for controlling the behavior of computer systems. Several
programming languages exist and new are being created every day. These programming
languages become popular with use to different programmers because there is always a
tradeoff between ease of learning and use, efficiency and power of expression. This study
revealed differences regarding two programming Language (Python and Java) in terms of the
following features (Code size, Running/execution time, memory consumption,
correctness/robustness, and commenting/reliability etc.) and is therefore of value to newbies
in software development and programming language tutors. Same set of code was tested on
the two programming languages, the result gotten shows that Python consumes less memory
than Java, Python has less code size than Java, Python executes faster than Java and Java is
more robust than Python.
Thus, it is known fact, with the results at hand that Python is better than Java. We therefore
recommend that python be used for instruction in first course in computer programming
classes for newbies.
References
Alireza Ebrahimi (2014). Novice programmer errors: Language constructs and plan
composition. Intl. J. of Human-Computer Studies, 41:457–480.
Allan J. Albrecht and Jr. Gaffney, John E.(2003). Software function, source lines of code, and
development effort prediction: A software science validation. IEEE Transactions on
Software Engineering, SE-9(6):639–648.
Bradley Efron and Robert Tibshirani. (2010). An introduction to the Bootstrap. Monographs
on statistics and applied probability 57. Chapman and Hall, New York, London.
C.E. Walston and C.P. Felix (2007). A method of programming measurement and estimation.
IBM Systems Journal, 16(1):54–73.
Foster, E. C (2014). Lecture Notes on Programming Languages. Keene NH: Keene State
College.
George A. Miller (1999). The magic number seven, plus or minus two.The Psychological
Review, 63(2):81–97.
John A. Lewis, Sallie M. Henry, Dennis G. Kafura, and Robert S. Schulman (2002). On the
relationship between the object-oriented paradigm and software reuse: An empirical
`investigation. J. of Object-Oriented Programming.
Lutz Prechelt and Barbara Unger (1999). A controlled experiment on the effects of PSP
training: Detailed description and evaluation. Technical Report 1/1999,
Fakult¨atf¨urInformatik, Universit¨at Karlsruhe, Germany.
Kasia Mikoluk (2013). Python vs Java: Key Differences.Online resource. Retrieved from
https://blog.udemy.com/python-vs-java/
Les Hatton (2010). Does OO sync with how we think? IEEE Software, 15(3):46–54,
Comparing Java to other languages. Online resource. Retrieved from
https://www.python.org/doc/essays/comparisons/
Lutz, Prechelt (2000). An empirical comparison of C, C++, Java, Perl, Python, Rexx, and
Tcl for a search/string-processing program. Technical Report, FakultInformatikUniversit,
Karlsruhe. Germany.
Robert Klepper and Douglas Bock (2005).Third and fourth generation language productivity
differences. Communications of the ACM, 38(9):69–79.
Richard M. Shiffrin and Robert M. Nosofsky (2004). Seven plus or minus two: A
commentary on capacity limiations. Psychological Review, 101(2):357–361.
Software Productivity Research Capers Jones (2000). Programming languages table, version
7 Online resource. Retrieved from. http://www.spr.com/library/0langtbl.htm.
http://www.itjobswatch.co.uk/jobs/uk/java.do
Apendix 1: Java Source Code
package resultcomputation;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
package resultcomputation;
import javax.swing.JFrame;
import MySQLdb
con=MySQLdb.connect(host="localhost", user='root', db='results')
cursor =con.cursor()
choice=raw_input('Press R to retrieve latest record, Press D to delete all records, Press enter
to skip ' "\n")
if choice=="R" or choice=="r":
try:
cursor.execute(read)
results=cursor.fetchall()
for row in results:
name=row[0]
cul=row[1]
gpa=row[2]
print "Student Name: %s, Total Unit Loads: %s, GP: %s" % (name,cul,gpa)
con.commit()
except:
print "Error: Unable to retrieve data"
else:
print
class Gpa(object):
# data attributes
"helps to calculate the Gpa and Cgpa"
arg1 = None
arg2 = None
subData = None
Scale = None
credits = None
initCourse = 0
initgetCredit = 0
totalCredits = 0
temp = 0
def getCourse(self):
"get the value of the no of course you registered"
self.arg1 = input("No of courses you have registered: " )
pass
def getSubject(self,value):
"get the subject value"
self.arg2 = value
pass
def getScale(self):
"To get the scale value"
self.Scale = input("Enter the Scale value(Either 5 or 10): " )
pass
def getSubjectData(self):
"get the subject Data in string"
self.subData = raw_input("Enter the grade: " )
pass
def getGradeData(self):
# To calculate grade for two scale,one is for 5.0 and other one for 10.0
if self.Scale == 10:
grade1 = {'s':10,'a':9,'b':8,'c':7,'d':5,'e':3,'f':0}
x=grade1[self.subData]
def gpa(self):
print "Calculate GPA:"
name=raw_input("Please what is your name ? ")
sem = raw_input("Please Enter Semester: " )
self.getScale() #input the scale value
if self.Scale == 5 or self.Scale == 10:
self.getCourse()
if self.arg1 >= 2:
self.calculateGpa()
else:
print "In order to calculate GPA you should have at least 2 subject minimum"
else:
print "you have not entered the scale correctly please try again"
pass
def calculateGpa(self):
"Method to calculate GPA "
while self.initCourse!=self.arg1:
self.initCourse=self.initCourse+1
self.getCredits()
self.initgetCredit = self.credits
self.getSubjectData()
#type(self.getSubjectData())
self.temp = self.initgetCredit*self.getGradeData()+self.temp
self.totalCredits=self.totalCredits+self.initgetCredit
gpa = round((self.temp+.0)/(self.totalCredits+.0),2)
print "Your Total Credit Units Load is:"+" "+str(self.totalCredits)+" "+"and your GP
is :\""+str(gpa)+"\""
pass
def cgpa(self):
print
"##################################################################"
print "Calculate your CGPA: "
name=raw_input("Please what is your name ? ")
semesters = input("Enter how many semester CGPA you wish to calculate: " )
counter = 0
tempInit = 0
tempTotalCredits = 0
self.getScale() #input the scale value
if self.Scale == 5 or self.Scale == 10:
while counter != semesters:
counter = counter+1
print "Please enter the details of the semester"+" "+str(counter)
self.getCourse()
self.calculateGpa()
tempInit = self.temp+tempInit
tempTotalCredits = tempTotalCredits + self.totalCredits
# re-assigning
self.arg1=0
self.initCourse =0
self.temp=0
self.totalCredits=0
print "\n"
cgpa = round((tempInit+.0)/(tempTotalCredits+.0),2)
print name+", Your Total Credit Units Load is:"+" "+str(tempTotalCredits)+" "+"and
your CGPA is :\""+str(cgpa)+"\" "
if cgpa > 4.5:
print "You have bagged a First-Class!"
elif cgpa < 4.5 and cgpa > 3.5:
print "You have bagged a Second-Class Upper (2.1)!"
elif cgpa < 3.5 and cgpa >2.5:
print "You have bagged a Second-Class Lower (2.2)!"
elif cgpa < 2.5 and cgpa > 1.5:
print "You have bagged a Third-Class!"
elif cgpa <1.5:
print "You have a Pass!"
try:
insert ="INSERT INTO RESULT(NAME,CUL,GP) VALUES ('%s', '%s', '%s')" %
(name,tempTotalCredits,cgpa)
cursor.execute(insert)
print "Records saved Successfully!"
con.commit()
except:
print "Error: Unable to save record!"
else:
print "you have not entered the scale correctly please try again"
pass
#output:
con.close