Java vs. Python (1): Simple Code Examples

Some developers 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 thoroughly. 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, one point should 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.

You may also check out the most popular python libraries and code examples.

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(" "))
	System.out.print(a);
}
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;
 
//if
if(condition>10)
	System.out.println("> 10");
else
	System.out.println("<= 10");
 
//while
while(condition>1){
	System.out.println(condition);
	condition--;
}
 
//switch
switch(condition){
case 1: 
System.out.println("is 1"); 
break;
case 2: 
System.out.println("is 2"); 
break;
}
 
//for
for(int i=0; i<10; i++){
	System.out.println(i);
}
condition=10;
 
# if
if condition > 10:
    print ">10";
elif condition == 10:
    print "=10";
else:
    print "<10";        
 
#while
while condition > 1:
    print condition;
    condition = condition-1;
 
#switch
def f(x):
    return {
        1 : 1,
        2 : 2,
    }[x]
print f(condition);
 
#for    
for x in range(1,10):
    print x;

4. Class and Inheritance

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

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
in.close();
myFile = open("/home/path/test.txt")
 
print myFile.read();

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>();
		al.add("a");
		al.add("b");
		al.add("c");
		System.out.println(al);
	}
}
aList = []
aList.append("a");
aList.append("b");
aList.append("c");
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.

96 thoughts on “Java vs. Python (1): Simple Code Examples”

  1. Python is fine up to around 40,000 LOC imo if you keep things well organised. You can do a hell of a lot in 40k LOC of python! But I’d admit that beyond that… (and even with new static analysis typing tools like mypy… I’d start reaching for something like C# – I’ll probably never learn java unless I have to – too verbose).

  2. I am learning programming these days as a newbie. My only previous working knowledge and experience is in PHP (web development).As a newbie, Python feels like learning English language. Java makes me feel like I am learning a programming language. Did a little research and realised that almost all important softwares (that matters) are in Java while almost all python based stuffs are childish (that doesn’t matter).

  3. Cant agree more. I know both Java and Python and use them appropriately. My experience is as follows:

    With Java the compiler complains about mistakes in code
    With Python the customer compains about mistakes in code

    🙂

  4. Nice and clever comparison over code brevity between Java and Python. Here are my two cents.
    In Python, you can open+read a file in a single line. Here is how will you do it.

    print(open(‘myfile_path_name’).read())

  5. – If the input to a function is external to your program, you will need to check it anyway. If it’s internal, then you can warrant it using test-cases.

    – If you have clean rules for code acceptance, like having test-cases for each function, it doesn’t matter how sloppy developers are. The problem isn’t the lack of control on them, but the lack of clarity about what is expected from them.

    – Cisco uses Python as its main programming language. The reason is it fits better DevOps, where continuous improvement among different people is expected at any time.

    – Clearly written code, modular and well named, doesn’t need explanation:

    func main() {
    webExists(“http://es.archive.ubuntu.com/ubuntu/”)
    validateList(“packages”, toInstall)
    validateList(“repositories”, toInstall)
    managePackages(“install”, toInstall)
    managePackages(“purge”, toPurge)
    removeUnusedDependencies()
    }

  6. It’s fact that dynamic typing allows for much more errors to happen, and from experience I can tell that it WILL lead to these kinds of errors (it’d be naive to believe that those won’t happen). I’ve fixed so many bugs that wouldn’t even be possible in a statically typed language, IMO such bugs are complete time waste. The additional “time it takes” and the “reduced readability” (ignoring the additional information static typing gives the reader, and the awesome support every decent IDE can give you) never outweigh the time (and money, and loss of image) it takes you to fix such a bug in production.

    In dynamically typed languages you never know what you’re dealing with. For instance in Python get a parameter somewhere down your stack, you have no idea what it actually is. The only way to find out is either to set a breakpoint and inspect the variable, or to climb up the call hierarchy to figure out what is actually passed to you. Both of which take you much more time than adding type information, or read/write a little more verbose code. But even if you figure out what *one* call passes to you, it doesn’t tell anything about all the other calls.. It could be a type, a dictionary or just anything. In code you’ve never been in, this is *not* helpful.

    Comments, you say? Well, 90% of developers are sloppy; they don’t document well, they don’t read documentation, they don’t update it and they bypass intended use whenever they “need” to, just to get things done. Relying on developer’s discipline is like relying on people’s fairness; not gonna happen unless you enforce it. Also, good code is self-describing and doesn’t need comments.

    But hey, that’s just me. Or isn’t it; https://semitwist.com/articles/article/view/why-i-hate-python-or-any-dynamic-language-really
    Of course you can find such rants for every language, but some are actually reasonable and others, like this article, are just rants by haters who come up with ridiculous and/or out of touch with reality arguments just to bash what they don’t like for uneducated reasons.

    To me, Python is a neat scripting language, it’s good to get started with programming, works well for small and/or science projects, but I would never use it for mission critical software, and I’m not even talking about performance yet.

  7. Could be, just I’m a bit sceptic.

    For example I don’t think that dynamically typing leads to more errors, if you test your functions just after being written. Rather it allows careless programmers to throw untested code.

    I think the extra verbosity of explicit static typing contributes more to errors, by hiding the problems into more convoluted code: (https://elsmar.com/Identify_Waste/img011.jpg)

    Also the organisational advantages of having the code grouped as Java does, in packages and classes, only applies when the program is designed beforehand. But when you use emergent design and a WIP Kanban board those advantages don’t exist, and these techniques are also employable in large projects.

    The only real drawback I see in Python right now is its performance. Even the simplest applications written in Python don’t feel snappy at all.

  8. I hope you used Java 8, and I hope your teacher knew and told how to use Java 8 efficiently.
    And once you jump into a real-life projects with several hundert thousand lines of code you’ll realize that there are far more important things than “way less code” and “far more readable” (which btw. Python really isn’t).

    There are many many more reasons to use Java over Python, but you don’t learn those with developing a simple one-man lab application at an university.

  9. I have learned both of them at University during the same year, and made the same application in both of them to clarify my mind.

    Developing in Python took way less, and the code was by far more readable. The only reason for using Java is if you need that extra performance.

  10. I learned both Python and Java in the same year on college. At first I thought it really didn’t matter that much which language I chose.

    Then I tried to write a small but lengthy enough program in both languages, and changed my mind. Development in Python took me sensibly less to write, and the code was highly more readable.

  11. Practically beyond better Java8 based examples, until atleast the popular frameworks this won’t be complete. Certain above examples are true but we need to solve much bigger problems as like talking to all kinds of databases, messaging, security, web services etc.

    Although this is an old article, still this doubt comes to mind and while was deeply revising java benefits, have written a short book as well – https://leanpub.com/superbjava

  12. Comparison of scripting language with java wont be fair. For me comparison between Jython and Python would be more sensible. I basically use python to write scripts and it is very good for that. But I would prefer Java to start some big projects, where implicit variable declaration in python creates a lot of confusion.

  13. You are right. Python is a good language, but its implementation makes it slow, mostly because of its dynamic typed nature! 🙁

    I work in the area of scientific computing and use a lot of Python for prototyping. As you may know, pypi is a reimplementation of Python, which may become mainstream in few years. Also, numba might pick up, which uses JIT compilation. As of now, for scientific computing, I am continuing to use Java for my final code because it is easier compared to C++ and it provides me with the required speed.

    Also, I am slowly moving my Python codes to Julia, as it is a dynamically typed language and still (its implementation) runs as fast as C.

  14. Take a look at Groovy. It combines Java and dynamic typing plus other useful stuff. It’s fully Java compatible and also runs in the JVM.

  15. Speed comparison is not relevant. In Python the modules is written in C when speed is on the table.
    I write a project with heavy mathematics involved and GMPY2 excels.

    I have to say I am not familiar with Java.

  16. I do not get this article. The lines needed comparison is silly. You can use a library that wraps the low level api in java and come up with a single line functions. So that is irrelevant, only difference I see is python compiler is not smart enough to have multi line code, How does a more primitive become better?

  17. No it won’t. Pyinstaller isnt a compiler, its a packager. If you want compiled speed you can use the cython compiler (Theres a few wrinkles),, Psyco or PyPy for its JIT features. And finally, and relevant to Jython, Jython can compile out to jvm bytecode , and its quite sensible java jvm bytecode too. THEN you can wrap it with PyInstaller.

    ctypes in my opinion is the most useful one if you dont need JVM, as you can get in there and start wiring in static types and low cost abstractions of external C libs, which can buy you *very* good performance.

  18. A better way of doing this with python is this:

    with open(“/home/xiaoran/Desktop/test.txt”) as infile:
    …. print infile.read()

    And that will close it automatically when it leaves the block.

  19. I’m not sure what the point your making is. We know that, and that factors into decisions on what languages to use. If we want something thats type safe , due to mission criticality, we might chose Java. If we want something thats duck typed , to accelerate development we might chose Python.

    Also, for all purposes, Jython and Python are more or less the same, with a different library ecosystem (Jython will work for any library that supports the 2.x line of pythons and doesnt need C extensions , although theres a project in the works to address that last point), though from my experience theres some great Java libraries out there that work just fine with Python, even if they are not so “pythonic” (and to some extent you’ll need to get used to the wind in your hair when it comes to trusting Jythons type introspection).

  20. Basically Folks, my take so far has been that build projects in Java and test the projects performance in Python.

  21. I really hope so. I would love to see Python codes running faster. Especially when loops are involved and unavoidable. I hope they do something about it. PyPy and numba seem to be promising, I have been watching these projects for a while now. For some reason PyPy / numba are not coming to the main stream.

    In the mean while, Julia seems to be competing with Python as a dynamically typed, scripting language for numerical computing and runs really fast, surprisingly.

    Java / C++ have been my favourite languages, and I don’t think that will change soon.

  22. Python can simply be made an executable speed with PyInstaller, and its speed will come up to a compiled or statically typed programming language.

  23. I mean, seriously. Files.readAllLines(Paths.get("pathToYourFile")) deals with the IO issue and Arrays.toString(yourArray) deals with the array printing one…

  24. 1. This is true.

    2. System.out.println(Arrays.toString("compare Python with Java".split(" "))); Know your libraries.

    3. This is simply massively marginal.

    4. I honestly believe that the inheritance system in Java is more clear. When you have code that states, in Python, the __init__ with self and name, this simply gets confusing compared to the Java method with clear construction methods.

    5. List fileContents = Files.readAllLines(new File("/home/xiaoran/Desktop/test.txt"); Know your libraries.

    6. This is getting to the point that you’re including the class construction and main declaration for the sake of saying Python is more concise. If you want to say ‘Collections’ (which, if you know your libraries, in this case, you ought use List), you should not then actually include the code for ‘initialisation and collections’. This is about the Collections system in Java, not the method and class declaratives.

  25. I disagree. Java is indeed more verbose, but that doesn’t necessarily makes it less productive, depending on whom you’re asking. I actually find the opposite of what you said to be true. I can look at java code and immediately see what it’s doing because it’s more explicit, it’s more clear and more logical, as opposed to when I look at larger part of python code and have to look around and see what’s happening. Also in my opinion python code is harder to read because of its white space based blocks.

  26. Hope your comment was sufficient to make others understand that on the large scale when managing the application,enhancing ,debugging,maintaining,extending and many more things are concerned , Python not even fly near to Java,

  27. I shouldn’t say this, may be I will be thrashed by many enthusiasts here but

    “Python is a large heavy-bodied nonvenomous constrictor snake whereas Java is a coffee.”

    Seriously, even though I have been using Java for a long time and just started putting my hands on python, I found Python really easy to pick up and I can ramp up a __prototype quickly. What are the real life scenarios where you had seen people preferring Python over Java. Do you have situations/scenarios/applications where one is preferable over the other? For example : Say, I have to create a RESTful service, should I make a conscious decision which language should be picked. Why and why not?

  28. I just finished a class in Python and Java, I googled this to find out what professionals think about this. Personally I like Java way more.

    It is clear, when I look at someones code in java I know what it means where as when I look at someones else python code I have to think about it a little more to make connections

    OO, this is where i love java the most, you define private variables in the scope of the class then you initialize them in the constructor,

    It could be because I learned Java first but I also love the FOR loops in java more than python.

    I feel that for big programs Java is better since it organizes everything well, where as Python is good for short programs for faster writing

    I use Intelij so I don’t really care about syntax, (although it was a real pain on the final…)

  29. not to mention that you must write 3 separate codes for python (windows, mac, linux) which is much longer than java

  30. 1. That’s exactly my point, isn’t it? Did you even read my text?
    2. No, you don’t. Did you even read my example?

  31. Agreed. And stating the last example, in python, he is giving the absolute path statically, whereas in java, he is obtaining it with the language’s functions. In python, unless you are using with open, you have to close the file handler object explicitly, just like how he did in java. This article is biased towards python.

  32. Yet another ridiculous and biased comparison that uses short code for the preferred language and exaggerated circumstantial code for the disliked language. One can do so for every language.

  33. Couple of questions:

    1, Less typing means more productivity?

    Take a few minutes to think about what’s the percentage people spend on typing in the whole project development? I think less than 1%. it really doesn’t matter to spending ten minutes or twenty minutes to type 100 lines code or 200 lines code as long as the codes are much easier to debug or maintain.

    2, the developers who are familiar with Java have the reason to doubt the author’s intention if the author is familiar with Java. otherwise there is no more much meaning to write a article to compare a programming language you know few with another language you know much better. Although it’s hard to approve which language is better by above samples. the samples in java can be be simplify a lot. Author really don’t need to add so many “public static void main(String[] args) {” in the Java sample. for example, the last sample can be in Java with a general programming library: AbacusUtil at: http://landawn.com


    List list = N.asList("a", "b", "c");

  34. Agree. To further add, Many of the Java examples could have been written better. Also any professional Java developer would use a set of libraries to perform many of the trivial IO, String, and other operations. Another note, the line-by-line pure java file reading is mainly when you don’t want to load a whole (potentially giant) file into memory. Else, just use IOUtils.read*.

    Furthermore, little syntax is not an end-all-be-all decider. You must also consider the strong typing of the system, future readability, I won’t even tackle performance.

    I have jumped into a number of Python projects to find that it’s not clear what certain types are by just reading the code. In large code, that concerns me. When i’m bug hunting or trying to orchestrate a large complex project, that concerns me even more.

    It also doesn’t help that Python scripts are often abused and end up being giant scripts, but I guess many languages do that 🙂

    Side note: I frequently play dabble in Python, more so in the past and like it as a language, but just think these comparisons are misleading to new people entering the field and deciding on a language.

  35. On the static and dynamic declation difference between Java and Python – Microsoft Visual Basic provides option to be both – you can be dynamic and if you want to be static just add Option Explicit in the beginning… VB/ASP seem to be far richer than all of this – but they seem to have lost the war with others….

  36. I am developer of c/c++ and java also ,java is manufacture by c and c++ and c/c++ is Powerful Language for ever ,but i don’t know about anything about python but java have alots of libraries and api and freedom of use with any database u want but i can’t say anything about python

  37. For #5, JDK 7 offers a dramatically simplified file API. Python does have a cleaner more concise syntax than Java, but these examples are exaggerated. And they miss the benefits of Java syntax. There are some benefits to Java’s more strict syntax with static types. Also some Python syntax can be wonky. And I’d argue that the Python build/test/deployment tools aren’t up to the JVM ecosystem level. Also, more important than pure language syntax is ecosystem: Python is dominant in scientific computing and lots of academia, JVM is dominant in lots of production server-centric computing. The Spark ecosystem for example, supports Python, but it’s fundamentally JVM based and using Spark in the JVM ecosystem is nicer.

  38. never seen a more language-fixed fan community than in and around Java. Most Java fans seem to have a “it’s us (superior) v.s. them (poor, lost souls)” mentality, why I don’t really understand. Python developers are quite simply a lot more relaxed about their language…

  39. The difference between your examples in Java using Guava conceal the fact that these two-liners are not fully valid (compilable) Java programs. The Python versions are.

    It’s not so much missing elements in Java’s core language libraries, such as easy file handling, that makes Java more verbose. Rather it’s the fact that _everything_ is convoluted by reams of non-essential syntax. In other words, you can look at a Python program and immediately see what it is doing, because there is not much more but the pure logic, you can’t do the same with Java.

    With Java, most every time you look at some code, one first has to switch on the brain’s lexer and parser to separate the actual logic from all the heavy syntactical bloat. _That_ kills productivity, as well as having to type too many lines writing code. (Please spare me the my-IDE-does-the-heavy-lifting-pitch, as there are great Python IDEs, too, some even based on Eclipse, and they improve productivity for Python ever so much, so the argument is moot).

  40. Grovvy is not an extension of Java but a compiled programming lang that run on top of the JVM, like Scala, Clojure, and many others, including .. well, Jyhton http://www.jython.org

    However my point is that Java is a static type language, while Python is dynamic type language. Thus is like comparing apples and oranges ..

    Cheers, p

  41. The only thing which Python fall behind is “GUI”. With Netbeans it’s too easy. But developing GUI isn’t effective as Netbeans. Actually it’s not problem of Python. There is no RAD tool for Python. I mean drag-and-drop GUI development. QT, Wx or Glade isn’t satisfy…

  42. hahaha you are right buddy especially in the IDE part. Python has created all a new generation of fanboys. Certainly it has its advantages over Java and others but people has taken it like a super thing.

  43. 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.

  44. http://en.wikipedia.org/wiki/List_of_Python_software, 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.

  45. 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’.

  46. 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

  47. 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”});

    System.out.println(al);

    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.

  48. 虽然不知道在说些什么,但看起来很厉害的样子。

  49. py code in article could be better. f.read() 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.

  50. 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)

Leave a Comment