例)Python
import urllib
urlenc_param = urllib.quote_plus(param.encode('utf8'))
例)Java
※メソッド宣言は省略しています。
import java.net.URLEncoder;
String urlenc_param = URLEncoder.encode(param, "UTF-8");
JavaプログラマのためのPython入門。その違いについてソースコードをメインに比較していきます。 Pythonの対象バージョンはGoogleAppEngineと同様2.5としています。
buffer = []
for i in range(100):
buffer.append(str(i))
print ''.join(buffer)
StringBuffer buffer = new StringBuffer(100);
for(int i = 0; i < 100; i++) {
buffer.append(String.valurof(i));
}
System.out.println(buffer.toString());
value = None
if map.has_key("hoge"):
value = map["hoge"]
String value = (String)map.get("hoge");
例)Java
for i in range(100): # 変数iを0から99までインクリメントして繰り返す。
print i
for (int i = 0; 100 > i; i++) {
System.out.pritln(i);
}
出力)
from datetime import date
date.today().year
date.today().month
date.today().day
date.isoformat(date.today())
> 2009
> 10
> 1
> '2009-10-01'
System.out.println(Calendar.getInstance().get(Calendar.YEAR));
System.out.println(Calendar.getInstance().get(Calendar.MONTH));
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd");
System.out.println(sdf.format(Calendar.getInstance().getTime()));
例)Java
class Employee(Person):
def __init__(self):
super.__init__(self) # 親クラスの初期化メソッドを呼び出し。
public class Employee extends Person {
public Employee() {
super(); // 親クラスのコンストラクタ呼び出し。
}
}
例)Java
# 単継承
class SingleExtendsClass(Base1):
<文-1>
.
.
.
<文-N>
# 多重継承
class MultiExtendsClass(Base1, Base2, Base3):
<文-1>
.
.
.
<文-N>
/**
* 単継承しかできない。
*/
public class SingleExtendsClass extends Base1 {
<文-1>
.
.
.
<文-N>
}
出力)
FORM = "%02.3f" # 符号なし、ゼロ埋めあり、整数2桁、小数3桁
x = float(1)
y = float(3)
print FORM % (x / y) # 値のバインド
> 00.333例)Java
final MessageFormat FORM = new MessageFormat("{0, number, ##.##}");
float x = (float)1;
float y = (float)3;
Object[] args = {new Float(x / y)};
System.out.println(FORM.format(args));
# -*- coding: utf-8 -*-
'''
Created on 2009/05/19
@author: hogehoge
'''
from google.appengine.ext import db
from datetime import date
> javac -encoding utf-8 hogehoge.java
import re # モジュールをインポート
from datetime import date # datetimeモジュールからdateクラスをインポート
from calendar import * # Java同様ワイルドカードも使える
from math import sin, cos, tan # 複数関数を指定
print re.split('\W+', 'Words, words, words.')
print date.today()
print firstweek() # calendarモジュールの関数
import java.util.regex.*;
import java.util.Date;
import java.util.Calendar;
colors = {"red":"#FF0000", "green":"#F00FF00", "blue":"#0000FF"}
print colors["red"] # keyを指定して値を取得
print colors.keys() # キー一覧を取得
HashMap colors = new HashMap();
colors.put("red", "#FF0000");
colors.put("green", "#00FF00");
colors.put("blue", "#0000FF");
System.out.println(colors.get("red"));
System.out.println(colors.keys());
上記をファイル名"hello.py"として保存し実行すると、4行目が実行されます。
def hello():
print "hello!"
hello()
> python hello.py
hello!
numbers = [10, 20, 30]
for num in numbers:
print num
拡張for文
int[] numbers = {10, 20, 30};
for(int i = 0; numbers.length > i; i++) {
System.out.println(numbers[i]);
}
int[] numbers = {10, 20, 30};
for(int num : numbers) {
System.out.println(num);
}
if 28 <= age and age <= 33:
print "around 30!"
elif 38 <= age and age <= 43:
print "around 40!"
if(28 <= age && age <= 33) {
Sysem.out.println("around 30!");
}
else if(38 <= age && age <= 43) {
System.out.println("around 40!");
}
person = None
person = 100
person = Person()
Person person = null;
person = new Person();
person = 100; // <- 当然コンパイルエラー
class Person:
__name = None
def get_name(self):
return self.__name
public class Person {
private String name = null;
public String getName {
return this.name;
}
}
# 1行コメント
str = "hogehoge" # これも1行コメント
'''
# ブロックコメントに代用
x = 1
y = 2
print x + y
'''
// 1行コメント
String str = "hogehoge"; // これも1行コメント
/*
// ブロックコメント
int x = 1;
int y = 2;
System.out.println(x + y);
*/
class Person:
__name = None
__age = None
def __init__(self, name, age):
self.__name = name
self.__age = age
public class Person {
private String name = null;
private short age = -1;
public Person(String name, short age) {
this.name = name;
this.age = age;
}
}
class Person:
__name = None
__age = None
public class Person {
private String name = null;
private short age = -1;
}
class Person:
__name = "hoge"
p = Person()
print p.__name # <- AttributeError: Person instance has no attribute '__name'
hoge = -99
hoge = "abc"
hoge = [1, 2, 3]