Java vs. Python (1): Simple Code Examples

Source: Internet
Author: User

Some developers has claimed that Python are more productive than Java. It's dangerous to make such a claim, because it could take several days to prove that thoroughly. From a high level view, Java was statically typed, which means all variable names has to be explicitly declared. In contrast, Python is dynamically typed, which means declaration are not required. There is a huge debate between dynamic typing and static typing in programming languages. This post does isn't talk on that. However, one point should being 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'll try to cover some basic language components, such as string, control flow, class, inheritance, File I/O, etc. All of them would be compared by using side-by-side examples. I hope this can provide Java programmers a general idea of what Python and Java do the same thing differently. By a glance of the code below, we can easily realize this Python code is much shorter, even though some Java "class shell" (In Java everything starts with a class definition) are not listed. This might is one reason why Python can is more productive.

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 are 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 does 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 ("")) Syste M.out.print (a);}
A= "Compare Python with Java";p rint a.split ();

There is a lot of string related functions in Python which was as good as or better than Java, for example, Lstrip (), RSTR IP (), etc.

3. Control Flow

int condition=10; IfIf (condition>10) System.out.println (">") elseSystem.out.println ("<= 10"); Whilewhile (condition>1) {System.out.println (condition); condition--;}//switchswitch (condition) {Case 1: System.out.println ("is 1"); Break;case 2:system.out.println ("is 2"); break;} forfor (int i=0; i<10; i++) {System.out.println (i);}
condition=10; # IfIf Condition >:    print ">10"; elif condition = =:    print "=10"; else:    print "<10";        #whilew Hile condition > 1:    print condition;    condition = condition-1; #switchdef f (x):    return {        1:1,        2:2,    }[x]print F (condition), #for for    x in range (1,10):    PR int 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");d og.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 are no requirement such as defining an explicit constructor for implicit super Construc Tor.

5. File I/O

file dir = new File (". "); /get current directoryfile fin = new File (Dir.getcanonicalpath () + file.separator+ "Code.txt"); FileInputStream fis = new FileInputStream (fin);////construct the BufferedReader objectbufferedreader in = new BufferedRea Der (New InputStreamReader (FIS)); String aLine = Null;while ((aLine = In.readline ()) = null) {////process each line, here we count empty linesif (aline.tr
      Im (). Length () = = 0) {}} //do not forget to close the buffer readerin.close (); 
myfile = Open ("/home/xiaoran/desktop/test.txt")  print myfile.read ();

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

6. Collections

Import java.util.ArrayList; public class Main {public static void main (string[] args) {arraylist<string> al = new arraylist<string> (); AL.A DD ("a"); Al.add ("B"); Al.add ("C"); System.out.println (AL);}}
Alist = []alist.append ("a"), Alist.append ("B"), Alist.append ("C");p rint alist;

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

Transferred from: http://www.programcreek.com/2012/04/java-vs-python-why-python-can-be-more-productive/

Java vs. Python (1): Simple Code Examples

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.