In general, anything that can be accomplished in one programming language can also be accomplished in another, though not necessarily as easily. Most simple programming concepts appear in all languages, although the specifics of how to invoke them may differ. Java requires more attention to punctuation; the syntax required is less like English than Python. The table below gives some examples of equivalent structures in the two languages. The use of semicolons between statements is required in Java. Curly braces are required if more than one statement is to be executed. On the other hand, indentation style is flexible.
Topic | Python | Java |
---|---|---|
types and declarations | dynamically typed: you don’t have to explicitly declare the type | everything must have a declared type: either a primitive (int, long, double, float, char, byte, boolean) or an Object (e.g., String) |
comments |
# a single line comment |
// a single line comment /* this is a multi- line comment */ /** this is a Javadoc comment */ |
control structure: if |
if <test1>: <statementsA> elif <test2>: <statementsB> else: <statementsC> |
if (<test1>) { <statementsA> } else if (<test2>) { <statementsB> } else { <statementsC> } |
control structure: while |
while <test>: <statementsA> else: <statementsB> |
while (<test>) { <statementsA> } // no else clause is available |
control structure: do/while |
while <test>: <statementsA> else: <statementsB> |
do { <statementsA> } while (<test>); // no else clause is available |
control structure: for |
for i in range(1,10): <statements involving i> |
for (int i = 1; i <= 10; i++) { <statements involving i> } |
exceptions |
try: <statementsA> except <name>: <statementsB> else: <statementsC> |
try { <statementsA> } catch (<name> e) { <statementsB involving e> } // no else clause is available |
functions |
def times(x, y): return x*y |
public static int times(int x, int y) { return x*y; } |
function calling |
z = times(3, 5) |
int z = times(3, 5); |
sample program: hello world |
print "Hello, world!" |
public class HelloWorld { public static void main(String[] args) { System.out.println( "Hello World!" ); } } |
sample program: summing integers 1-10 |
sum = 0 for x in range(1, 10): sum = sum + x |
int sum = 0; for (int x = 1; x <= 10; x++) { sum = sum + x; } |