Comparison between Java and Python
The last session was on the pros and cons of Python. In this Python Vs Java Tutorial, we will study a basic difference between java and python. The comparison between Java and Python on the basis of syntax, simplicity, speed, interpreted, database accessibility etc.
So, let’s start Python Vs Java.
To rigorously compare Python and java, we first compare the first program in any programming language- to print “Hello World”.
Now, let’s try printing the same thing in Python.
As you can see, what we could do with 7 lines of code in Java, we can do with 1 line in Python.
Let’s further discuss parts of this program, and other things.
A striking characteristic of Python is simple python syntax. Let’s see the subtle differences.
Python statements do not need a semicolon to end, thanks to its syntax.
But it is possible to append it. However, if you miss a semicolon in Java, it throws an error.
Compilation error #stdin compilation error #stdout 0.09s 27828KB
Main.java:10: error: ‘;’ expected
In Java, you must define blocks using semicolons. Without that, your code won’t work. But Python has never seen a sight of curly braces. So, to define blocks, it mandates indentation. Some lazy programmers don’t go the extra mile to indent their code, but with Python, they have no other choice. This indentation also aids readability. But you must compliment the indentation with a colon ending the line before it.
This code would break if we added curly braces.
SyntaxError: expected an indented block
Now, let’s see if we can skip the curly braces and indentation in Java.
Success #stdin #stdout 0.09s 28020KB
As you can see here, 2 isn’t less than 1, so the if statement’s body isn’t executed. Since we don’t have curly braces here, only the first print statement is considered to be its body. This is why here, only the second statement is executed; it isn’t in the if’s body.
Starting Python 3.x, a set of parentheses is a must only for the print statement. All other statements will run with or without it.
SyntaxError: Missing parentheses in call to ‘print’
This isn’t the same with Java, where you must use parentheses.
Comments are lines that are ignored by the interpreter. Java supports multiline comments, but Python does not. The following are comments in Java.
Now, let’s see what a comment looks like in Python.