Python and Java - Comparisons and Contrasts

# Simple Python program

year = 2007
print "Hello World!" 
print "CSSE 120 changed a lot in %d." % (year)
		
// Simple Java program

public class HelloWorld {

	public static void main(String[] args) {
		int year = 2007;
		System.out.println("Hello World!");
		System.out.print("CSSE 120 changed a lot in ");
		System.out.print(year);
		System.out.print('.');
	}
}
		
Concept/feature Python Java Comments
case-sensitivity Python is case-sensitive. Y is not the same as y. Java is case-sensitive. Y is not the same as y.

Python and Java are the same here.

In Python, standard library functions usually have lowercase names.

In Java, standard library functions usually have "camelCase" names (each word but the first begins with a capital letter).

Eclipse - creating source files New ... PyDev module. Do not put the .py on the module name New ... Class. You specify some details and Eclipse makes a template for you
(do not put .java in the name).
Eclipse - running programs right-click the file you want to run.  Run as ... right-click the file you want to run.  Run as ...

Python: Can run any file in the project.

Java: Must have a class in the project that defines a main() method.

files and classes A Python source file can contain definitions of any number of classes (including zero) If a Java source file contains the definition of a public class or interface named XXX, the filename must be XXX.java  .  A source file can contain at most one definition of a public class.  It can include multiple non-public class definitions. In both languages, it is common to have one class definition per file.
Where does execution start?

Executes the code in order from beginning to end of the file.

main() is optional, and has no special meaning in Python.

Executes the body of the main() method from the selected source file and anything that main() calls. (Similar to C).

That means that Java starts in the class in the project containing main(), but main() can call methods from other classes.

main() needs to be declared as public static void main in Java to work.

Arguments and return type of main() Whatever you want (since main is not a special function in Python)

   public static void main(String[] args) {
	 // body of main()
   }
In Java, the arguments passed to main() are the command-line arguments that are provided when the program is run (usually from the command line).
running a program from the command line python filename.py javac Classname.java
java Classname
(assumes that the folders containing python.exe and java,exe are in your execution path)
Comments From # to the end of the line "C-style" comments begin with /* and end with */, may span multiple lines.
Alternatively, comments can begin with // and run to the end of the line.

Java interprets /** as beginning a documentation string; Python interprets the first string of a function/class/method (usually set aside with triple quotes) as its documentation.

C-style comments may not be nested.

The following is illegal:

/* cannot have /* comment inside */ comment */

Semicolons at the end of simple statements Allowed, but only needed between two statements on the same line. Required, as in:

x = f(a, b);

Java's use of semicolons is very similar to C's.
Indentation and line breaks is essential to the syntax of the language is ignored by the compiler It's still a good idea to have good, consistent indentation.
Using code from other files import module   or
from module import *
If the class you want to use is in another package,
import packagename.classname;
or
import packagename.*;
We can automatically use other classes that are in the same package (and thus reside in files in the same folder); no import needed for those
Variable types Variables are untyped; a given variable (label) can be stuck on values of different types at different times during the execution of a program. The type of a variable must be declared when it is created, and only values of that type can be assigned to it. In Java, we may not write x = 5.6; unless x has been previously declared:
double x;

...
x = 5.6; // legal
x = "String value"; 
/* This is illegal in Java; types don't match*/	
Variable declaration with assignment. Python has no declarations
int i;
int n = 5;
double x=7.3, y=8.2, z;
				
Variables must be declared and should be initialized before they are used
Simultaneous assignment x, y = 3, x-y Not allowed in Java
chained assignments x = y = 0 x = y = 0; Identical in Python and Java (except for the semicolon)
Assignment with operators x += 2 x += 2; Identical in Python and Java
Increment and decrement operators x++; ++x;, x--, --x  (as in C) Not available in Python (use x+=1).
Exponentiation operator x**6 No exponentiation operator in Java: instead, use Math.pow(x,6). For small integer powers, it's better to use x*x or x*x*x
comparison operators <   <=   >  >=   ==   != < <= > >= == != identical in Java, C, and Python.
Boolean operators and   or   not &&   ||   ! The meanings are the same, but the notation is different.
getting help Documentation is on your computer (C:\Python25\Docs\Python25.chm) and online. Documentation is online at Sun's website.  
You can also download the documentation so you can access it on your own computer, and get context-sensitive help in Eclipse.  Instructions are at 
http://www.rose-hulman.edu/class/csse/resources/JavaDevKit/installation.htm (see the part on documentation near  the bottom of the page) and
http://www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-java-configuration.htm (see the part on Java documentation near  the bottom of the page).
As you use more language features, you will find websites such as these very handy for quickly looking up things such as the names of functions and classes.
Exceptions
try:
	<code that could throw an exception>
except:
	<code to handle the exception>
				
try {
	<code that could throw an exception>
}
catch (ExceptionType e) {
	<code to handle the exception>
}
				
Another difference is that Python throws exceptions with the raise statement; Java with the throw statement.
for loop standard form
sum = 0

for i in range(5):
	sum += i
print i, sum
	 			
int i, sum=0;
for (i=0; i<5; i++) {
	sum += i;
}

System.out.print(i);
System.out.print(' ');
System.out.println(sum);
				
These two programs do the same thing.
More details of for loop syntax
for <variable> in <list>:
	 <one or more indented statements>
	 			
for (<initialization> ; <test>; <update>) {
	 <zero or more body statements>
}  
for (int i : numList) {
	 <zero or more body statements>
}
				

initialization: usually gives initial value to loop variable(s)

test: If the value of the test is true, the loop continues.

update: After each execution of the loop body, this code is executed, and the test is run again.

The second form of the for loop works for the elements of an array,

A block of statements to be executed sequentially indicated by indentation level surrounded by { ... }

In Java, a block can be used anywhere a single statement can be used.

If a Java block only contains one statement, the braces are optional.

Refined Java for-loop definition
for (<initialization> ; <test>; <update>) 
	 <statement>
	 			
Parentheses are required. <statement> may be a single statement or a block of statements surrounded by { ... }
do-nothing statement pass ; In Java, a single semicolon with nothing in front of it indicates an empty statement. Just like Python's pass, it is used where the syntax requires a statement, but there is nothing to do there.
while loop syntax
while <condition>:
	<one or more indented statements> 
				
while ( <condition> )
	<statement>
				
Parentheses are required. <statement> may be a single statement or a block of statements surrounded by { ... }
break statement break break; immediately end the execution of the current loop
continue statement continue continue; immediately end the execution of this time through the current loop, then continue the loop's next execution.
basic if syntax
if <condition>:
	<one or more indented statements> 
				
if ( <condition> )
	<statement>
				
Java Syntax is just like C.
Parentheses are required. <statement> may be a single statement or a block of statements surrounded by { ... }
if with else
if <condition>:
	<one or more indented statements>
else:
	<one or more indented statements> 
				
if ( <condition> ) <statement> else <statement> As in above cases, <statement> may be a single statement or a block of statements surrounded by { ... }.

Java Syntax is just like C.
 

if with multiple cases
if <condition>:
	<one or more indented statements>
elif <condition>:
	<one or more indented statements>
else:
	<one or more indented statements> 
				
if ( <condition> )
	<statement>
else if ( <condition> )
	<statement>
else
	<statement>
				
Java has no special syntax that is similar to Python's elif .

Java Syntax is just like C.
 

do { ...} while loop No Python equivalent do {
    statement;
    . . .
    statement;
   } while (condition);
In a while loop, the test is at the beginning.  So it is possible that the loop body never executes at al.  In a do loop, the test is at the end, so the loop body always executes at least once.
switch statement. Test a simple variable (for example, an integer), and choose which block of code to execute based on its value. If none of the specific cases match, execute the default code. If no default code and no cases match, do nothing.
switch (<variable>) {
	case <value1> :
		<statement1>
		break;
	case <value2> :
		<statement2>
		break;
	...
	default:
		<statement>
}
				

Java Syntax is just like C.
 

Python has nothing that is like Java's switch statement ( if-elif-else is used)

If there are multiple statements for a given case, no curly braces are needed.

Don't forget the break; at the end of each case (except the last).

decision as part of an expression. Similar to Excel's if(test, true-value, false-value) a if b else c  b ? a : c Conditional expression. Can be used anywhere an expression can be used. For example:
public static int max (int a, int b) {
   return (a > b) ? a : b;
}
Java Syntax is just like C.
long integer types Basic int type is 32-bit (this is processor-dependent); if an operation produces a value too big for int, a long value (which can be an arbitrarily large integer) is automatically produced.

int type is typically 32-bit.

long type is sometimes 64-bit, but always at least 32-bit.

There is no automatic conversion of values.

If bigger integers are needed in Java, use the BigInteger class.
constant array or list initialization numList = [1, 3, 5, 7, 9] int[] numList = [1, 3, 5, 7]; The Python list can change size later.  The Java array will always have four elements; the individual elements may change, however.

Note that Java has an ArrayList class with much of the functionality of Python's lists, but no special list syntax like Python has.

list/array element assignment. numList[2] = 8 numList[2] = 8;
list slicing numList[2:3] Java does not have this feature  
Graphics CSSE 120 uses a graphics library built on top of the builtin Python graphics library, Tkinter. Java uses the Swing graphics library. These libraries are very different: you will want to look at the online documentation.
Object-oriented programming Supported: you can use classes and methods to design object-oriented programs. Required: code resides in classes, main is a method, and all functions are implemented as methods. Java forces some level of use of object-oriented programming, whereas Python allows for other methods of program design.
Lists Lists are almost a primitive type: there is native syntax for creating lists, there are keywords to modify lists, and the builtin len function can tell you their lengths. Lists are in the standard library in the ArrayList class which can only store one type of object (although you can use inheritance to store multiple types). The builtin language features only arrays, which function similarly to C arrays. Do not confuse the Python term "list" with linked lists, a related data structure you will learn about.
Strings Python strings are basically lists of characters: you can perform all list operations on them. Strings are their own types, with quite different methods from lists.
Simple Printing print 5

print 5,

print "x =" , 5

System.out.println(5);

System.out.print(5);

System.out.println("x = " + 5);

In Python, print is a keyword, which can take a list and prints the elements of the list one at a time.

In Java, the print and println methods take a single argument. To print multiple things with one call, you need to convert them all to strings and concatenate the strings.

Converting an object to a string __str__ method toString method Both languages can convert objects to strings, but the name of the method to override is different.
calling __str__ or toString()  str(x) x.toString() In many cases in Java, an explicit call to toString is not required, because Java puts it  in for you when needed.  Examples:  in print or println, and in string concatenation.
If x is an object, System.out.print(x); is equivalent to System.out.print(x.toString());
Objects and inheritance No base class for all objects All classes inherit from Object The Object class gives all Java objects certain properties, such as rudimentary toString() and hashCode().
self and this self.x = 5 this.x = 5; In Java, the use of this in many contexts (including the one shown here) is optional.  But it is encouraged.
self as an explicit formal parameter to a method
 def move(self, deltax, deltay):
     self.x += deltax
     self.y += deltay
  int move(int deltax, int deltay){
     this.x += deltax;
     this.y += deltay;
  }
Both are called in the same way, p.move(5,7) (in Java a semicolon is also needed), In Python the declaration of self as the first parameter is what distinguishes it as a method instead of an ordinary function.  In Java, methods are the only kind of functions there are.
simple function definition
from math import *

def printRootTable(n):
	for i in range(1,n):
		print " %2d %7.3f" % (i, sqrt(i))

def main():
	printRootTable(10)

main()
public class RootTable {
	public static void printRootTable(int n) {
		int i;
		for (i=1; i<=n; i++) {
			System.out.printf(" %2d %7.3f\n", i, Math.sqrt(i));
		}
	}
	
	public static void main(String args[]) {
	      RootTable.printRootTable(10);
	}
}
If a Java function does not return a value, you must declare its return type as void. A python function always returns a value (if no return statement is present, None is returned).
reading numbers as input
m,n = input("Enter two numbers: ")
print m, n
import java.util.Scanner;

public class InputTwo {
	public static void main(String args[]) {
		int i, j;
		System.out.print("Enter two numbers: ");

		Scanner s = new Scanner(System.in)

		i = s.nextInt();
		j = s.nextInt();

		System.out.print(i);
		System.out.print(' ');
		System.out.println(j);
	}
}
In the Python example, the numbers in the input must be separated by commas.
variable visibility All variables can be accessed from anywhere in the code, unless the variable's name begins with __ (two underscores) and does not end with two underscores. You can specify each variable's visibility with an access specifier: one of public, private, or protected. If you leave off the specifier, the visibility is "package friendly). Public data can be accessed anywhere (like data in Python), whereas private data can only be accessed from within the class, and protected data only from within the class or classes inherited from it.