Comments

Comments come in three styles:
  • // comment on one line
  • /* comment on one or more lines */
  • /** documenting comment */
  • Data Types

  • boolean
  • byte (8 bits - signed)
  • char (16 bits - unsigned, UNICODE)
  • short (16 bits - signed)
  • int (32 bits - signed)
  • long (64 bits - signed)
  • float (32 bits - IEEE 754)
  • double (64 bits - IEEE 754)
  • Data types always have a predefined value. Byte, short, int, long, float, and double are initialized to zero. A char is initialized to "\u0000" (NULL). All object reference types are initialized to NULL.

    Arrays

    Arrays are objects and have one instance variable, length. One can declare arrays of any type:

    	int[] array1;
    	MyObject s[];
    
    An empty array is created as follows:
    	int my_list[] = new int[10];
    
    A pre-initialized array is created as follows:
    	String names[] = {"Karen", "Paul", "Linda" };
    
    You cannot create static compile time arrays:
    	int nogood[40];  // compile time error.
    

    Operators

    Operators in Java are the same as in C and C++, except for the instanceof operator. This operator tests whether an object is of a specific type:
    	if (event.target instanceof Button) {...
    

    Classes

    Every class contains data variables and methods that act on the data. New classes create new types that are derived from the original class. The derived class is called a subclass and the original or parent class is called a superclass. Derivation is transitive, i.e. given A->B->C, then C is a subclass of A.

    A class is a template of what an object will look like, and an object is an instance of a class. The syntax is as follows (real examples are given throughout the lectures and labs):

    	modifiers class classname
    	[extends Superclassname] [implements Interface{,interface}] {
    
    		body
    
    		}
    

    Modifiers

    Modifiers can be:
  • abstract - an incomplete implementation. An abstract class must be subclassed and cannot be instantiated. An abstract class can have abstract methods. If one or more methods is abstract, the class must be abstract.
  • final - a final class cannot be subclassed anymore.
  • public - the most commonly used modifier. Public classes can be accessed from anywhere. An example of a class declaration is:
    	public class MyCourse {
    		int sum;
    
    		// MyCourse constructor (where some initialization is done)
    		public MyCourse() {
    			sum = 0;
    		}
    
    		public void Add(int j) {
    			sum = sum + j;
    		}
    	}
    
    A class instance example is:
    	MyCourse mc = new MyCourse();
    	mc.Add(95);
    

    Subclassing

    Only single inheritance is possible. Java differs here from C++ in that it uses the extends word to represent subclasses:
    	// MyNewCourse overrides Add of MyCourse
    	public class MyNewCourse extends MyCourse {
    		public void Add(int j) {
    			sum = sum + (j/2);
    		}
    	}
    
    A class instance example is:
    	MyNewCourse mnc = new MyNewCourse();
    	mnc.Add(95);
    

    Interfaces

    An interface defines methods without bodies that are inherited and defined by the implementing class. They provide encapsulation of method protocols without restricting implementation to a single inheritance tree. Using interfaces allows several classes to share a programming interface without being aware of each implementation. An interface looks a lot like an abstract class, except that it uses the keyword interface instead of the words abstract and class.
    	public interface Storing {
    		void FreezeDry(URLConnection stream);
    		void Reconstitute(URLConnection stream);
    	}
    
    	public class Image implements Storing, Painting {
    		void FreezeDry(URLConnection stream) {
    			// Compress image before storing
    			....
    		}
    
    		void Reconstitute(URLConnection stream) {
    			// Decompress image before reading
    			....
    		}
    	}
    

    Methods

    Methods are the operations performed on an object or class. They can be declared in both classes and interfaces, but can only be implemented in classes.

    The syntax for method declaration is:

    	modifiers returntype MethodName ( params ) {
    		[body]
    	}
    
    All methods (like procedures in C) must have a return type except for constructors.

    The modifiers here can be:

  • public - accessible everywhere
  • protected - accessible by subclasses of the class and by members of the class package
  • private protected - accessible only within the subclass
  • private - accessible only within the class body
  • default - "friendly" - accessible throughout the package
  • abstract - no implementation, class must also be declared abstract
  • final - cannot be overridden by subclass
  • static - implicitly final; can only refer to static variables
  • native - a method implemented in some other language, usually C
  • synchronized - per-instance (object) access lock. Acquired on entry, release on exit. It is the primary mechanism for dealing with synchronization between multiple threads
  • The argument list (parameters) can only be pass-by-value (objects are passed as their object reference value). Methods with the same name, return type, number and type of arguments in the class override the parent class method.

    Constructors

    Constructors have the same name as the class and do not specify a return type. They are called automatically upon object creation and serve to initialize the data members of the object. They may be overloaded, but the default constructor is the parent class constructor.

    The first statement may be:

    	super(...); // calls superclass initializer
    	this(...); // calls this class initializer
    

    Exceptions

    The following is a list of the most used exceptions from the Java.lang package:
  • ArithmeticException
  • NullPointerException
  • IncompatibleClassChangeException
  • ClassCastException
  • NegativeArraySizeException
  • OutOfMemoryException
  • NoClassDefFoundException
  • ArrayIndexOutofBoundsException
  • UnsatisfiedLinkException
  • InternalException
  • You can also create your own new exception:

    	class MyException extends Exception { }
    
    	class MyCourse {
    		void oops() throws MyException {
    			if (some_error_occured) {
    				throw new MyException();
    			}
    		}
    	}
    

    Exceptions must be either thrown or caught. You can catch exceptions and recover from them:

    	try { a[i] = 10;
    	} catch (ArrayIndexOutOfBounds e) {
    		System.out.println("a[] out of bounds");
    	} catch (MyException e) {
    		System.out.println("Caught my error");
    	} catch (Exception e) {
    		System.out.println(e.toString());
    		
    	} finally {
    		// stuff to do regardless of whether an exception was thrown
    	}
    

    Packages

    Packages group classes and interfaces. Java comes with these packages:
  • java.applet - contains Image display and Audio classes
  • java.awt - contains Window, Frame, Button, and other GUI components
  • java.io - contains File I/O, InputStream, OutputStream, and PrintStream
  • java.lang - contains Object, Thread, Exception, System, and Strings
  • java.net - contains ServerSocket, Socket, URL, client/server connections, TCP.IP, and UDP
  • java.util - contains Date, Vector, Hashtable, Stack, and Random
  • If you want to use one or more of these classes you must include the right package. You do this by using the import command. The import command specifies which package to load and is used by the compiler to mark class names. There are three ways to declare class names:

  • import all classes within a package:
    import java.io.*;
  • import specific class names:
    import java.net.socket;
  • use fully qualified class names:
    paint(java.awt.Graphics g) { }