Python vs Java: Which is best? Code examples and comparison for 2019

| 9 min. (1833 words)

Should you choose Java or Python for your next project? Are you fortunate enough to have a choice? Are one of these languages a better option?

According to GitHub’s annual Octoverse report, Java and Python are the second and third most popular languages for the fourth year in a row. According to the same story, Python is one of the top ten fastest growing languages. Most of the other fast-gainers are new languages, while Python has been around longer than Java.

At the time of writing, the TIOBE index places Java at the top of their list and Python at number three. Python moved up a spot this month (December 2018), after sitting at number four for over a year.

Digital Ocean’s recent language survey places Python at number two on their list of languages for open source projects. Java is in fourth place, with only half the adoption of Python.

So, the two languages are popular and aren’t going anywhere. Which one is your best choice?

Java vs. Python in 2019

Java and Python have many similarities. Both languages have strong cross-platform support and extensive standard libraries. They both treat (nearly) everything as objects. Both languages compile to bytecode, but Python is (usually) compiled at runtime. They are both members of the Algol family, although Python deviates further from C/C++ than Java does.

Support for Python 2.x will end on January 1, 2020. For a long time, Python development has fragmented between version 2.7 and the regular releases of new 3.x versions. But, with the end-of-life date for Python 2 a year away, the question over which version to use is settled. The community has centered on Python 3.

Meanwhile, Oracle’s new release model for Java created a lot of fear, uncertainty, and doubt in the software community. Even though the announcement provided a free (as in beer) option and a clear upgrade path, confusion continues to reign. Several platforms providers, such as Red Hat and Amazon, have stepped in to support OpenJDK. But the once unified Java community is more fragmented than Python ever was. Let’s take a closer look at the similarities and differences between Java vs. Python.

Java vs. Python typing

Python and Java are both object-oriented languages, but Java uses static types, while Python is dynamic. This is the most significant difference and affects how you design, write, and troubleshoot programs in a fundamental way. Let’s look at two code examples.

First, in Python, we’ll create an array with some data in it, and print it to the console.

stuff = ["Hello, World!", "Hi there, Everyone!", 6]
for i in stuff:
    print(i)

Next, let’s try it in Java.

public class Test {
    public static void main(String args[]) {
        String array[] = {"Hello, World", "Hi there, Everyone", "6"};
        for (String i : array) {
          System.out.println(i);
        }
    }
}

In Python, we put two strings and an integer in the same array, and then printed the contents. For Java, we declared a List of Strings and put three string values in it.

We can’t mix types in a Java array. The code won’t compile.

 String array[] = {"Hello, World", "Hi there, Everyone", 6};

We could declare the array as containing Object instead of String, and override Java’s type system. But, that’s not how any experienced Java developer uses the language.

In Python, we don’t have to provide a type when we declare the array and can put whatever we want in it. It’s up to us to make sure we don’t try to misuse the contents.

For example, what if we modified the code above to do this?

stuff = ["Hello, World!", "Hi there, Everyone!", 6]
for i in stuff:
    print(i + " Foobar!")

The above code will throw an error when we try to run it since we can’t append an integer with a string. What are advantages and disadvantages to dynamic typing and static typing?

Static typing catches type errors at compile time. So, if mixing strings and integers weren’t what you wanted to do, the Java compiler catches the mistake. How much of an advantage compile-time checks is up for debate in some circles. But, static typing does enforce a discipline that some developers appreciate.

Whether static typing prevents errors or not, it does make code run faster. A compiler working on statically-typed code can optimize better for the target platform. Also, you avoid runtime type errors, adding another performance boost.

Code that’s written with dynamic types tends to be less verbose than static languages. Variables aren’t declared with types, and the type can change. This saves a copy or type conversion to new variable declarations.

The question of code readability comes up often when debating Java vs. Python. Let’s take a look at that next.

Code readability and formatting

Let’s take an example from Java and Python and compare them. In this example, we need to open a large text file and collect each line into sets of 50 comma-separated records. Here is the Python code:

def get_symbols(file_name):
    with open(file_name, "r") as in_file:
        records = []
        count = 0
        symbol_set = ""
        for line in in_file:
            symbol_set = symbol_set + line[:-1] + ','
            count = count + 1
            if count % 50 == 0:
                records.append(symbol_set)
                symbol_set = ""

        symbols.append(symbol_set)
        return records

Here’s the Java code:

List<String> getSymbols(String filename) throws IOException {
  List<String> records = new ArrayList<>();
  try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
    String line;
    int count = 0;
    StringBuilder symbol_set = new StringBuilder();
    while ((line = reader.readLine()) != null) {
      symbol_set.append(line).append(",");
      count++;
      if ((count % 50) == 0) {
        records.add(symbol_set.toString());
        symbol_set.setLength(0);
      }
    }
    records.add(symbol_set.toString());
    return records;
  }
}

Whitespace

Whitespace is part of Python’s syntax, while Java ignores it. Python uses tabs for nesting and a full colon to start loops and conditional blocks. Java ignores whitespace and uses semicolons, parentheses and curly braces. Arguments over which code is easier to read, like the debate over static vs. dynamic typing, are subjective. Some say Python code is more concise and uniform than Java because your formatting choices are more limited. Python’s use of whitespace ends debates over how to format code. The only option you have left is how to use blank lines.

The Python snippet is a few lines shorter than the Java snippet, a difference that adds up in larger programs. Much of the difference is because there are no closing braces. But Python’s brevity—when compared to Java —goes deeper.

Brevity

Let’s look at how the two languages handle files.

Here’s Python again:

with open(file_name, "r") as in_file:

Here’s Java:

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {

In both cases, the declaration creates a block. The file resource remains in scope, and the languages close it when the code exits the block.

In Python, we’re opening a file and reading from it. When the loop reaches the end of the file, the loop exits.

for line in in_file:

Java is more complicated. We’re opening a BufferedReader by passing it a FileReader. We consume lines from the reader. It’s our responsibility to check for null when the file ends.

while ((line = reader.readLine()) != null) {

This only demonstrates that it’s easier to handle text files in Python. But, it demonstrates how Java tends to be more verbose than Python. “Pythonic” constructs are more concise and less demanding. Java has evolved over the past few releases, with the introduction of try-with-resources in Java 7 and lambdas in Java 8, but it’s still a verbose language.

Let’s revisit our first example.

Here’s the Python again:

stuff = ["Hello, World!", "Hi there, Everyone!", 6]
    for i in stuff:
        print(i)

Here is the Java:

public class Test {
    public static void main(String args[]) {
        String array[] = {"Hello, World", "Hi there, Everyone", "6"};
        for (String i : array) {
          System.out.println(i);
        }
    }
}

Both of these snippets will build and run as is. Python will run a script from beginning to end of a file. Java requires at least one entry point, a static method named main. The JVM (Java virtual machine) runs this method in the class passed to it on the command line.

Putting together a Python program tends to be faster and easier than in Java. This is especially true of utility programs for manipulating files or retrieving data from web resources.

Performance

Both Java and Python compile to bytecode and run in virtual machines. This isolates code from differences between operating systems, making the languages cross-platform. But there’s a critical difference. Python usually compiles code at runtime, while Java compiles it in advance, and distributes the bytecode.

Most JVMs perform just-in-time compilation to all or part of programs to native code, which significantly improves performance. Mainstream Python doesn’t do this, but a few variants such as PyPy do.

The difference in performance between Java and Python is sometimes significant in some cases. A simple binary tree test runs ten times faster in Java than in Python.

Final thoughts on Java vs. Python

So, which language is your best choice?

Oracle’s new support model changes the Java landscape. While there is still a free option, the new release schedule and support model gives developers a reason to take stock. Java clients will need to pay Oracle for support, change OpenJDK versions on a regular basis, or rely on third parties like Red Hat or Amazon for fixes and security updates.

At the same time, Python has cleared a significant hurdle with Python 3. Python has a more unified support model than Java for the first time, and open source developers are focusing their efforts on the latest version of the language. I have to give Python the edge here.

Whether Python’s dynamic typing is better than Java’s static approach is subjective. The debate between the two models predates both of them, and it’s a question of what’s best for you and your team.

After working on large projects in both languages, I feel secure saying that Python’s syntax is more concise than Java’s. It’s easier to get up and running quickly with a new project in Python than it is in Java. Python wins again.

Performance is where Java has a substantial advantage over Python. Java’s just-in-time compilation gives it an advantage over Python’s interpreted performance. While neither language is suitable for latency-sensitive applications, Java is still a great deal faster than Python.

All things considered, Python’s advantages outweigh the disadvantages. If you’re not already considering it, give it another look.

In any project, whether you choose Python or Java make sure it’s error free with the Raygun Platform. Raygun automatically detects errors and performance problems with sophisticated Error Monitoring, Real User Monitoring, and Application Performance Monitoring. Learn more.