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

String exampleString;

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

Class files for a project in Python are contained with in a source folder.

With java, classes for a project are typically stored within a package
for purposes of visibilty and accessability.

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 (nested classes).

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)

Example with Java:

-Navigate to the folder containing the file
-javac ClassName.java compiles the file and produces ClassName.class
-java ClassName.class executes that class
-java ClassName arg0 arg1 executes that class with given command-line
arguments


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.

/** Marks a special comment used to generate javadoc.

Java interprets /** as beginning a documentation string. Javadoc can contain special tags such as @author and @param to further describe
methods or fields that are commented

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.

In java spacing and alignment is more stylistic per programmer than anything else.

Sharing 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*/


Java has two types: primitive and reference. The eight primitive types are known as integral types and the values are held directly by the variables. Reference type variables in java, store the memory address where an object resides.

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 because the pow function is a resource expensive operation.

comparison operators

<   <=   >  >=   ==   !=

<  <=   >   >=   ==   != identical in Java, C, and Python.
Boolean operators and   or   not

&&   ||   !

The meanings are the same, but the notation is different.
help features 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).

Javadoc is available for interfaces and classes online (Google search).

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 as with an if-test that has one resulting statement.

Classes and methods in java must be closed in braces.

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 (main reason to use a do-while over a while loop).

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) or else the value could be switched to a different case.

Conditional Operator
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;
}
What this statement says is "if a is greater than b, return a, else return 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, which creates a referenced object to store the integer. Limited only to hardware and memory.
Lists

Lists are almost a primitive type: there is native syntax for creating lists, there are keywords to modify lists, and the built in 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 in java you will learn about.
constant array or list initializationnumList = [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] = 8numList[2] = 8;
list slicing numList[2:3]

Java does not have this feature

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());

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.

String can be broken up using the string Tokenizer - splits string based on defined character.
Note on Strings in java: Only reference type that allows operators to work on it (String concatenation)
Simple Printingprint 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. Can also use printf for print formatting similar to what you learned in C.

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.
Objects

Objects are regarded as an active data type - "know stuff and can do stuff"

An instance of a class that contains instance variables (know stuff) and use methods to operate on instance variables (can do stuff).

Objects are created using a constructor.

Objects send each other messages
       p.getX()     accessor method

Interaction of these objects is the basic idea of Object Oriented Development.

Same concepts as in Python.

An object is an atomic unit, meaning that its parts cannot be dissected and viewed by general users.

Have structure and state and define operations that may access or manipulate that state..

Initialized by a constructor.

Object-oriented programming
Supported: you can use classes and methods to design object-oriented programs.

Breaking a problem down into components (objects) and having them interact to solve a problem.

Components provide services through interfaces, while components called clients use these services.

Objects are abstractions: hide irrelevant details and can be independently developed.

Object-Oriented Design is a data-centered view of computing that relies on the processes of finding and defining a useful set of classes for a given problem

Objects are the mechanisms of abstraction while accessor and mutator methods (with formal params and return values) are the interfaces.

Encapsulation, polymorphism, and inheritance are OOD terms that refer to the same concepts in Python as they do in Java.

Required: code resides in classes, main is a method, and all functions are implemented as methods. Main creates an instance of a class (object) that contains fields and is oeprated on by methods.

A class in Java consists of fields the store data and methods that are applied to instances of a class. An object is the instance of a class.

Objects provide for encapsulation, which is the hiding of functional details of a class from outside methods. OOD is also based on polymorphism, which gives a reference variable the ability to reference objects of several different types. One last significant characteristic of object-oriented development in Java is inheritance.

This is a very basic overview of objects in Java. For a more in-depth description consult your textbook.

Object-oriented programming in either language refers to the concept of using objects to define fields pertaining to the object and operations that may access or manipulate its state.

An object is an instance of a class that contains functions and data, known as fields and methods. Object-oriented programming utilizes the object to interact with other classes and other objects in order to solve the problem at hand...

Java forces some level of use of object-oriented programming, whereas Python allows for other methods of program design.

No base class for all objects

Subclass inherits from the existing superclass. Allows for code reuse and the structuring of classes to avoid duplication of operations.

Methods and fields can be overridden to accommodate the derived class.

Assuming you have Student and Person classes, and a student IS-A Person, you'd write:

class Student(Person): .

All classes inherit from Object

In java, a class can only inherit from one class, but can inherit from multiple interfaces. If a class extends an interface, it must include some implementation of all of the methods within that interface (even thay are merely passed over).

IS-A and HAS-A relationships appear in inheritance. Referring to shape classes, the shape class HAS-A circle class, and since the circle class extends shape, the circle class IS-A shape class.

In inheritance, the derived class must either override or accept the methods of the base class. Construct a derived class object by first constructing the inherited portion of the base class using super to call the base class constructor.

In the example to the left, you'd write:

public class Student extends Person {

The Object class gives all Java objects certain properties, such as rudimentary y toString() and hashCode().

The object is the foundation of all object-oriented programming.

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..

Both self and this are used to access private data fields or methods of an object within a class.

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.

Converting an object to a string__str__ methodtoString() method

Both languages can convert objects to strings, but the name of the method to override is different.

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

If a java function is to return a value, the method header must have the type of that value declared. This example header returns a String.

	public static String returnAString(){
		...
	}

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.

In java, an input scanner can be used, which parses primitive types and strings using assignment expressions. A BufferedReader can also be used, which stores the input from an InputStreamReader object.

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" meaning that only classes within the package can access the data).

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.

Declaring a final value in java:

public static final int MAX_WIDTH = 100;

This statement declares a final variable in java that is public, but cannot be changed.