# 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). |
Class files for a project in Python are contained with in a source folder. |
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
|
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.
|
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
|
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) -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 The following is illegal:
|
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. |
Sharing code from other files | import module or
|
|
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; 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 |
|
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 |
|
Not available in Python (use x+=1). | |
Exponentiation operator | x**6 |
No exponentiation operator in Java: instead, use
|
|
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. |
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. |
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. |
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. |
|
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; } 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 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 | |
calling __str__ or toString() | str(x) | x.toString() |
In many cases in Java, an explicit call to |
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 Printing | print 5 print "x =" , 5 | System.out.println(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 |
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" |
Same concepts as in Python. |
|
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. |
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. |
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:
|
All classes inherit from Object In the example to the left, you'd write:
|
The Object class gives all Java objects certain
properties, such as rudimentary y 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 | |
|
Both are called in the same way, p.move(5,7) (in Java a
semicolon is also needed). |
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. |
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
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.
|
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" 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: |