DEV Community

Cover image for How to Approach Python From a Java Perspective
Jeremy Grifski
Jeremy Grifski

Posted on • Originally published at therenegadecoder.com on

How to Approach Python From a Java Perspective

Right now I’m taking a break from sharing updates on the image-titler script and reflecting on teaching to respond to a request from a former student. In one of my course evaluations, they asked me to write an article on how to approach Python as someone who knows Java. Naturally, I thought that would be a lot of fun, so here it is!

In short, in order to approach Python from a Java perspective, I recommend learning how the two languages compare (e.g. compiled vs. interpreted, static vs. dynamic typing, etc.). Then, I recommend learning Python’s idioms, using those idioms, and writing about your experience. There’s no better way of learning than to dive in.

Hopefully, this gives you a good overview of what to expect in this article. Keep reading for more details!

Understanding My Expertise

Before we get started, I thought it might be helpful to share exactly why I’m qualified to write this article. If that’s not interesting to you, feel free to jump to the next section. Otherwise, here’s my story.

When I first learned to program, I was 18 and a freshman in college. At the time, I was taking an introductory Java course, so naturally Java became my first programming language.

Over the next four years, I picked up a language or two to get through some other courses. For instance, I learned C/C++ while on an internship—which I ended up using for an operating systems course as well as a graphics course. Around the same time, I also picked up C# for game development and MATLAB for simulation and modeling. In addition, I even messed around with more specialized languages like Verilog and the Arduino language (i.e. C-ish).

In all my years of college, I never once touched Python. That wasn’t until I was about a year into my first engineering job. At that point, I had largely stayed in the Java and C/C++ space. Suddenly, I was stuck picking up a brand new language.

Of course, if any of you have worked a full time job, you know how quickly you’re able to pick things up. As a result, I was able to wrap my head around the syntax in just a couple of weeks.

That said, the code I wrote wasn’t great. In general, I spent a lot of time thinking about how to organize the code the way a Java programmer would. For instance, I spent a lot of time trying to convert code into objects when that wasn’t always necessary. Likewise, I felt myself falling into the same sort of iterative looping mechanisms that I might use in Java.

Over time, I began to think of Python as its own language, separate from Java. However, this was a long process, so I figured I’d put together this article of approaches to help you out.

What Differentiates Python From Java?

Typically, when a student asks me to teach them a little Python, I like to start by looking at what makes the languages different. That way, we get an idea of what we need to learn. As a result, this section will call out some of the main differences between the two languages. Then, we’ll take a look at how they’re similar.

Compiled vs. Interpretted

Perhaps the biggest difference between Java and Python is the fact that one is compiled (Java) while the other is interpreted (Python). Basically, that means that one language has to be translated as a unit (Java) while the other can be translated on-the-fly (Python).

To illustrate this concept, I like to share a common introductory program, Hello World, in both languages:

public class HelloWorld { 
  public static void main(String[] args) { 
    System.out.println("Hello, World!") 
  }
}
Enter fullscreen mode Exit fullscreen mode
print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

Here, we can see that the Java version requires quite a bit of boilerplate. That’s because we’re dealing with a compiled programming language. As a result, there needs to be some structure to indicate where to begin executing the code (i.e. the main method).

On the flip side, Python, the interpreted language, only needs to call the print() function directly. After all, this command is assumed to be executed within a sequence of statements on-the-fly. In other words, there’s no need to provide an entry point.

Naturally, this makes Python a nice scripting language. Basically, that means we can write sequences of commands into a file to be executed as needed. For example, here’s a script that prints the current date and time:

import datetime
print(datetime.datetime.now())
Enter fullscreen mode Exit fullscreen mode

For this “script” to work in Java, we’d have to compile it first and run the binary. Unfortunately, that means we can’t really make any changes without compiling the program again.

On the other hand, Python is pretty quick to modify. For instance, here’s that same program but with an additional label:

import datetime
print(f"The current date and time is {datetime.datetime.now()}")
Enter fullscreen mode Exit fullscreen mode

How cool is that?

Static vs. Dynamic Typing

Another fundamental difference between Java and Python is how variables are typed. Specifically, Java is statically typed while Python is dynamically typed. In essence, this means that Java variables are type checked at compile time while Python variables are type checked at runtime.

To understand the difference, let’s once again take a look at some code snippets:

public class FiveFactorial { 
  public static void main(String[] args) { 
    int total = 1; 
    for (int i = 1; i <= 5; i++) { 
      total *= i; 
    } 
    System.out.print(total); 
  }
}
Enter fullscreen mode Exit fullscreen mode
total = 1
for i in range(1, 6): 
  total *= i
print(total)
Enter fullscreen mode Exit fullscreen mode

Here, the most obvious difference is that the variables in Java have to be explicitly typed. In other words, we have to say we want to store an integer before we can actually do that. On the flip side, Python types (aka type hints) are not required, and I don’t believe they were formally included in the language until Python 3.5.

Of course, to avoid confusion, it’s possible to have a statically typed language that doesn’t require explicit typing (see Kotlin). That said, I think the lack of explicit types is the most jarring change of Java developers. Luckily, type hinting is available and encouraged. Here’s the same sample with type hints added:

total: int = 1
i: int
for i in range(1, 6): 
  total *= i
print(total)
Enter fullscreen mode Exit fullscreen mode

All this does is help you catch some bugs in editors like PyCharm. Type hints will not stop you from running code.

Braces vs. Spaces

At this point, you’ve probably noticed, but one of the more jarring differences between Java and Python is how scope is defined. In Java, we define blocks using braces. Meanwhile, in Python, we define blocks using spaces. To me, this is an elegant way of expressing readability in the language syntax because it forces you to maintain consistent spacing.

Of course, there’s no point in chatting without an example. Let’s once again take a look at the factorial example:

public class FiveFactorial { 
  public static void main(String[] args) { 
    int total = 1; 
    for (int i = 1; i <= 5; i++) { 
      total *= i; 
    } 
    System.out.print(total); 
  }
}
Enter fullscreen mode Exit fullscreen mode
total = 1
for i in range(1, 6): 
  total *= i
print(total)
Enter fullscreen mode Exit fullscreen mode

In the Java example, we can see that there are three levels of nesting based on the three sets of braces. Of course, we also see that by the indentation, but that’s not strictly necessary:

public class FiveFactorial {
public static void main(String[] args) {
int total = 1;
for (int i = 1; i <= 5; i++) { total *= i; }
System.out.print(total);
}
}
Enter fullscreen mode Exit fullscreen mode

Here, we’ve decided to compress the loop to a single line. In addition, we’ve eliminated all indentation. Regardless, the compiler will be happy. On the other hand, your fellow developers (or your future self) will not be too happy with you.

Meanwhile, Python doesn’t really allow for this sort of restructuring of code. In fact, we’ll get a syntax error:

total = 1 
for i in range(1, 6): 
total *= i
print(total)
Enter fullscreen mode Exit fullscreen mode

If you try to run this, you’ll get the following error:

SyntaxError: expected an indented block
Enter fullscreen mode Exit fullscreen mode

Basically, this means that the interpreter was expecting some sort of nested block, but it didn’t find it. As a result, the program crashed.

At any rate, certainly there are other ways that Python and Java are different, but these cover the main difference from a beginner’s perspective. In the next section, we’ll take a look at how the languages are the same, so you can maximize the overlap.

What Makes Java and Python Similar?

As promised, we’ll now take a look at how Java and Python are the same—or at least similar. You’d be surprised by how much overlap there actually is.

Programming Paradigms

If you have a background in Java, you’ll be glad to know that Python is largely imperative in nature. Essentially, that means that both program languages leverage statements to update the program’s state.

If you’re not familiar with some of the other programming paradigms, this might not be the most useful information. That said, this means that you won’t really have to stretch your idea of what programming means when learning Python. If you’re already comfortable with the idea of expressions and statements, those concepts will continue to be useful in Python.

All that said, Java sort of binds you to the realm of Object-Oriented Programming (OOP). In Python, you’re not as restricted. You’re free to use the language in whatever paradigm you please which includes OOP and even functional programming (FP).

Also, you can have more than one top-level class per file in Python. It’s glorious!

General Syntax

One of the nice things about Python is that it takes the syntax from languages like Java and cleans them up a bit. For example, the while loop in Python is much like its counterpart in Java, but it drops the parentheses and braces and picks up a colon:

int i = 0;
while (i < 10) { 
  i++;
}
Enter fullscreen mode Exit fullscreen mode
i = 0
while i < 10: 
  i += 1
Enter fullscreen mode Exit fullscreen mode

Meanwhile, conditionals follow the same sort of pattern:

int i = 0;
if (i == 1) { 
  System.out.println("This is dead code, buddy!");
}
Enter fullscreen mode Exit fullscreen mode
i = 0
if i == 1: 
  print("This is dead code, buddy!")
Enter fullscreen mode Exit fullscreen mode

Of course, you’ll have to get used to using elif over else if, but that shouldn’t take too long!

Likewise, many of the same operators are intact including all of the following:

  • Arithmetic Operators: +, -, *, %
  • Relational Operators: <, <=, ==, >=, >

Of course, Python messes around with division by including both / and //. In addition, Python ditches the usual boolean operators and replaces them with their English counterparts: and, or, and not.

That said, I think you’ll find that it’s pretty easy to pick up Python given what you already know about the syntax of Java. Of course, the biggest change will be forgetting about braces and semicolons. But, you got this!

The Standard Library

One of the great things about using Java is its standard library. For instance, if you need a data structure like a list, you’ll find several implemented for you in the standard library. Luckily, Python also has an excellent standard library, and it’s available right at your fingertips.

For example, do you need a queue for something? Here’s a queue code snippet from both standard libraries:

import java.util.LinkedList; 
import java.util.Queue; 

public class QueueExample { 
  public static void main(String[] args) { 
    Queue<Integer> q = new LinkedList<Integer>(); 
    // Do queue things 
  }
}
Enter fullscreen mode Exit fullscreen mode
import queue
q = queue.Queue()
# Do queue things
Enter fullscreen mode Exit fullscreen mode

Likewise, with the addition of a nice package manager like pip, you’ll even be able to expand the standard library with 3rd party packages developed for just about everything. For instance, I’m using a few packages in my image-titler script including Pillow and Matplotlib.

Approaching Python From a Java Perspective

Now that we’ve taken a moment to compare the two languages, I figured I could put together a list of tips to help you transition. Feel free to take these tips with a grain of salt; only you will be able decide what’s useful.

Learn the Idioms

Python is an idiomatic language. Basically, that means there are certain ways of solving certain problems that are standard in the community. Typically, these idioms are outlined in the Python Enhancement Proposals (PEPs), but you’ll tend to run into them in the wild first.

One of the common idioms I think of that’s just not possible in Java is the emptiness test for strings:

if (s.length() == 0) { 
  // Do the thing
}
Enter fullscreen mode Exit fullscreen mode
if s: 
  # Do the thing
Enter fullscreen mode Exit fullscreen mode

As a Java programmer, it might be tempting to check if a string is empty by testing for the length of the string. While that’s certainly possible in Python, it’s typically more idiomatic to leverage the variable’s type flexibility. See, in Python, variables can evaluate to booleans under certain conditions. For example, an empty string is perceived as False while a string of any length is perceived as True.

Another common example of a Python idiom is looping. If we wanted to traverse an array, we might be tempted to use a for loop in Java. In Python, however, the traditional for loop doesn’t exist. Instead, Python programmers use what’s often referred to in Java as the enhanced for loop or the for-each loop:

int[] arr = {1, 2, 3}
for (int i = 0; i < arr.length; i++) { 
  // Do the thing
}
Enter fullscreen mode Exit fullscreen mode
arr = [1, 2, 3]
for item in arr: 
  # Do the thing
Enter fullscreen mode Exit fullscreen mode

If for some reason you need the indices, you’ll have to use the enumerate() function.

Unfortunately, there are quite a few idioms you’ll have to learn in Python. That said, your code won’t be bad if you don’t use idioms; it’ll just be a little slower and less readable.

If you’re interesting in exploring some idioms, I actually write about them all the time. In fact, I have an entire series dedicated to solving common problems in Python. Almost every article features a clean idiomatic solution.

Use the Language

One of the less appetizing pieces of advice is use the language. After all, you can study all day, but until you actually try to solve your own problems, you’ll never really know the language.

That said, I figured I’d get you started by curating a little list of Python projects you can try:

Keep in mind that none of these projects are mine, so I didn’t thoroughly vet them or anything. That said, I thought the titles were enticing and perhaps a good place for you to start (although maybe too difficult for a true beginner).

If you don’t like any of these options, you can always come up with your own. After all, you already know Java, so maybe you can rewrite some of your old projects in Python.

Write About What You’ve Learned

One of the quickest ways to assess your learning is to explain your understanding. If you can articulate exactly why something works, you’ll reinforce the learning process.

To make this less scary, you can try jotting down the learning process in a notebook. Or, if you want to take your learning to the next level, you can write up a quick blog post on a site like dev.to. If done right, you might be able to help out beginners just like yourself.

If you’re worried about rehashing the same old concepts on the internet, don’t be! I don’t think there’s any shame in writing content that already exists on the internet because it serves to reinforce your own learning. Likewise, we could all benefit from another perspective.

Start Coding!

At this point, there’s not much else for me to say, so let me summarize. First, when learning Python, it’s important to compare and contrast Python with the language you already know, Java. In terms of differences, I identified three:

  • Python is interpreted while Java is compiled
  • Python is dynamically typed while Java is statically typed
  • Python uses spaces for code blocks which Java uses braces

Naturally, there are probably thousands of differences, but these were the big three for me.

On the flip side, there Python is similar to Java in a lot of ways. For the purposes of brevity, I picked three:

  • Both Java and Python share the imperative programming paradigm
  • Both Java and Python share general syntactic elements like loops and conditionals
  • Both Java and Python share the idea of a vast standard library

Once we compared an contrasted the languages, I shared three tips to help you through the transition:

  • Learn the Python idioms
  • Use Python to build projects
  • Write about everything you’ve learned

Hopefully, these 2500+ words give you a decent starting point on your transition. As someone who had to go through a similar transition, I wish you the best of luck and keep grinding!

If you enjoy this kind of content, I’d appreciate it if you showed the site some love by checking out my list of ways to grow the site. For instance, that post will point you to my mailing list as well as my YouTube channel and Patreon. Every little bit helps!

While you’re here, here’s a list of related posts:

Thanks again for hanging out! I appreciate it.

Top comments (0)