Saturday, February 27, 2010

Java Cheat Sheet

Why a cheat sheet? Object-oriented programming languages are mostly the same except for annoying syntactic differences.

Other cheat sheets: Jython/Python

General Language Notes

Statically Typed

Use semicolons to delimit statements.

Null is null.

Block structure determined by curly braces:

eg:
// sample if-then-else
    if (x == y && y != z) {
        System.out.println("condition true");
    }
    else {
        System.out.println("condition false");
    }

Printing to standard output

Printing is a method call.

Examples:

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

Defining a Class

# define a java class
    public class MyClass {
        private int x;
        public MyClass(int x) {
            // initialize instance var x 
            this.x = x;
        }

        public void myMethod() {
            System.out.println("myMethod");
        }
    }

Jython / Python Cheat Sheet

Why a cheat sheet? Object-oriented programming languages are mostly the same except for annoying syntactic differences. I probably write 1-2 python programs per year, which means I have to relearn the language every time I use it.

Other languages: Java

General Language Notes

Dynamic Typing

Use newlines to delimit statements; no semicolons.

Null is None.

Block structure determined by indentation:

eg:
#block structure example
if x == y and y != z:
    print 'condition true'
    print 'condition true'
else
    print 'condition false'
    print 'condition false'

Printing to standard output

The print statement is a statement in the language.

Examples:

print 'hello'
print 'x = ', x

The for loop

Link: for loop in python ref manual

#python for loops
for x in range(0,5):
    print x

for x in [0,1,2,3,4]
    print x

# results in all cases
0
1
2
3
4

Defining a Class

Link: Class in Python language reference

# define a python class
class MyClass:
    def __init__(self, x):
        # initialize instance var x 
        self.x = x

    def myMethod(self):
        print 'myMethod'