Skip to content

Latest commit

History

History
263 lines (201 loc) · 3.93 KB

File metadata and controls

263 lines (201 loc) · 3.93 KB

Principles of programming in Java for Python programmers

This document provides a quick introduction to the principles of programming in Java by mentioning the main differences with Python.

PythonJavaComments
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 x / y (rounding to an integer or not) depends on the type of x and y.

sum=0forxinrange(3, 6):
sum+=xassertsum==3+4+5
intsum = 0;
for (intx = 3; x < 6; x++)
sum += x;
assertsum == 3 + 4 + 5;

for loops specify an initialization (e.g. int x = 3, a loop condition (e.g. x < 6), and an update (e.g. x++).

[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: int[] xs = new int[] {1, 3, 5}; can be abbreviated as int[] xs = {1, 3, 5};.

defsame(xs, ys):
returnxsisys
booleansame(int[] xs, int[] ys) {
returnxs == ys;
}

In Java, if xs and ys are arrays, xs == ys compares the arrays' identity, not their contents. That is, it returns true only if xs and ys refer to the same array object, i.e. the same memory location. It corresponds to Python's is operator.

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 Arrays.equals.)

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;
}

new int[b - a] creates a new zero-initialized array of length b - a.

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.