Java 9 vs Python 3 code compare

For many years there is a rivalry between Java and Python programmers and constant fight which language is better. A popular image showing both languages generation simple start pyramid is circulating the web. This is the Java version:

In post:

Update 2018 July: Python 3.7 was released a few days ago and many new features were introduced in this release. If you want to read more go here: Python 3.7 features.
Next big version for Java SE 11 (18.9 LTS) is expected to be launched in September. For more information about the last Java 10 check here: Java 10 what's new and how to install

Java vs Python pyramid example

public class JavaPyramidl {
    public static void main(String[] args) {
        for(int i=1; i<=5; i++){
            for(int j = 0; j<i; j++){
                System.out.print("*");

            }

//generate a new line
            System.out.println("");

        }
    }
}

and this is the python:

def create_pyramid(rows):
    for i in range(rows):
        print('*' * (i+1))

There are several points that could be mentioned:

  • there are newer versions of Java allowing you to code shorter program
  • the two snippets has differences
  • comments
  • class definition
  • python version should call a method

How to rewrite Java version to Java 9

In Java 9 you can use jshell so there's no need of class. You can use lambda expressions and you could avoid the two loops. A sample program which is valid in Java 9 could be:

first you need to start jshell by:

jshell

More about Java 9 jshell: Java 9 play with jshell

And then simple execute:

import java.util.stream.IntStream;
IntStream.range(0, 5 + 1).forEach(
        k -> {
            System.out.println(new String(new char[k]).replace("\0", "*"));
        }
);

and if you want to do it as method:

import java.util.stream.IntStream;
public static void pyra(int n) {
    IntStream.range(0, n + 1).forEach(
            k -> {
                System.out.println(new String(new char[k]).replace("\0", "*"));
            }
    );
}

Most probably there other ways to rewrite this program in Java 9 in shorter and more readable way. If you find any please do share them.

Java 9 vs Python 3

Still python version looks shorter and it's easier to be read. Since this was the idea of python to be short and easy for reading this is normal.

On the other hand Java is evolving and it's improving by adding new features and ways for developer to test and code his programs. Both languages are mature enough and have their communities and products. In my works and projects I use both of them and I can say that the problem is not about the language and how to write it shorter. The problem is how to write clever, well organized and working code.

I know endless number of programs written badly in many languages. And my conclusion is that:

  • understand the problem
  • you need to be able to write the program in meta code
  • be able to define working algorithm which covers all cases and side-effects
  • and finally to write the program in your language

So from this point of view in many aspects Java 9 and Python 3 could be helpful for solving such simple technical problems. The choice of the language should depend on the available libraries and support for them rather than syntax beauty.

Java vs Python in 6 sentences

The Java features:

  • Java is a bit faster(depending on what you are doing and what versions you are using) in comparison to to Python.
  • Java is statically typed - it forces you to define the type of a variable (when you first declare it; this is changed in the latest version for local variables).
  • Java syntax uses braces in order to define scope of functions and statements
  • Java is famous for its platform-independent applications
  • Java has a Virtual Machine which is a virtual computing environment with a specific set of instructions. A Java compiler converts Java language into a byte-code stream.
  • Java may become commercial in future for Long Term Support (LTS) versions

The Python features:

  • Python code is much compact and easier to read and maintain. Many people claim that Python is easier and faster for development with nicer learning curve comparing to Java
  • Python is dynamically typed - no need to declare type of the variable (the object can be of any type)
  • Python use indent syntax - this force the programmer to write better and more beautiful code
  • Python is powerful tool for Data Science and Machine Learning because of it's huge set of scientific libraries.
  • Python has Interpreter - translates source code into some efficient intermediate representation (code) and immediately executes this.
  • All Python releases are Open Source

Groovy create pyramid

If you want to see the create pyramid in Groovy language which is one of the top paid according to StackOverFlow survey for 2018:

Top paid languages

(0..5).each{
    println '*' * (it +1)
}

and now lets compare to python. I want also to say that there could be a shorted and better way to write in python 3:

def create_pyramid(rows):
    for i in range(rows):
        print('*' * (i+1))
create_pyramid(5)    

I like to write simple programs in groovy and test algorithms because it's simplicity and expressiveness.

Translate Java code into Beautiful, Idiomatic Python

There is a great talk by Raymond Hettinger about:

Transforming Code into Beautiful, Idiomatic Python

In this video he gave many points which has to be considered when you write code in Java or Python. In this section I would like to mention some of them.

Concatenating Strings

They are so many different ways of creating, manipulating and concatenating strings. Most of the time we even don't think about which one should be used. In the video the Raymond is giving an example:

names = ['raymond', 'rachel', 'matthew', 'roger']

s = names[0]

for name in names[1:]:
    s += ', ' + name
println s

And the more pythonic and natural way which is:

names = ['raymond', 'rachel', 'matthew', 'roger']
println ', '.join(names)

As you can see the second example is much more readable and easier to be maintained. This can be applied to both languages Java and Python since Java is also supporting method join. Of course the first example is not wrong or bad it's just unnatural way for Python world.

Clarify function calls with keyword arguments

Another good point and potential difference between Java and Python would be functions calls and the way we work with arguments. Take a look on the next two examples:

twitter_search('@obama', False, 20, True)

twitter_search('@obama', retweets=False, numtweets=20, popular=True)

The key point of this is to leverage micro seconds of execution time against hours of the programmer for debug and analyze. Maybe faster, smaller and optimized in not always the best option. There are hidden limits which shouldn't be passed if we want to have clear code.

Unpacking sequences

How to unpack sequences and collections is another point which can make huge difference in your code - Java and Python. Let's have a look on this code example:

p = 'Raymond, 'Hettinger', 0x30, 'python@example.com'

fname = p[0]
lname = p[1]
age = p[2]
email = p[3]

and this one:

fname, lname, age, email = p

As he mentioned in the video the first one is working on many languages and programmers used it because they know it. But the second one is more readable and faster.

Here is good to mentioned that first example is perfectly OK for some languages. But if your language supports the second syntax then you need to choose one of the two ways. And it's more important to not mix the ways in your project. Because if you start to use different code styles and techniques you will end with something ugly and difficult for reading.

Looping over dictionary keys

Raymond mentioned two points about dictionaries:

  • Mastering dictionaries is a fundamental Python skill
  • They are fundamental tool for expressing relationships, linking, counting and grouping

Here is the code example:

d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}

for k in d:
    print k
    
for k in d.keys():
    if k.startswith('r'):
        del d[k]

The difference between the two ways of iterating over the keys of a dictionary is that the second way create a list of keys which allow you to modify the dictionary without problems of getting unknown start - modifying and reading something at the same time.

Related Article