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/xiaoran/Desktop/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.

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

时间: 2024-08-25 20:51:02

Java vs. Python (1): Simple Code Examples的相关文章

AWS s3 python sdk code examples

Yet another easy-to-understand, easy-to-use aws s3 python sdk code examples. github地址:https://github.com/garyelephant/aws-s3-python-sdk-examples. """ Yet another s3 python sdk example. based on boto 2.27.0 """ import time imp

[转]Java Code Examples for android.util.JsonReader

[转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing how to use android.util.JsonReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will b

Java Code Examples for javax.servlet.http.Part

http://www.programcreek.com/java-api-examples/index.php?api=javax.servlet.http.Part The following are 20 Jave code examples that show how to use the javax.servlet.http.Part class. These examples are extracted from open source projects. You can click 

Java vs Python

面试时常问到这两种语言的区别,在此总结一下. Referrence: Udemy:python-vs-java Generally, Python is much simpler to use, and more compact than Java. It is generally easier to learn, and more forgiving when it comes to using shortcuts like reusing an old variable. You will

Topcoder 练习小记,Java 与 Python 分别实现。

Topcoder上的一道题目,题目描述如下: Problem Statement      Byteland is a city with many skyscrapers, so it's a perfect venue for BASE jumping. Danilo is an enthusiastic BASE jumper. He plans to come to Byteland and to jump off some of its buildings. Danilo wants

BSD Socket~UDP~Code examples

C 代码,可以用于OSX运行 /* Client-server example using UDP[edit] The User Datagram Protocol (UDP) is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, U

使用国内镜像通过pip安装python的一些包 Cannot fetch index base URL http://pypi.python.org/simple/

原文地址:http://www.xuebuyuan.com/1157602.html 学习flask,安装virtualenv环境,这些带都ok,但是一安装包总是出错无法安装, 比如这样超时的问题: (env)[email protected]:~/flask_study/venv-test/test$ easy_install Flask-SQLAlchemy Searching for Flask-SQLAlchemy Reading http://pypi.python.org/simpl

java与python在处理大文件操作上的对比

1.问题描述 现在对一个2g的大文件,抽取第二列含有特点16个串的信息,并将这些含有特串的信息,写回到两个文件中 2.具体实现 (1)java代码 package naifen; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java

fasttext的基本使用 java 、python为例子

fasttext的基本使用 java .python为例子 今天早上在地铁上看到知乎上看到有人使用fasttext进行文本分类,到公司试了下情况在GitHub上找了下,最开始是c++版本的实现,不过有Java.Python版本的实现了,正好拿下来试试手, python情况: python版本参考,作者提供了详细的实现,并且提供了中文分词之后的数据,正好拿下来用用,感谢作者,代码提供的数据作者都提供了,点后链接在上面有百度盘,可下载,java接口用到的数据也一样: [html] view plai