Java vs. Python (1): Simple Code Examples

Some people have claimed that Python is more productive than Java. It is dangerous to make such a claim, because it may take several days to prove that throughly. From a high level view, Java is statically typed, which means all variable names have to be explicitly declared. In contrast, Python is dynamically typed, which means declaration is not required. There is a huge debate between dynamic typing and static typing in programming languages. This post does not talk about that. However, there is one thing that can be agreed - Python is an interpreted language with elegant syntax and that makes it a very good option for scripting and rapid application development in many areas.

In this comparison, I will try to cover some basic language components, such as string, control flow, class, inheritance, file i/o, etc. All of them will be compared by using side-by-side examples. I hope this can provide java programmers a general idea of how Python and Java do the same thing differently. By a glance of the code below, we can easily realize that Python code is much shorter, even though some Java "class shell" (In Java everything starts with a class definition) is not listed. This might be one reason why Python can be more productive.

1. Hello World
Start with the simplest program. Java needs a lot of words for printing just a string. This is the first example showing Python is more concise.

Java Python
public class Main {
  public static void main(String[] args) {
     System.out.println("hello world");
print "hello world";

Fist of all, whatever we do in Java, we need start with writing a class, and then put our desired method(s) inside. This is sometimes very annoying and it does waste time. In Python, you can simply start writing your code, and then run it.

2. String Operations

public static void main(String[] args) {
  String test = "compare Java with Python";
	for(String a : test.split(" "))
a="compare Python with Java";
print a.split();

There are a lot of string related functions in Python which is as good as or better than Java, for example, lstrip(), rstrip(), etc.

3. Control Flow

int condition=10;
	System.out.println("> 10");
	System.out.println("<= 10");
case 1: 
System.out.println("is 1"); 
case 2: 
System.out.println("is 2"); 
for(int i=0; i<10; i++){
# if
if condition > 10:
    print ">10";
elif condition == 10:
    print "=10";
    print "<10";        
while condition > 1:
    print condition;
    condition = condition-1;
def f(x):
    return {
        1 : 1,
        2 : 2,
print f(condition);
for x in range(1,10):
    print x;

4. Class and Inheritance

class Animal{
	private String name;
	public Animal(String name){ = name;
	public void saySomething(){
		System.out.println("I am " + name);
class Dog extends Animal{
	public Dog(String name) {
	public void saySomething(){
		System.out.println("I can bark");
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog("Chiwawa");
class Animal():
        def __init__(self, name):
   = name
        def saySomething(self):
            print "I am " +    
class Dog(Animal):
        def saySomething(self):
            print "I am "+ \
            + ", and I can bark"
dog = Dog("Chiwawa") 

When you extend a base class, there is no requirement such as defining an explicit constructor for implicit super constructor.

5. File I/O

File dir = new File(".");// get current directory
File fin = new File(dir.getCanonicalPath() + File.separator
				+ "Code.txt");
FileInputStream fis = new FileInputStream(fin);
// //Construct the BufferedReader object
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = null;
while ((aLine = in.readLine()) != null) {
	// //Process each line, here we count empty lines
	if (aLine.trim().length() == 0) {
// do not forget to close the buffer reader
myFile = open("/home/xiaoran/Desktop/test.txt")

As we can see that there are a lot of classes we need to import to simply read a file, and in addition, we have to handle the exception thrown by some methods. In Python, it is two lines.

6. Collections

import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<String> al = new ArrayList<String>();
aList = []
print aList;

These comparisons only stand on the surface of Python, for real programming, the Python doc is still the best place to go for reference.

Category >> Python >> Versus  
If you want to post code and let me or someone else review it, please format your code in eclipse and put the code inside <pre> and </pre> tags.
  • Giant Duck

    Python is glue code it does not exist without C++. Java is C++

  • Sourabh Bhat

    Hi Pedro Forli,
    By using the statement ” stop at ‘hello world’ “, I meant for learning to program. As it is very well known that the learning curve for Python is very smooth. “According to me”, based on my experience, I feel that dynamically typed languages are not well suited for large projects as things get very messy pretty soon; especially when lot of people are working on a project. Also there is only so much that a IDE can do, to prevent bugs before they get inserted, due to the dynamic nature of the language.

    The second thing is the speed of execution. When learning and testing we are normally not bothered about the speed, but when we run the code for real problems Python takes a toll. For example, my code for numerical computations (CFD code) in Java runs about 10-15 times faster than Python. Which means that I have to wait for about 10-15 days to get results instead of 1 day!! The projects like numba and PyPy for jit compilation in Python may change things for Python in future, I suppose.

    That being said, I myself use Python extensively for testing my algorithms quickly and also I use matplotlib a lot. And I use Java for real applications. C/C++ are awesome but they do not port to different operating systems / architectures very well.

  • Pedro Forli, I do think there are several cases where you should use java over python (I have made programs in both languages as well), but saying that Python is intended to stop at hello world is at least an ignorant statement, you should use C/C++ code WITH python, or use some other language such as Cython, then you could have the best of both worlds: a fast program to write and execute, perhaps you should study python a bit more.

  • ryanlr

    Very useful comment! Thanks!

  • Pablo Gonzalez

    you must say is too difficult for me!

  • Radit


  • Sourabh Bhat

    The comments are good. I have developed Java and Python applications myself, to be more specific, I have used the languages for numerical computing. And I have understood that for real large projects Python is NOT a good choice.

    Python is very very slow, even with the optimizations done in packages like numpy. However, for small scripts Python is great. Java on the other hand is much faster than Python and execution speeds are comparable with C++ programs. And if you intend to write huge programs with many data objects with Python, then forget it. You will spend the rest of your life debugging, because it is dynamically typed language, some time or the other (while upgrading the application in future) you will tend to replace some variable already used (commonly used variables like ‘temp’, ‘i’ etc.), and the program will start behaving unexpectedly during runtime (and may perform okay during debugging). And at that point you will understand why people are still using statically typed languages.

    Python is very good language for testing small snippets of logic, not for writing the complete application. One place where I still use Python is for plotting using the library ‘matplotlib’, where I use it like a software rather than language.

    I will certainly NOT recommend Python over Java, until and unless you intend to only stop at ‘hello world’.

  • OldLIPSer

    All OOP languages are garbage.

  • Lasitha Ishan Petthawadu

    Good article very informative, Thanks!

  • daru

    As MIke said these examples would be a lot cleaner with a utility library like guava. IMO this post does not demonstrate that python is in fact more productive since similar productivity can be reached in java with utility libs.

    For me the following features make python more productive than java:
    1. duck typing
    2. decorators
    3. metaclasses
    4. with statement

  • RamtinA

    Python is really good programming language .

  • Mike Brock

    The comparisons are a little disingenuous in my opinion. You can simply pick up a library like Guava for Java (as most good Java devs do) to simplify most of these Java examples. Here’s the Java code for the File I/O apples-to-apples comparison with Guava:

    String file = CharStreams.toString(new FileReader(“file.txt”));

    … and here’s a compact way to make a list using Arrays.asList() (part of the Java JDK)

    List al = Arrays.asList({“a”, “b”, “c”});


    The string operations comparison doesn’t make any sense to me. You’re printing out the split array directly with Python and needlessly looping to print out the elements in Java. It’s the most apples-to-oranges comparison of the bunch.

    The Python output prints this out: ['compare', 'Python', 'with', 'Java']

    This very same Java code will produce identical results:

    String a=”compare Python with Java”;
    System.out.println(Arrays.toString(a.split(” “)));

    In any case, most of the extra verbosity that is being complained about here is handled automatically by any Java IDE. I haven’t manually written an import statement or “public static void main(String[] argv)” by hand in over 10 years.

  • luciuz


  • tahiriqbal

    python is speedy language and easy to learn

  • 三毛


  • goodboy


  • super_admi

    …with english…

  • super_admi


  • Iqbal Talaat Bhatti

    py code in article could be better. can crash process, range generates list not iterator xrange does that, formatters not used,etc.
    Please focus on python’s strong parts. Read PEP8, introspective capabilities, batteries included in standard library, etc.
    I’m a python advocate but I think dissing java based on these examples is unfair.

  • Bhushan Nahsuhb

    Agree with you..

  • Mind Bending

    Hi, nice article. But Python doesn’t need semicolon

  • ryanlr



    You shouldn’t concatenate str, instead use print “I am %s” %

  • Sergiy Skynin

    I like Python, but these examples conceal his features. I’m a Java developer too, so – no need to compare the syntax, we need to compare – the semantic, then capabilities Python will visible. Such as metaclasses, override of methods in runtime, generator expressions (Groovy: AST transformations, etc)

  • paolodt

    This is trivial. You should compare Python with Groovy, not with Java