A quick reference card for Java syntax

The syntax of Java is based on that of C and C++. Here are a lot of basic things to absorb -- ask the demonstrators for more explanation, and don't worry if you don't follow them all -- come back to it later.

Variable declarations and assignments

The most commonly used primitive types are: int, double, char, boolean.

int quantity; // declared, but not initialised
quantity = getQuantity(); // method call
if (quantity == 0) ... // = is assignment, == is comparison
double price = 12.56; // declared and initialised
total = total + price * 1.175; // * has precedance over +
boolean inStock = (quantity > 0); // actually the brackets aren't needed
boolean specialOffer = inStock && price < 10; // boolean operations are &&, ||, !, true, false

Strings and arrays are built into the core language, but they are object types (passed by reference) rather than primitive types (passed by value).

String name = "Joe Bloggs";  
if (name.equals("Tom Smith")) ... // use s1.equals(s2) to check if s1,s2 equal
int space = name.indexOf(" "); // string operations are methods in the String class
String initials = "" + name.charAt(0) + name.charAt(space+1); // + is overloaded: adds numbers and concatenates strings
int[] a = new int[20]; // array elements are a[0],...,a[19]
int[] b; // b declared but not initialised; current value null
b = a; // arrays are first-class

By convention, variables always begin with a lower-case letter! They can be multiWordIdentifiers with uppercase letters in the middle.

 

Commands

if (boolean expression) command;

if (boolean expression) {
   command1;
command2; command3; } if (boolean expression) { block1; } else { block2; } for (int i=0; i<name.langth(); i++) { do something with name.charAt(i); } while (bexpr1) { command1; if (bexpr2) break; // breaks out of loop command2; }

Exceptions

A powerful mechanism for catching problems.

      try
        {

        myNum = Integer.parseInt( myStr );
        }

      catch ( NumberFormatException error )
        {
        // The user entered something that wasn't a number
        System.out.print( "Not an integer number: " + myStr );
        }
      }

      ...
   
      if (h<0 || h > 23)
          throw new IllegalArgumentException();

Differences between Java and C++

 

© 2001 Mark Ryan and Alan Sexton