Java Quick Reference


Contents


Syntax for a class (including constructors, methods, and fields)

Class Syntax

/**
 * Description of the class
 */
accessSpecifier class ClassName
{

    ///////////////////////////
    // Data Members (fields)
    ///////////////////////////

    accessSpecifier fieldType fieldName; // description of field
    


    //////////////////
    // Constructors
    //////////////////

    /**
     * Describe what constructor does
     * @param p1 describe the first parameter
     * @param p2 describe the second parameter
     */
    accessSpecifier ClassName(paramType paramName, paramType paramName)
    {
        // constructor body
    }
    
    
    
    /////////////
    // Methods
    /////////////

    /**
     * Describe purpose and use of the method.
     * @param p1 describe the first parameter
     * @param p2 describe the second parameter
     * @return describe the value returned
     */
    accessSpecifier returnType methodName(paramType paramName, paramType paramName)
    {
        // method body
    }

}

Example

/**
 * A Human has a name and an age.  A human's name can be changed at any time.
 * A human's age only changes when the human has a birthday.
 */
public class Human {

    private String name;  // the human's name
    private int age;      // the human's age
    
    /**
     * Creates a human with the given name.  The human starts out at age 0.
     * @param initName the name to give the human
     */
    public Human(String initName) {
        name = initName;
        age = 0;
    }
    
    /**
     * Returns the name of this human.
     * @return the name of the human
     */
    public String getName() {
        return name;
    }
    
    /**
     * Returns the age of this human.
     * @return the age of the human
     */
    public int getAge() {
        return age;
    }
    
    /**
     * Changes the name of this human to the new name given.
     * @param newName the new name for the human
     */
    public void setName(String newName) {
        name = newName;
    }
    
    /**
     * Causes the human to have a birthday (i.e., adds a year to the age).
     */
    public void haveBirthday() {
        age = age + 1;
    }
}  

Primitive and reference types

Primitive vs. Reference Data Types

Assignment

Comparisons (e.g., ==)

Passing Parameters

Returning Values


Java operators and operator precedence

Numeric operators

arithmetic operators

+addition
-subtraction
*multiplication
/division
%modulus (remainder)

Note: applying an operator to two integer operands results in an integer result. For example, the result of 13 / 5 (an int divided by an int) is 3.

unary operators

+unary plus      ++increment
-unary minus      --decrement

compound assignment operators

+= -= *= /= %=
For each compound assignment operator op=,
x op= y;   is the same as   x = x op y;

Relational (comparison) operators

==equal to      !=not equal to
>greater than      >=greater than or equal to
<less than      <=less than or equal to

Logical (boolean) operators

!NOT (unary)
&&AND
||OR

See Java operator precedence for information about Java's order of operations.


Syntax for decision statements

if-else

if ( boolean expression )
	if block
else
	else block
Note:

switch

switch ( arithmetic expression ) {
	case label 1 : case body 1
	case label 2 : case body 2
	...
	case label n : case body n
}
Note:

Syntax for loops (repetition statements)

while

while ( boolean expression ) 
	block	

do-while

do {
	block
} while ( boolean expression );

for

for ( initialization ; boolean expression ; increment )
	block

Syntax for interfaces (defining and implementing)

Defining an interface

Java Syntax

public interface InterfaceName {
	method prototypes
}

Example

public interface Ownable {
    Owner owner();
    boolean updateOwner(Owner newOwner);
}

Implementing an interface

Java Syntax

public class ClassName implements InterfaceName1, InterfaceName2, ... {
	data members
	constructors
	methods
}

Example

public class Car implements Ownable {

    // data members
    private Owner myOwner;
	
	
	
    // constructors
	
    // other Car methods
	
    public Owner owner() {
    	return myOwner; // method implementation
    }
	
    public void updateOwner(Owner newOwner) {
        myOwner = newOwner;
        return true;
    }
}

Exceptions

Throwing an Exception - where the error is detected

throw exceptionObject;

Example: throw new IllegalArgumentException();

Handling an Exception

using try-catch

try {
    code that might raise an exception 
} catch (ExceptionType1 identifier1) {
    code to handle exception type 1    
} catch (ExceptionType2 identifier2) {
    code to handle exception type 2   
} ...
finally {  // note: the finally clause is optional
    code executed no matter what happens in try block   
}

using a throws clause

... methodName(parameter list) throws ExceptionType { ...

... methodName(parameter list) throws ExceptionType1, ExceptionType2, ... { ...

Example: public static void main(String [] args) throws IOException { ...

Defining an Exception

Define a new class that is a subclass of Exception (either directly or through the inheritance hierarchy).

Example

public class EmptyBagException extends Exception {

    public EmptyBagException() {
        super();
    }
    
    public EmptyBagException(String msg) {
        super(msg);
    }
}

File and console input and output

See also:

Console I/O

For console input, use a Scanner object

For console output, use System.out

File I/O

For file input, use a Scanner object

For file output, use a PrintStream object