This document provides a quick introduction to the principles of programming in Java by mentioning the main differences with Python.
| Python | Java | Comments |
|---|---|---|
defarea(width, height):
returnwidth*height | intarea(intwidth, intheight) {
returnwidth * height;
} | Statement blocks are delimited using braces; indentation is ignored. Simple statements are terminated with a semicolon. Parameter names are preceded by the parameter type. The function name is preceded by the function's return type (= the type of result values). |
deffac(x):
ifx==1:
return1else:
returnx*fac(x-1) | intfac(intx) {
if (x == 1)
return1;
elsereturnx * fac(x - 1);
} | |
defdivides(a, b):
x=awhilex>b:
x-=breturnx==0 | booleandivides(inta, intb) {
intx = a;
while (x > b)
x -= b;
returnx == 0;
} | Local variable declarations specify the variable type. While loop conditions are enclosed in parentheses. |
x=3y=2assertx/y==1.5assertx//y==1 | intx = 3;
inty = 2;
assertx / y == 1;doublex = 3;
doubley = 2;
assertx / y == 1.5; | In Java, the rounding behavior of |
sum=0forxinrange(3, 6):
sum+=xassertsum==3+4+5 | intsum = 0;
for (intx = 3; x < 6; x++)
sum += x;
assertsum == 3 + 4 + 5; |
|
[1, 3, 5] | newint[] {1, 3, 5} | |
xs= [1, 3, 5]
sum=0forxinxs:
sum+=xassertsum==1+3+5 | int[] xs = newint[] {1, 3, 5};
intsum = 0;
for (inti = 0; i < xs.length; i++)
sum += xs[i];
assertsum == 1 + 3 + 5; | Note: |
defsame(xs, ys):
returnxsisys | booleansame(int[] xs, int[] ys) {
returnxs == ys;
} | In Java, if |
defequals(xs, ys):
returnxs==ys | booleanequals(int[] xs, int[] ys) {
intm = xs.length;
intn = ys.length;
if (m != n)
returnfalse;
for (inti = 0; i < m; i++)
if (xs[i] != ys[i])
returnfalse;
returntrue;
} | In Java, to compare the contents of two arrays you need to use a loop to compare the elements one-by-one. (In JLearner, you need to write such a loop yourself; in Java, you can use the library method |
defslice(xs, a, b):
returnxs[a:b] | int[] slice(int[] xs, inta, intb) {
int[] s = newint[b - a];
for (inti = a; i < b; i++)
s[i - a] = xs[i];
returns;
} |
|
classPoint2D:
passp=Point2D()
p.x=10p.y=20 | classPoint2D {
intx;
inty;
}
Point2Dp = newPoint2D();
p.x = 10;
p.y = 20; | Attributes (called fields in Java) have to be declared. |