Use these checkboxes to control the appearance of the document :

Show Clear Talk facts
Show subject hyperlinks
Bullet and highlight facts (as opposed to bar '|' delimited facts)

The Basics of Java

© Doug Skuce, Tim Lethbridge

School of Information Technology and Engineering

University of Ottawa

7/6/2003    3:37 PM

Main Features in Brief

Introduction

Java is an object-oriented programming language and, like C++, shares much of its syntax with the C programming language. If you know how to write statements, including variable declarations and loops, in one of these three languages, then you have a head start in learning the others. However, many other details differ among the languages. The biggest difference is that C is not object-oriented while the other two are. Also, the data types and libraries available are considerably different.

Java is a kind of object-oriented programming language Java's syntax is similar to (C++'s and C's) syntax (Java and C++'s) are object-oriented (Java, C) difference: C is not object-oriented

Java was developed at Sun Microsystems in the mid-nineties. It has a useful combination of features that, combined with the fact that it is a member of the C/C++ family, have made it very popular in recent years.

Java was developed at Sun Microsystems in the mid-nineties Java is very popular

The following section describes some of Java's most important features.

Platform-independence

Java is platform-independent, i.e. it is designed to be run using a virtual machine, or VM. Java compilers compile source code (typically found in files ending with the .java suffix) into files containing bytecode (typically in files ending with the .class suffix, or in libraries ending with .jar). Java source code is also found in JServer pages which are files which end with .jsp. These pages are JavaSoft's version of MicroSoft's Active Server Pages.

Java runs using a virtual machine (aka: VM, JVM) Java compilers compile source code into files containing bytecode Source code is typically found in (files whose names end with .class or libraries whose names end with .jar) A platform is the (hardware or software) environment in which a program runs; example: Windows Java is platform-independent platform-independent is a synonym of portable

Bytecode is like a universal machine language – it is very low-level in the sense that it is not designed to be read by human beings. At the same time, programs in bytecode can be run on any computer that has a VM. The VM acts as an interpreter for the bytecode; this makes Java programs portable; Bytecode compiled on one computer can be run on a different architecture. The VM itself is a complex program usually written in C or C++.

Bytecode is like a universal machine language; it is very low-level Bytecode can be run on any computer that has a VM A VM acts as an interpreter for bytecode Java programs are portable because they are written in bytecode

Use over the Internet

Java is designed with very easy-to-program networking capabilities; In addition, small programs called applets can be loaded directly into a web browser. A properly configured Java VM will not allow violations of certain security constraints when programs are downloaded over the Internet.

Java is easy to use for networking Some Java programs (called: applets) can be loaded directly into a web browser A Java VM will not allow violations of certain security constraints when applets are downloaded over the Internet

Removal of troublesome C++ features

C++ has many powerful capabilities, such as pointer arithmetic, multiple inheritance, macros and operator overloading. Although powerful, these can make programs difficult to understand, so they have been deliberately left out of Java. Also, Java will not let programmers refer to information beyond the end of an array, or follow an invalid pointer.

Java does not have (pointer arithmetic, multiple inheritance, macros and operator overloading); except: a few operators (eg +) are overloaded You cannot (refer to information beyond the end of an array and use a pointer) in Java

Garbage collection

Garbage collection is the process of finding and reusing small pieces of memory that are no longer needed.

Java has garbage collection (aka: automatic memory recycling) You do not need to free objects from memory when you no longer need them; unlike: (C and C++) The VM will reclaim objects that are no longer being used

Efficiency

Java tends to be less efficient than programming languages like C or C++ for two reasons : First, Java's safety checks and garbage collection slow down execution. Second, the interpretation of bytecode is not as fast as direct execution of machine code. Most virtual machines assist with this latter problem by using what is called just-in-time compilation (JITC). This means that the first time a method is executed, the VM converts it into machine code and stores the machine code to save work on subsequent calls. However, even with JITC, Java is not as fast as a fully compiled language. Java performance can be as bad as 10 times slower than C++, but can be as fast as 1.5 times slower than C++.

Java is less efficient than C or C++; because: Java's safety checks and garbage collection slow down execution; The interpretation of bytecode is not as fast as direct execution of machine code Most virtual machines assist with interpretation of bytecode using just-in-time compilation (aka: JITC) JITC means that: when a method is executed the first time the VM converts that method into machine code and then the VM stores that machine code to save work on subsequent calls Java is not as fast as a fully compiled language Java's performance can be 1.5 to 10 times slower than C++'s performance

However, the reduced efficiency of Java is often not a problem. In today's world, hardware is so fast that efficiency does not always need to be a high priority. Also, the cost of programmers' time tends to be far more expensive than hardware, so development teams can save money by using Java, which is easier to program than C++ The savings in programmer time can easily pay for faster CPUs. Nevertheless, Java's lower efficiency means that it is not suited to every application: A program that primarily performs CPU-intensive calculations should probably be written in a more efficient language.

Incidentally, the fact that Java uses a virtual machine or has garbage collection is not unique. Smalltalk is another OO language that also has these features; in fact many of the ideas in Java were adopted from Smalltalk which was designed in the seventies.

Smalltalk is a kind of object-oriented language that has (a virtual machine and garbage collection); similar to: Java Many of the ideas in Java were adopted from Smalltalk Smalltalk was designed in the seventies at Xerox PARC

There is a related language called JavaScript which is used to add functionality to web pages. Despite sharing much of the same syntax and many of the same keywords, Java and JavaScript should be seen as clearly separate languages.

Javascript is a kind of programming language that is used to add functionality to web pages Javascript is similar to Java

Documentation

One of the most important skills for anyone designing or programming software is to be able to navigate the documentation and look up the methods available to achieve some objective. Java comes with extensive on-line documentation about each class and method; you should become familiar with how to look up information in this documentation.

The documentation is available on Sun's web site at http://java.sun.com You may also find a copy of the documentation that was installed with the Java compiler and VM on your local disk or network.

Java has extensive on-line documentation about each (class and method) Java's documentation is on Sun's web site Sun's web site url: http://java.sun.com Java's documentation is also normally installed on (your local disk or network)

Hello World

It is traditional to show the "Hello World" example at the beginning of programming language descriptions. To make a Java application (a kind of Java program, as we will see later) that prints "Hello World", enter the following in any text editor:

class HelloWorld {
    public static void main(String args[]) {
        System.out.println("Hello World");
    }
}

Save it as "HelloWorld.java" and then compile it with the Java compiler:

javac HelloWorld.java

Now you can run the resulting compiled class file (called HelloWorld.class) by typing:

java HelloWorld

Concepts of Java

Classes

Classes are the units of data abstraction in an object-oriented program. More specifically, a class is a software module that represents and defines a set of similar objects, also called its instances. All the objects with the same properties and behaviour are instances of one class. A program is built up out of classes. Classes are one of the fundamental features of the object-oriented paradigm.

class definition: a unit of data abstraction in an object-oriented program class definition: a software module that (represents and defines) a set of similar (objects and operations on these objects) The objects of a class are also known as the instances of the class All objects with the same (properties and behaviour) are instances of one class A program consists of one or more classes Classes are one kind of the fundamental features of the object-oriented paradigm

All Java code must be written inside of some class, which serves to gather together some related data and procedures, called methods. Thus the smallest program consists of one class, while a large system would have hundreds of classes.

All Java code must be written inside of some class Class purpose: to gather together some (related data and procedures (aka: methods)) The smallest Java program consists of one class A large Java program has hundreds of classes Class purpose: to store data in the class; called: class variables; to specify methods to operate on these data; called: class methods; to specify the structure of the data in its instances; called: instance variables; to specify methods to operate on the data in the instances; called instance methods A class can have zero to many instances A class' procedures are also known as methods Java code is always in a block A block is a kind of (a class body, a method body, or a nested block that is inside another block)

For example, Figure 1 shows how bank employees can be represented as instances of the class Employee, which declares that all its instances have a name , a date of birth, an address and a position.

Figure 1 A class representing Employees.

As a software module, a class contains all of the code that relates to its objects, including:

A class is a kind of software module A class contains: all of the code that operates on its objects all the declarations describing how the objects of the class are structured Code that operates on class is called an instance method An instance method purpose: to implement part of the behaviour of the objects of a class

In other words, in addition to defining the properties such as name and address, as shown in Figure 1, an Employee class would also provide methods for creating a new employee, and changing an employee's name, address and position.

Sometimes it is hard for beginners to decide what should be a class and what should be an instance. The following two rules can help: For example, in an application for managing hospitals, one of the classes might be Doctor, and another might be Hospital. You might think that Hospital should be an instance if there is only one of them in the system. However, the fact that in theory there could be multiple hospitals tells us that Hospital should be a class. If you are thinking that something might be an instance, ask yourself what it is an instance of, and that will be a class.

Here is the basic structure of a class:

  class classname {
      // declarations of variables
      // declarations of constructors (see below)
      // declarations of other methods with public ones first
  }

class declaration example:

  public Employee class {
    String name;
    Date dateOfBirth;
    Address address;
    String position;

    Employee(String aName){
      name = aName
    };

    getName() {
      return name
    };
  }

Naming classes

One of the first challenges in any object-oriented project is to name the classes. Notice that the class names mentioned in the last subsection such as Employee, Hospital and Doctor are nouns, have their first letter capitalized and are written in the singular. These are important conventions that should be followed in all object-oriented programs.

class names should (have their first letter capitalized and be written in the singular)

Being consistent about capitalization ensures that readers of the program can tell what is a class and what is not. Using the singular ensures that readers can tell that an instance of the class is a single item, not a list or collection. If you want to give a class a class consisting of more than one word, then omit the spaces and capitalize the first letter of each word, for example: PartTimeEmployee.

It is also important to choose class names that are neither too general nor too specific. Many words in the English language have more than one meaning, or are used with a broad meaning. For example the word 'bus' could mean the physical vehicle, or a particular run along a particular route, as in,"I will catch the 10:30 bus (but I don't care which vehicle is used)". You might choose to call the class that represents physical vehicles BusVehicle and the class that represents runs along a route BusRouteRun.

Another principle is to name classes after the things their instances represent in the real world. Unless you are dealing with low-level system design, you should avoid using words in class names that reflect the data structures of a computer system such as 'Record', 'Table', 'Data', 'Structure', or 'Information'. For example, a class named Person would be acceptable, but one named PersonDataRecord would not.

All the code of a Java program must be placed inside classes. This is an important difference from C++, which allows some code to exist outside classes. You normally put each Java class in a file of the same name.

All the code of a Java program must be placed inside classes; difference: C++ allows code to exist outside classes Each class is normally in a file of the same name A Java program has as parts one or more classes Class syntax: classModifiers 'class' className classBodyBlock classBodyBlock syntax: { declarations of variables declarations of constructors declarations of methods with public ones first } comment: The exact order of these elements is a matter of convention

Objects

An object is the main kind of data element in an object-oriented system. It has its own identity, belongs to a particular class, and has behaviour and properties defined in the class. The term 'instance' is often used as a synonym for object. An object can represent any entity to which you can associate properties and behaviour. An object can model a real world object or an abstract concept.

An object is a kind of data element of an object-oriented system belongs to a class has a behaviour defined by the instance methods of its class has a unique identification number called its identity Object is also known as instance

The following are some examples of classes of objects:

Each instance, e.g; each employee, would be an object from its class.

Figure 2: Several objects in a banking application

State and Behaviour

An object's variables maintain its state and its methods specify its behaviour. An object shares all the class variables of its class with the other instances of its class, and it shares the instance methods. Every object knows what class it belongs to and can return its class using the getClass method. It can also convert itself to a string representation using the toString method.

An object's variables purpose: to maintain its state An object's methods purpose: to specify its behaviour An object shares (the class variables, the class methods, and the instance methods) with the other instances of its class Every object knows what class it belongs to; it can return an object that represents its class using the getClass method Every object can convert itself to a string representation using the toString method

Objects communicate with each other by sending and receiving what are called messages, similar to a procedure call in other languages. An object can send and receive messages to and from objects in the same process, objects in different processes, objects on the same machine, and objects on different machines.

Objects communicate with each other; how: by (sending and receiving) messages Messages are similar to procedure calls in other languages An object can (send and receive) messages (to and from) (objects in the same process, objects in different processes on the same machine, and objects on different machines)

Inheritance Hierarchy

Classes are arranged in a hierarchy called an inheritance hierarchy. The programmer must specify the 'parent' class of each, called its super class. At the top of the hierarchy is the most general class, called Object. All classes are subclasses of it. Each object automatically inherits (i.e. obtains) instance methods and instance variables (i.e. the data in the instances and the methods for these data) from the class to which it belongs and all that class's superclasses as well.

Classes are arranged in a hierarchy called an inheritance hierarchy You must specify the parent (aka: super) class of each class; comment: if you do not specify the parent then the parent class is 'Object' At the top of the hierarchy is the most general class (called: 'Object') All classes are subclasses of 'Object' Inheritance definition: is a kind of mechanism where an object automatically inherits (instance methods and instance variables) from (the class to which it belongs and all that class's superclasses) Inheritance is one kind of the fundamental features of the object-oriented paradigm

To create a subclass of a class Account, i.e. Account will be the super of the subclass, you use the extends keyword, as in the following example:

  public class MortgageAccount extends Account {
    // body of the class
  }

According to the above, class MortgageAccount is a subclass of Account. Any instance variables or methods defined in Account (or its superclasses) are now also implicitly present in the new subclass – in other words they are inherited.

Single Inheritance

In Java, a class can have only one superclassthis is called single inheritance. Other languages, such as C++ allow more than one parent. Multiple inheritance can result in more confusing systems, hence the designers of Java decided it was better to allow only single inheritance.

Each class has one superclass; except: Object Single inheritance means: that a class has only one superclass Some programming languages such as C++ allow multiple inheritance Multiple inheritance means: that a class can have more than one parent The designers of Java feel that multiple inheritance can cause unclear programs

Organizing Classes into Inheritance Hierarchies

If several classes have attributes, associations or operations in common, it is best to avoid duplication by creating a separate class that contains these common aspects. Conversely, if you have a complex class, it is usually good to divide it into several more specialized classes.

The two-level hierarchy formed from one superclass with several immediate subclasses is commonly called a generalization. A hierarchy with multiple levels of generalization is called an inheritance hierarchy, a generalization hierarchy or an isa hierarchy.

You control inheritance by creating an inheritance hierarchy. Once you define which classes are superclasses and which classes are their subclasses, inheritance automatically occurs.

The two-level hierarchy formed from one superclass with several immediate subclasses is called a generalization A hierarchy with multiple levels of generalization is called (an inheritance hierarchy, a generalization hierarchy or an isa hierarchy) You define inheritance by creating an inheritance hierarchy You create a subclass of a class by using the keyword 'extends'; example: Class2 extends Class1 Inheritance is one kind of the fundamental features of the object-oriented paradigm

Variables

Instance variables, Attributes and Associations

A variable is a place where you can put data. Each class declares a list of variables corresponding to data that will be present in each instance; such variables are called instance variables. Instance variables are operated on by instance methods.

A variable purpose: a place to store data Every class declares the set of variables (called: instance variables) that will be present in each instance of the class Instance method purpose: to operate on instance variables There are two kinds of instance variable: (those used to implement attributes and those used to implement associations) An association purpose: to represent the relationship between instances of one class and instances of another Attribute purpose: to represent a (property or characteristic) of an object

An attribute is a simple piece of data used to represent the properties of an object. For example each instance of class Person might have the following attributes:

An association represents the relationship between instances of one class and instances of another. For example, class Person in a business application might have the following relationships:

Class variables

Sometimes you want to create a variable whose value is shared by all instances of a class. Such a variable is known as a class variable or static variable. If one instance of the class sets the value of a class variable, then all the other instances see the same changed value.

Class variables are often overused by beginners in cases when they should use instance variables. Class variables are, however, useful for storing the following types of information:

A class variable must have the keyword static. You access a class variable by specifying the name of the class, followed by a dot, followed by the name of the variable.

A class variables purpose: to store data in a class A class variables has the keyword 'static' An instance variable does not have the keyword 'static' If a variable is in another class then you access it by specifying the name of the class, followed by a dot, followed by the name of the variable; example: Student.numberOfStudents

Variables versus objects

One common source of confusion when discussing object-oriented programs is the difference between variables and objects. Variables and objects are distinct entities. At any given instant, a variable may refer to a particular object or to no object at all. (We shall see later that some variables refer to data that are not objects, called primitive values.) Variables that refer to objects are therefore often called references. During the execution of a program, a given variable may refer to different objects. Furthermore, an object can be referred to by several different variables at the same time.

We declare the type of a variable to specify what classes of objects or values it may contain. We will explain the rules regarding this in later sections. The primitive data types (e.g. numbers, see below), which are not objects, can also be referred to by variables, which then would have a primitive type(see below).

If you declare that a class has an instance variable called var, then you are saying that each instance of the class will have its own piece of data named var. So, for example, each Employee has a supervisor. The actual data put into these variables will vary from object to object: Employees will have different instances of Manager as their supervisors.

A variable refers to (an object or to primitive data) Variables that refer to objects are called references A variable may refer to different data during the execution of a program An (object or primitive datum) can be referred to by several different variables at the same time The type of a variable determines what values it may contain (Primitive data and objects) are distinct If a class has an instance variable (V) then each instance of the class will have its own piece of data that is called V;  example: each Employee has a supervisor

Methods

A method is a concrete implementation of an operation; a procedure associated with a class. The term "method" for us is a synonym of the terms "function member" or "member function" which are used in C++, and the terms "routine", "function" or "method" which are used in non object-oriented programming languages. Methods are procedural abstractions used to implement the behaviour of a class or its instances.

A method is a kind of concrete implementation of an operation; it is a kind of procedure associated with a class The term "method" is similar to the terms (("function member" or "member function" that are used in C++) and the terms ("routine", or "function") that are used in non object-oriented programming) Methods are a kind of procedural abstraction; purpose: to implement the behaviour of (a class or an object)

Instance methods

A method belongs to a class and, in the case of instance methods, can be inherited by subclasses of its class. Each method has a method signature - the method's name and the number and the types of its parameters including the invoking object. Several methods may have the same name so long as they have different method signatures - this is called method name overloading or polymorphism. This makes it possible for methods to behave differently depending on the arguments they receive.

A method belongs to a class Instance methods can be inherited by subclasses of their class Each method has a signature A method's signature definition: (the method's name, the number, the types of its parameters, the type of the invoking object) Several methods may have the same name if they have different signatures called: (method name overloading or polymorphism) Polymorphism purpose: methods can behave differently depending on the arguments they receive

There are two kinds of methods: instance methods and class methods (also called static methods). An instance method executes in the context of a particular object. It has access to the instance variables of the given object, and can refer to the object itself using the 'this' keyword. A class method affects the class as a whole, not a particular instance of the class.

There are two kinds of methods: instance methods, class methods Class method are also called static methods An instance method executes in the context of a particular object (called the invoking object); it has direct access to the instance variables of the object; it can refer to the object itself using the 'this' keyword A class method affects the class as a whole; it does not affect a particular instance of the class Method syntax: access modifier return type name(arguments) block where:
access modifier is an instance of an access modifier return type is an instance of a type or class name arguments is a list of zero or more argument declarations block is a block for the implementation (called the body) of the method
example:
public double credit(double amountToCredit)
{
    balance = balance + amountToCredit;
    return balance;
}

If a method is declared with the same method signature as a method in a superclass, then this method overrides the method with the same method signature in the superclass. You can access the overridden method in the superclass by using the 'super' keyword. Here is an example of calling an overridden method:

super.myMethod(a,b)

Class Methods

A class method is a method marked static. When a class method executes it is not working on a particular instance of the class. You can therefore manipulate class variables or call other class methods of the class.

You call a class method by using the name of the class, followed by a dot, followed by the name of the method (the name of the class can be omitted when calling a class method in the current class).

A class method has the keyword 'static' An instance method does not have the keyword 'static' A class method does not normally use a particular instance of that class; comment: but there is nothing to prevent this You can (manipulate class variables and call other class methods of the class) from a class method A class method call syntax: classname.method_name(parameter_list); example: MyClass.classMethod() An instance method call syntax: object_reference.method_name(parameter_list); example: myObject.instanceMethod()

Polymorphism

An abstract operation is a higher-level procedural abstraction: It is used to specify a type of behaviour independently of any code which implements that behaviour. Several different classes can have methods with the same name that implement the abstract operation in ways suitable to each class. The word 'method' is used because in English it means 'way of performing an operation'.

We call an operation polymorphic if the running program decides, every time an operation is called, which of several identically-named methods to invoke. The program makes its decision based on the class of the object in a particular variable and on the arguments. Polymorphism is one of the fundamental features of the object-oriented paradigm.

An abstract operation is a kind of higher-level procedural abstraction; purpose: It is used to specify a type of behaviour independently of any code which implements that behaviour Classes can have methods with the same name that implement an abstract operation in ways suitable to the class If an operation is polymorphic then the system decides which of several identically named methods to use when the operation is invoked; The system makes its decision based on (the class of the invoking object and on the arguments) An invoking object definition: is the object before the dot Polymorphism definition: a kind of mechanism that permits multiple choices of a method implementation depending on the argument types Polymorphism is one kind of the fundamental features of the object-oriented paradigm

As a illustration of polymorphism, imagine a banking application that has an abstract operation calculateInterest. In some types of account, interest is computed as a percentage of the average daily balance during a month. In other types of account, interest is computed as a percentage of the minimum daily balance during a month. In a mortgage account, to which you can only deposit (pay off) but from which you can not withdraw except initially, interest may be computed as a percentage of the balance at the end of the month.

In the banking system, the three classes ChequingAccount , SavingsAccount and MortgageAccount would each have their own method for the polymorphic operation calculateInterest. When a program is calculating the interest on a series of accounts, it will invoke the version of calculateInterest specific to the class of each account.

Major Syntactic Structures

Java programs are a series of statements. An assignment statement in Java uses the '=' symbol. It is the simplest kind of statement, apart from declarations. A semicolon terminates all statements:

aVariable = 5;

assignment statement syntax: variable = expression;; example: aVariable = 5;; comment: All statements terminate with a semicolon

A call to a class method in the current class (i.e. the class having the method doing the call) looks like the following:

resultVariable = methodName(argument1, argument2).

In this case, the result is assigned to the variable resultVariable.

If there are no arguments to a method, use open and close parentheses with nothing in between, thus:

resultVariable = noArgumentMethod().

The dot (.) symbol is used to access an instance variable of an object stored in a variable, thus:

aVariable = b.variableName;

gets the variable called variableName in the object referred to by the variable b

A call to a procedure in the current class; example: resultVariable = methodName(argument1, argument2) A call to a procedure is also called a method invocation The class definition: the class having the method in which the call occurs If there are no arguments to a method then you use (open parentheses, close parentheses ) with nothing in between; example: resultVariable = noArgumentMethod() an instance variable reference to an object (obj); example: aVariable = obj.variableName

Blocks

Several statements can be placed together in a block, surrounded by braces (' {' and ' }', also colloquially known as curly brackets). Blocks are one of the main scoping units, i.e. new declarations can be introduced in a block. Blocks are used primarily as the bodies of classes, loops, conditional statements and for exception handling. All of these uses are discussed later.

Statements can be placed together in a block surrounded by braces (aka: curly brackets) Block is a kind of scoping unit syntax: '{' [declarations] statements '}'; purpose: (to group a sequence of statements and to permit new declarations); example: {int a; a = 5; b = computeSomething(c); } Scoping unit definition: a part of a program in which a name has a fixed meaning

Conditional statements and choice among alternatives

A condition in Java is an expression that evaluates to a boolean value ( true or false). The following are examples of conditions:

aNumber > 5

aNumber < 5

aNumber > 5 && anotherNumber < 7

aNumber == anotherNumber

A condition is a kind of expression that evaluates to a boolean value There are 2 instances of boolean values: (true, false) Boolean values are a kind of primitive value Condition example: aNumber > 5 Java has 3 kinds of conditional statement: ( if statement, ?: statement and switch statement) if statement syntax:
if (condition) {
   // block of statements to execute if condition is true
}
else {
   // block of statements to execute if condition is false
}
If there is only a single statement in the true or false case of an if statement then the curly brackets can be omitted The else block of an if statement can be omitted

The ?: operator can be used to execute one of two alternative expressions, depending on the value of a condition :

result = (condition) ? doSomething() : doSomethingElse();

If condition is true, then result is set to the expression following the question mark, otherwise result is set to the expression following the colon. The ?: operator can shorten some code, but make other code harder to understand. As a rule of thumb, always choose the form which results in the most readable code.

A switch statement syntax:
switch(primitiveVariable)
{
   case value1:
      // statements to execute if primitiveVariable equals value1
      break;
   case value2:
      // statements to execute if primitiveVariable equals value2
      break;
      ;;;
default:
      // statements to execute if none of the above cases occur
}
break keyword purpose: to jump past remaining cases switch statement purpose: to select an action based on the value of a variable

A few general comments about the switch statement:

You can use polymorphism to reduce the need for switch statements.

Loops

There are 2 kinds of loop statement: ( for statement, while statement);
comment: their syntax is identical to loops in C and C++ while statement syntax:
  while (condition) {
    // statements to keep executing while condition is true
  }
where:
condition is a Boolean expression
for loop syntax:
  for (initializer; condition; incrementer) {
   // statements to keep executing while condition is true
  }
where:
initializer is a simple statement that sets up some kind of initial condition for the loop
condition is an expression that returns a boolean value, normally testing the variable initialized in the initializer; the condition is evaluated before every iteration through the loop;
incrementer is a statement executed after every iteration through the loop, updating the variable set in the initializer

You can, in general, interchange a while loop and a for loop. To turn a while loop into a for loop, move the initializer before the while statement, and ensure that the incrementer is the last statement executed in every iteration. The advantage of using a for loop is that all the information about controlling the loop is kept in one place. The disadvantage is that it can be slightly harder to read the code of a for loop.

Comments

Comments in Java take two forms: Two slashes '//' indicate that the rest of the line is to be considered a comment and hence ignored by the compiler. Alternatively you can start a comment with '/*' and end it with '*/'. Anything between this pair of markers is ignored.

Comments syntax: (' // ' text to end of line and /* any text */ )

Types

Variable declarations and data types

You declare variables in Java by giving the data type followed by the name of the variable. A variable declaration can be placed practically anywhere in Java code, although it is good practice to only declare variables at the beginning of blocks. Variable types can classified as either object or primitive. The first to are referred to via pointers that are hidden. They are also called the reference types for this reason.

A variable declaration; syntax: typeName varName; example: int x; String s A variable declaration can be placed practically anywhere in Java code; comment: it is good practice to only declare variables at the beginning of blocks There are 2 kinds of types: object types, primitive types Object types are accessed via pointers that are hidden Object types are also called reference types

Primitive types

The primitive types act like in C. You cannot have a pointer to a primitive. Primitives are stored directly in their variables. The following are some examples of variable declarations, illustrating all the primitive data types of Java :

  byte aByte;      // an 8-bit value
  short aShort;    // a 16-bit integer
  int anInteger;   // a 32-bit integer
  long aLong;      // a 64-bit integer
  float aFloat;    // a floating point number
  double aDouble;  // a double-precision floating-point number
  char aChar;      // a character of Unicode, discussed below
  boolean aBoolean;// must be one of true or false

there are 8 instances of primitive types: (byte, short, int, long, float, double, char, boolean) if a variable's type is primitive then its primitive value is stored directly in the variable The set of operations available to work with primitive data types is limited and it cannot be extended.

In the above declarations, the types all start with a lower-case letter. This distinguishes them as primitive data types since the reference types use upper case. You can use primitive data types for many purposes, but variables declared using these types do not contain objects – their contents are not instances of any class. They contain the data directly.

The set of operations available to work with primitive data types is rather limited and cannot be extended. The basic arithmetic operators +, -, *, / and % (for modulus) can be used with values that have type byte, short, int, long, float, or double.

The logical operators && (and), || (or) and ! (not) can be used to operate on boolean values.

Object Types

In addition to referring to primitive values, variables are also used to refer to objects in a Java program. To declare such variables, you use the name of a class as their type, indicating that a pointer to an instance of that class is to be put into the variable. Whenever the type in a variable declaration starts with a capital letter, you know that it is a class, not a primitive type.

A variable refers to (an object or a primitive value) To declare a variable that refers to an object you use the name of a (class or interface) as its type A variable that refers to an object contains a pointer to that object If a type's name starts with a lower case letter it is a primitive type If a type's name starts with an upper case letter it is ((an object type and the name of a class) or an interface name) If a variable's type is an instance of an interface name then any object that the variable refers to must belong to a class that implements the interface

Java defines many standard classes that can be used in any program. Important examples are String and ArrayList, shown below. You can also define your own classes such as PostalCode.

  String aString;        // an object that contains a string of characters (discussed later)
  ArrayList anArrayList; // an object that contains a list of objects (discussed later)
  PostalCode aPostalCode;// an object of class PostalCode

Java has many built-in classes that can be used in any program; examples: String, ArrayList To define your own class how: write a class declaration

To work with variables from these classes, you have to call methods or access instance variables that are found in the declared class or its superclasses.

Arrays

Besides ordinary objects, arrays are the other reference type. Arrays have a special status in Java. They are objects, but they are not instances of a class which you can subclass or for which you can write your own code. They have a special syntax. They cannot have instance variables. An array variable in Java is declared using square brackets following the element type. The following are some examples:

  int[] anIntArray = new int[25];
  byte[] aByteArray;   // not initialized
  Account[] anAccountArray = new Account[numAccounts];

As these examples show, arrays can be composed both of primitive types like intand byte, and also of instances of classes, such as Account objects. The number of elements in an array can be a constant or a variable.

The Array type is an instance of a reference type Arrays are unusual because they are not considered instances of a class You cannot (subclass the Array class or modify the Array class) An array variable in Java is declared using square brackets following the element type; example:  int[] anIntArray; An array object is normally created by using the 'new' operator; example: anIntArray = new int[25]; comment: strings and arrays can be created by literals; example: int[] x = {1, 2, 3};

In order to access an element of an array, you use square brackets and specify an index. You can also request the length of an array. For example, the following sums all the elements of an int array:

  int sum=0;
  for(int i=0; i < anIntArray.length; i++)
  {
    sum += anIntArray[i];
  }

An important thing to remember about arrays (and the specialized collection classes) is that they are zero-based. This means the first element is element 0.\ It also means that the highest numbered element is one less than the length of the array.

arrays are zero-based; means: the first element has index 0

The alternatives to arrays are the classes which we will discuss in the next two sections: String, for ordered collections of characters, and collection classes such as Vector and ArrayList, for collections of arbitrary objects.

Characters and Strings

In many programming languages, a character is an 8-bit byte encoded using ASCII. Unfortunately, although ASCII was an excellent invention for the English-language applications of the 1950's and 1960's, it is not capable of representing the wide variety of printed symbols used in other languages.

To make Java extendible to most of the written languages of the world, it uses a coding scheme called Unicode instead of ASCII. Characters in Unicode use 2 bytes. However the exact details of the representation of each character is normally not important to programmers. All a programmer needs to know is that when he or she is working with characters, they could be from an unusual character set. The basic ASCII characters remain a part of Unicode, and programmers can still use the byte datatype to work with 8-bit ASCII characters if they truly need to do so. It is bad programming practice, however, to use bytes for textual data which is to be exposed to the end user.

Java's character coding scheme is called Unicode Characters in Unicode use 2 bytes ASCII characters are a part of Unicode You can use the 'byte' type to work with 8 bit ASCII characters

Strings in Java are collections of characters. The String class provides a rich set of facilities for manipulating such objects. Some facilities for dealing with strings are built into Java. In particular, you can define a string constant by placing it in double quotes, and you can concatenate two strings by using the + operator. The following are some simple examples of string manipulations:

A string is a kind of collection of characters String constant syntax: "characters" To concatenate two strings; syntax: string + string

You can insert a variable (" + aVariable + ") between two constant strings

Note that aVariable above could contain anything. It will be converted into a string using a toString method. In the above example the toString method would be invoked on aVariable to generate an instance of String. It is good practice to write your own toString method in every class. It should return a string that will help identify each instance. The default implementation of toString outputs the name of the class followed by a hexadecimal code that distinguishes one instance from another.

Any object can be converted into a string using a 'toString' method The default implementation of the 'toString' method outputs the name of the class followed by a hexadecimal code that distinguishes the instance

The following two statements illustrate one of the many methods available to work with strings in Java. Note that as with arrays, the first character in a string is at index 0. For the substring operation, the first argument is the starting position, and the second argument is the ending position +1. The result is a new String with a sequence of characters from the original string.

  String sub = "submariner".substring(0,3);    // = "sub"
  String marine = "submariner".substring(3,9); // = "marine"

Collection classes and their iterators

We have seen how you can use arrays to create fixed-size collections of objects or primitive data. We have also seen how the class String provides collections of Characters. Java also provides a variety of other classes for working with collections of objects. Only the most important ones are shown below. you are invited to study the documentation to learn more about them.

(ArrayList, Vector, LinkedList) are subclasses of Collection classes Collection purpose: to build collections of objects that permit objects to be (added and removed) Vector is similar to ArrayList Vector is deprecated Deprecated means: that you should not use something because there is a better way LinkedList is similar to (ArrayList and Vector) except: it is more efficient for certain operations

Iterators

A common operation with collection classes is to do something with every member of the collection. Java provides an interface called Iterator to do this. To create an iterator, you simply use the methods called iterator or listIterator found in any collection class. These methods return a mysterious object called an Iterator. Its job is to understand the structure of the collection class and to be able to move from one element to the next - for all collections, the elements are actually ordered. Using this Iterator object you can repeatedly call the method next to obtain successive elements. The method hasNext enables you to find out if there are any more elements. The following example counts the number of empty strings in a collection of strings. We will discuss the notation '(String)' in the next section.

  emptyCount = 0;
  Iterator iter = aCollection.iterator();  // returns an Iterator object
  while(iter.hasNext())   // checks if there is a next
  {
    if(((String)iter.next()).length() == 0) //returns the next element
       emptyCount++;
  }

To do something with every member of a collection you use an iterator To create an iterator you use the methods ('iterator' and 'listIterator') that are found in any collection class ('iterator' and 'listIterator') create an object of the class iterator To move from one element of a collection to the next you call the 'next' method on the iterator; comment: the elements are actually ordered To get the first element of a collection you call the 'next' method on the iterator; comment: the first time 'next' gives the first; and then 'next' remembers its position To find out if there are any more elements you call the method 'hasNext' on the iterator

Iterators also have a remove method, that allows you to selectively delete elements of the underlying collection.

Wrappers

In some situations in Java, you want to operate on a primitive value as though it were an object. Java therefore provides a set of classes, called wrapper classes, corresponding to each of the primitive types. Each instance of these classes simply contains an instance variable of the corresponding primitive type.

The wrapper classes have many useful class methods such as the following:

  int i = Integer.parseInt(aString);     // converts aString to an int
  String s = Integer.toHexString(anInt); // converts to hexadecimal
  boolean b = Character.isDigit(aChar);  // tests if the character is a digit

Java has a set of 8 classes (called: wrapper classes) corresponding to each of the primitive types Each instance of a wrapper class contains an instance variable of the corresponding primitive type; example: an instance of Integer contains an int

The following are sample declarations:

  Integer anIntegerObject;
  Float aFloatObject;
  Double aDoubleObject;
  Byte aByteObject;
  Character aCharacterObject;
  Boolean aBooleanObject;

It is very easy to confuse instances of these classes with their primitive equivalents, so it is important to pay careful attention to where a primitive is required and where an object is required. When you work with instances of these classes, you cannot use the ordinary arithmetic or logical operators, instead you have to use methods. For example imagine you had two instances of class Integer, called integer1 and integer2. If you wanted to add them and store the result back into integer1, you would have to write the following rather inconvenient statement

   integer1 = new Integer(integer1.intValue() + integer2.intValue());

To add two instances of the Integer class; example:
integer1 = new Integer(integer1.intValue() + integer2.intValue())

Due to this complexity, and the inefficiency of the method calls, arithmetic in Java is normally done only using primitive values instead of instances of the wrapper classes.

Expressions

Expressions are formed using constants, variables, method calls and operators. They evaluate to a value, either a primitive value or an object.

There is a strict order of precedence that Java uses for evaluation of expressions. The precedence rules for the operators are described in Table 2.1. Operators at the top take precedence over operators lower in the table. At the same level of the table, operators are evaluated from left to right.

Expressions have as parts (constants, variables, method calls and operators); examples: 1, "abc", aVar, (3*x+1), y.aMethod Operators are evaluated in a strict order of precedence

Table 2.1: Precedence of the most important operators in Java.

Operators Comments
() [] Anything in parentheses, including array indexing, is evaluated first
++ -- ! Unary operators

* / % Multiplicative operators
+- Additive binary operatorsM
> >= < <= Relational comparison operators
== != Identity comparison operators
&& Logical AND
|| Logical OR
? : Ternary if-then-else, discussed below
= += *= -= /= Assigment

Special operators and operator precedence

Java, like C and C++, has some special operators that are widely used to shorten certain expressions. The most important of these are shown in Table 2.2.

Table 2.2: Special operators in Java

Operator Example expression Equivalent longer expression
++ postfix form a++;
b = a++;
a = a + 1;
b = a; a = a + 1
++ prefix form ++a;
b = ++a;
a = a + 1;
a = a + 1; b = a;
-- postfix form a--;
b = a--;
a = a - 1;
b = a; a = a - 1;
-- prefix form --a;
b = --a;
a = a - 1;
a = a - 1; b = a;
+= a += b; a = a + b;
*= a *= b; a = a * b;
-= a -= b; a = a - b;
/= a /= b; a = a / b;

Equality

The == operator, which returns a boolean, is used to compare any two primitive values which could be expression results, constants or the content of variables. The operator tests if the items are identical, which means they have the same primitive values. A common mistake is to use the identity operator == when the assignment = was meant, or vice versa. This bug will normally be caught by the compiler, but not if you are working with boolean items.

== is an instance of an operator; it returns a boolean; purpose: to compare any two primitive values; example: x == 4;

To test whether two variables contain objects that are equal (i.e. contain the same value, or state, but are not necessarily the same object), you call the equals method using an expression such as the following:

   boolean b = aPostalCode.equals(anotherPostalCode);

Here you would of course have to implement an equals method for PostalCodes.

Java Programs: Applets vs Applications

A Java program is a collection of classes that work together. It is started either by the operating system or a browser running it. Java programs can be compiled on any platform that has a Java compiler and run on any implementation of the Java Virtual Machine specification. A Java program is portable because it is compiled into a file containing bytecode that can run on any computer with a Java Virtual Machine. There are two kinds: applications and applets.

A Java program is a kind of collection of 1 or more classes that work together; it is started either by (the operating system or a browser or an applet viewer) A Java program has as parts 1 or more classes A Java programm can be compiled on any platform that has a Java compiler A Java program is portable because it is compiled into a file containing bytecode A file containing bytecode contains a Java compiled program A Java compiled program can run on any computer with a Java Virtual Machine There are two distinct kinds of Java programs: Java source programs, Java compiled programs There are two distinct kinds of Java programs: applications, applets Java applets are also called applets

An application is a Java program that runs stand alone rather than in a web browser. Each application must have one class that contains a main method which serves as the starting point for the rest of the program. To run a Java application in a command-line interface you type "java" followed by the class file name (without its extension) on the command line, for example "java HelloWorld". An application may have command-line arguments.

An application must have one class that contains a main method; purpose: to define a starting point for the application Main methods are a kind of method To run an application in a command line interface you type 'java' followed by the class file name without its extension; example: 'java HelloWorld' assuming HelloWorld has a main method. An application may have command-line arguments passed to it An application is a Java program that runs stand-alone rather than in a web browser

Applets

A Java applet is a Java program that adheres to certain conventions that allow it to run within the Java applet viewer or a Java-enabled browser such as Netscape or Internet Explorer.

A Java applet is kind of Java program that is intended to run within (a Java applet viewer or a Java-enabled browser) (Netscape and Internet Explorer) are kinds of Java-enabled browsers A Java-enabled browser is a kind of web browser that can run applets

Applets normally do not run stand alone and do not need a main method since they are to be run solely in a web browser. An applet can have a main method if it is to be run stand alone for the purpose of testing. An applet may be embedded into a web page using the <APPLET> tag.

An applet cannot read command-line arguments but it can have applet parameters which are passed from the HTML file that refers to the applet when the applet is loaded. For security reasons an applet cannot change the executing machine's environment.

Every applet is an instance of either Applet class, JApplet class or one of their subclasses. Currently most applets are usually written using Java 1.0 or Java 1.1 because most web browsers do not support later versions of Java. Here you must use Applet.

Applets (do not normally run stand-alone and do not need a main method); reason: they should be run solely in a web browser An applet can have a main method if it is to run stand-alone; purpose: testing An applet can be embedded into a web page using the <APPLET> tag An applet cannot read command-line arguments but it can have applet parameters which are passed from the HTML file that calls for the applet to (load and then run) an applet cannot change the executing machine's environment; reason: security Every applet is an instance of either (Applet class, JApplet class, or a subclass of these classes) Most applets are currently written using (Java 1.0 or Java 1.1); reason: most web browsers do not support later versions of Java applet example:
import java.awt.Graphics;
class HelloWorldApplet extends java.applet.Applet {
     public void paint(Graphics g) {
           g.drawString("HelloWorld!",5,25);
     }
}

Constructors and the creation of objects

Constructors are procedures that are called when a new object is to be created. Each constructor has the same name as the class, but can have different sets of arguments. The purpose of a constructor is to allocate heap space, initialize the instance variables of a newly created object, and perform any other needed initialization.

A new object is usually created by using the new operator in a variable declaration. The following gives an example:

   Account anAccount = new Account(holderName).

Constructors are a kind of procedure that is called when a new object is created Constructors are called by the 'new' keyword A constructor has the same name as its class A class may have many constructors with different signatures Constructor purpose: (to allocate heap space; to initialize the instance variables of a newly created object; to perform any other needed initialization) Constructors are often polymorphic Polymorphic means a method has the same name as another method and is distinguished by the types of the arguments A constructor can have 0 or more arguments constructor example:
public Account(String accountHolder, float initialBalance)
this.accountHolder = accountHolder;
    balance = initialBalance;
    opened = Calendar.getInstance();
}

The following are two constructors that might be used in a class Account. The first sets the balance to a specific initial value, whereas the second, lacking a second argument, sets the balance to zero.

public Account(String accountHolder, float initialBalance)
{   this.accountHolder = accountHolder;
    balance = initialBalance;
    opened = Calendar.getInstance();
}

public Account(String accountHolder)
{   this.accountHolder = accountHolder;
    balance = 0.0;
    opened = Calendar.getInstance();
}

Both of the above constructors initialize three instance variables. The value this represents the current object, in this case the object being created. It is being used here to distinguish between the instance variable accountholder and each constructor's argument of the same name. You normally use the new operator to create a new object. The exceptions are arrays created by literals eg{1, 2, 3} or strings created by string literals eg "abc". This operator sets aside memory for the object and calls a constructor.

You normally use the 'new' operator to create a new object; exception: An array can be created by a literal; example: int[] x = {1,2,3} and a string can be created by a literal; example: String x = "abc" The new operator purpose: allocates memory for the object and calls a constructor An object is created when control enters the block that contains its declaration

Here are examples of creating objects:

  String accountholder = "Tim";
  acct1 = new Account(accountholder, initialDeposit);
  acct2 = new Account(accountholder);

The constructor chosen is the one that has the same signature, ie argument types as the arguments that follow the new operator. Therefore, when acct1 is created, the first constructor (the one with a string and a float argument) would be called, whereas acct2 would be constructed using the second constructor. A constructormay have no arguments at all.

The constructor that is executed will have the same signature as the new statement that invokes it

It is important to remember that a constructor of class Account is called in the above statement. The particular constructor chosen will depend on the class (type) of holderName.

Alternatively, the declaration of the variable can leave it un-initialized – i.e. it is left to be initialized on a later line. A Java compiler should, however, warn you if your program can execute code that accesses un-initialized variables. Here is a variable declared without initialization:

  Account anAccount;
  ...
  anAccount = new Account(holderName, initialBalance);

An instance variable that is declared with any object type, but that is not yet initialized, has the special value null.

Casting

The block of code in a previous subsection illustrated an important issue. The next operation of an Iterator declares that it returns an Object, the class that is considered to be the ultimate superclass of all other classes. What this means is that when next is executed, the object returned can be of any Java class – it all depends on what was originally put into the underlying collection. However, if you put the result of next into a variable of type Object, you could only invoke those few operations defined in class Object. So you should use a mechanism called casting. Casting explicitly requests conversion between types.

To cast a variable or expression you precede it with the name of the resulting type, surrounded by parentheses, like this: (String)i.next(); or (int)4.5;. This statement is a bit like making a contract of the following form: "I, the programmer, know that the next method, in this particular case, is really going to return a String, even though next is declared to return type Object. So, trust me, compiler, and let me use the result as if it were a String. I agree to pay the consequences if I am wrong: an error will occur at run time." The type of error that occurs here is the raising of a ClassCastException    We discuss exceptions below.

Casting definition: a mechanism that explicitly requests conversion between types To cast an expression you precede it with the name of the resulting type, surrounded by parentheses; example: (int) 4.5

Exceptions

When something goes wrong in the execution of a program, such as an attempt to divide by zero, Java throws an exception. Throwing an exception means that instead of executing the next line of code, Java looks for some code to handle the exception and executes that instead. Java programmers are responsible for anticipating things that can go wrong and writing exception handling code in preparation. The try-catch construct provides the basic capability for this:

Java throws an exception when something goes wrong in the execution of a program; example: an attempt to divide by zero Java throws an exception means that: Java executes catch code to handle the exception; instead of: Java executes the next line of code An exception is a kind of object from (the Exception class or a subclass of the Exception class) You should (anticipate things that can go wrong and write try-catch code) Try-catch code is also called a try-catch block; comment: but it is really two or more separate blocks Try-catch code syntax:
    'try' tryBlock catch (exceptionArgument)
    catchBlock{1orMoreStatements};
    purpose: to handle an exception;
example:
try
{
    result = numerator / denominator;
    validResult = true;
}
catch (ArithmeticException e)
{
    validResult = false;
}

The throws statement

What happens if an exception is thrown in a statement that is not in a try block with an appropriate catch statement ? The answer is that Java will look to see if the caller of the current method is within a try block that has an appropriate catch block. It will continue to look at the chain of callers right up to the main program, and will finally report an error if it has not been able to find any suitable catch block.

If you are writing code in a class that could throw an exception, and you do not want to write a Try-catch block, but want to rely on the caller of the method to catch the exception, then you have to do something special: At the start of the method definition you have to declare that you are not handling certain exceptions by listing them in the following manner:

When an exception is thrown in a statement that is not in a try block that has try-catch code that can catch the exception then Java will check whether the caller of the current method is within a try block of try-catch code that can catch the exception if not then Java will check the chain of callers up to the main program for appropriate try-catch code if not then if Java has not been able to find any appropriate catch block then the system will finally report an error If there is code in a class that could throw an exception and you do not want to write try-catch code then you have to declare that you are not handling certain exceptions; how: use the throws clause; example:
int methodThatMayDivideByZero() throws ArithmeticException
{
   // code for the method that could throw the exception
}

Java provides many types of built-in exceptions. Each is, in fact, a class. When an exception is raised, an instance of that classis created that contains information about the problem causing the exception.

Java has many types of built-in exception classes When an exception is raised then an object of the class of the exception is created that contains information about the problem that caused the exception and then this object is passed to the catch block

Simple terminal I/O

Most serious programs interact with the user using graphical user interfaces. It is still useful, however, to know how to read and write information from the console (e.g. the Windows console or a Unix terminal). Java's basic terminal output statement is rather simple and takes the following form. Any String can be an argument to System.out.println, including strings constructed using the concatenation operator + described earlier.

  System.out.println("This line will be printed");

Most programs interact with the user using graphical user interfaces ( aka: GUIs) To write to the console you use the method 'System.out.println'. example: System.out.println("This line will be printed");

Java's mechanism for inputting what the user types at the console is less elegant. As the following code shows, you have to first create a byte array of sufficient size. You then call System.in.read, which waits for the user to hit a carriage return and then places what was typed into the byte array. Finally you have to convert this into a String, trimming off any whitespace that may have been unexpectedly added.

  byte[] buffer = new byte[1024];
  System.in.read(buffer);
  String theInput = new String(buffer).trim();

To read from the console you create a byte array to hold one line; call 'System.in.read' which (waits for the user to hit a carriage return and then places what was typed into the byte array); convert the data that was read into a String; trim off any whitespace that may have been unexpectedly added example:
byte[] buffer = new byte[1024];
System.in.read(buffer);
String theInput = new String(buffer).trim();

If you wanted to interpret the input as something other than a string, you could write statements like this:

  float afloat = Float.valueOf(theInput).floatValue();

In this example valueOf(theInput) is a class method of the class Float. It takes a string (theInput) and converts it to object of class Float. Then floatValue() returns the actual primitive float value of the float object.

We will leave it up to you to look up the necessary methods to convert to other data types.

Abstract methods and abstract classes

An abstract method is a method with no implementation, only a declaration of its signature. To create an abstract method in Java, you simply mark it abstract. You must not write any executable statements in the body of the method. the body is simply omitted. The method serves as a placeholder, indicating that subclasses must have actual (aka concrete) implementations. An abstract method must have overriding methods in all non-abstract subclasses with instances that call it.

An abstract method definition: a kind of method with no implementation; it has only a declaration of its signature; purpose: to serve as a requirement, indicating that subclasses must have actual implementations To create an abstract method you use the keyword 'abstract' An abstract method has no body An abstract method must have overriding methods in all concrete subclasses with instances that call that method Definition: a concrete method is a method that has a body aka: an implementation A concrete class definition a class that can have instances

An abstract class is a class that can only be subclassed - it cannot be instantiated or the compiler will display an error message and refuse to compile the program. The purpose of an abstract class is to hold features that will be inherited by two or more subclasses.

You declare a class to be abstract by specifying the abstract keyword on the first line when you declare the class. An abstract class can have concrete methods and member variables. Some or all of the implementation of its methods can be omitted. An abstract class is not required to have any abstract methods.

An abstract class definition: a kind of class that can only be subclassed; purpose: to hold declarations that will be inherited by two or more subclasses If you try to instantiate an abstract class then the Java compiler will display an error message You declare an abstract class by specifying the keyword 'abstract' for the class; syntax: 'abstract' 'class' className An abstract class can have (concrete methods and member variables) Some of the implementations of an abstract class's methods can be omitted An abstract class can have no abstract methods; comment: but this would defeat the purpose of an abstract class

More about methods

A method may have an array as a parameter. A method cannot itself be passed as an argument to a method or constructor, unlike in C and C++. A method must define its return type. A method returns a value that is of the return type of the method r a subtype of that type using the return statement. If the method has the return type "void" it does not need a return statement or it may have an empty return statement. A method should return to its caller from only one place which should be the last statement.

A method may have any type including interfaces as a parameter A method cannot be passed as an argument to a method or constructor unlike: (C and C++) A method must define its return type which may be 'void' If the return type (T) of a method is not void then the method must return a value that has type (T or a subtype of T); how: using the return statement If a method has the return type 'void' then it does not need a return statement or it may have an empty return statement A method should return from only one place which should be the last statement If a method has no return statement then it returns from the last statement executed

An accessor method is a method which returns or changes the state of an object, i.e. one or more of its instance variables. Accessor methods facilitate data abstraction. They should be provided if you anticipate that the detailed definition of a class may change because this will isolate the effects of potential changes.

An accessor method definition: a kind of method that (returns or changes) the state of an object The state of an object is defined by the values of its instance variables Accessor methods purpose: to facilitate data abstraction comment: They should be provided if you anticipate that the detailed definition of a class may change because this will isolate the effects of potential changes; They are considered good design practice

A deprecated method is a method that has been replaced by a different method in a later version of Java. If you are using the later version, do not use a deprecated method.

A deprecated method definition: a kind of method that has been replaced by a different method in a later version of Java; comment: If you are using the later version, do not use a deprecated method

A final method is a method that cannot be hidden or overridden. Its purpose is to increase efficiency (by simplifying optimizations) and to increase security (nobody can modify the method in a subclass).

A final method definition: a kind of method that cannot be (hidden and overridden); purpose: (to increase efficiency how: by simplifying optimizations and to increase security how: by not permitting anyone to modify the method in a subclass)

A recursive method is a method that calls itself. A recursive method works by calling itself to solve a subproblem until the subproblem is simple enough to solve without calling itself. Here is an example of a recursive method to calculate the nth power of 2:

A recursive method definition: a kind of method that calls itself A recursive method works how: by calling itself to solve a subproblem until the subproblem is simple enough to solve without calling itself recursive method example:
public static int recursivePowerOf2 (int n){
    if (n == 0) {
        return 1;
    }
    else {
        return 2 * recursivePowerOf2(n-1);
    }
}

Interfaces

An interface in Java is like a class except that it does not have any executable statements – it only contains abstract methods (both class and instance) and constants. It is a software module containing a description of a set of operations that certain classes must implement, hence it is essentially a requirement. An interface can extend one or more other interfaces from which it inherits constants and methods. Interfaces provide many of the same benefits of multiple inheritance, which Java does not have.

An interface differs from an ordinary abstract class in an important way: It cannot have any concrete methods or instance variables, whereas an abstract class can. The value of an interface is that it specifies a set of methods that a variety of different classes are to implement polymorphically. The classes that implement the interface do not have to be related to each other in any other way.

An interface is a kind of syntactic unit; purpose: to specify a set of methods that a variety of different classes must implement polymorphically; comment: if only one class implements a method there is no point in specifying it separately in an interface; is a kind of software module; can extend one or more other interfaces from which it can inherit (constants or methods); is like an abstract class; except: it cannot have any (concrete methods or instance variables) whereas an abstract class can have (concrete methods or instance variables); provides many of the same benefits as multiple inheritance; can capture similarities between unrelated classes without artificially forcing a class relationship; purpose: to declare methods that one or more classes are expected to implement; can specify an object's programming interface without specifying its class can be used as a type declaration for a variable Define behaviour means: define methods Behaviour of a class means: the set of methods the class provides API of a class is also called behaviour of a class Java does not have multiple inheritance; unlike: C++

A class uses an implements clause, as in the example below, to declare that it contains methods for each of the operations specified by an interface. In Java, a class can implement more than one interface, whereas it can only extend one superclass. As mentioned above, this is quite different from languages like C++.

To declare that a class implements an interface you use the 'implements' keyword
syntax: className 'implements' interfaceName;
A class can implement more than one interface but it can only extend one superclass; difference: this is quite different from languages like C++ that have multiple inheritance

You can declare a variable to have an interface as its type. This means that, using the variable, you can invoke any operation supported by the interface. Dynamic binding will occur so that the correct method is run.Of course a suitable implementation must exist. Dynamic binding is the capability to defer until runtime decisions about what class an object belongs to and the methods for accessing the object.

A variable can have an interface as its type If a variable has a type that is an interface then you can invoke any operation on it supported by the interface; comment: a suitable implementation for the operation must exist Dynamic binding definition: a kind of mechanism that makes decisions at runtime about what class a variable belongs to and hence the methods for accessing a variable; purpose: to provide programming flexibility; to ensure that the correct method is run Dynamic binding is one kind of the fundamental features of the object-oriented paradigm

For example, the following code specifies that any class can implement the Ownable interface. Furthermore a class that implements Ownable must provide concrete implementations for both of the operations. The code for the Ownable interface would be put in a separate file by that name, just like a class.

public class BankAccount implements Ownable
{
    ...
   public String getOwner()
   {
      return accountholder;
   }
   public void setOwner(String name)
   {
      accountholder = name;
   }
   ...
}
public class Pet extends Animal implements Ownable
{
   ...
   public String getOwner()
   {
      return owner;
   }
   public void setOwner(String name)
   {
      owner = name;
   }
}

Packages and importing

A package in Java is used to group together related classes into a subsystem. Each package is given a name composed of a series of words separated by dots. For example java.lang is one of the important packages of classes that is part of standard Java.

All the classes which belong in one package have to be put into a directory with the same name as the package. The components of a package name that come first correspond to higher-level directories. For example if you created a package called finance.banking.accounts, you would put that in a directory called accounts, which would be in a directory called banking, which would be in a directory called finance. The CLASSPATH variable would have to be set to point to the directory containing the finance directory. A further convention, not always adhered to, is to prepend to the package name the domain name of the organization, with the components inverted. So, for example if mcgrawhill.com owned the package finance.banking.accounts, then the full package name might be com.mcgrawhill.finance.banking.accounts. This assures that each package name is unique in the world.

A package purpose: to group together related classes Each package has a name composed of a series of words separated by dots; example: 'java.lang' 'java.lang' is one of the important packages that is part of standard Java All the classes in a package must be in a directory with the same name as the package The component names of a package name must correspond to a directory path; example: a package called finance.banking.accounts with a path = finance/banking/accounts The CLASSPATH variable must specify the remaining part of the path example: /a/usr/myhomedir

A file containing a class should always declare the package to which it belongs using the package keyword, thus:

   package finance.banking.accounts;

Note this corresponds to the directory structure holding the file.

If a class wants to use the facilities of another package, its file should contain an import statement, such as the following

   import finance.banking.accounts.*;

By importing a package, you are saying that all the code in that class file knows about the classes in the imported package – in other words you can refer to the classes in the imported package directly by name without specifying any directory. A package therefore defines what is often called a name space. The total name space of any class file includes the names in the file's own package plus the names in all imported packages.

A file that contains a class should always declare the package to which it belongs; how: by using the 'package' keyword at the beginning of the file; example: 'package finance.banking.accounts'; comment: this corresponds to the directory structure holding the file To use a package you use the 'import' statement example: import finance.banking.accounts If you use an import statement then you can refer to the classes in the imported package by name without specifying the package name If you do not use an import statement then you must refer to a class with the full package name A name space definition: a named area of code where a name has the same meaning; purpose: to permit a name to be used in another name space with a different meaning A name space can be defined by (a class or a package)

It is possible for two classes to have the same name as long as the names do not clash – i.e. the identically named classes are not in the same package – and their packages are never both imported into the same file. Despite this rule, however, it is a good idea to try to avoid giving two classes the same name, since somebody in the future might want to import both packages and hence create a name clash. If you ever do encounter a name clash, you can resolve it by qualifying the name of a class with the name of its package, for example, if there were two Account classes in the packages you were importing, you could write an expression like this :

  mybank.Account newAccount = new yourBank.Account(accountholder);

Encapsulation, Access control and Scope

By default, the methods and variables in a class can be accessed by methods in any class in the same package. This default rule is insufficient in two cases, however:

When you define any method, class, interface, instance variable or class variable, you can precede the definition with the keywords public, protected or private to control exactly what code can have access to the method or variable. Table 2.3 shows the effect of each of the keywords, starting with the least restrictive access and moving to the most restrictive.

When you control access so that parts of a program are invisible to other parts, you are practicing what is called encapsulation.

(any of method, class, interface, or variable) can have an access modifier keyword; purpose: to control exactly what code can have access to it 'public' is an instance of an access modifier keyword; purpose: to allow access from any code 'protected' is an instance of an access modifier keyword; purpose: to allow access only from (the class and subclasses) 'private' is an instance of an access modifier keyword; purpose: to allow access only from methods of the class default access is obtained by using no access modifier keyword If a syntactic unit has default access then it can be accessed by methods in any class in the same package Encapsulation definition: a kind of mechanism for hiding details of programs Encapsulation is one kind of the fundamental features of the object-oriented paradigm A class is used as the main unit of encapsulation.

It is good practice to restrict access to all syntactic units as much as possible. This is in line with the concept of information hiding: You want the details of the implementation of a class, class hierarchy or package to be hidden as much as possible from outsiders. This makes code easier to understand and change, and also tends to make designs more flexible. Restricting access reduces what we will call coupling, which is the amount of interconnection among various components of a system.

Some simple rules for access control are as follows: Make all instance variables as private as reasonably possible – almost never make them public. In addition, the only methods that should be public are those that will definitely need to be called from outside the package. Note that the keyword public is also applied to the declaration of classes. Unless a class is declared public, it is not available outside its package.

If you specify this keyword before the definition of a method, class, variable or interface Then code in the following places can call the method, or read and write the variable or use the class or interface
public Any code anywhere
protected Only code in the same package as this class as well as code in any subclasses, even if they are not in the same package
(nothing) = default Only code in the same package as this class; This is the default
private Only code in this class

Table 2.3: Effect of the access control keywords

Scope

The access control keywords described above help define the notion of scope in Java. In general, the scope of a variable or method is the parts of the source code in which reference to the variable or method can be made. The scope of an instance variable, instance method, class variable, class method, class or interface is defined by the public, private and protected keywords. Variables defined in blocks (defined by curly brackets '{' and '}'), including embedded blocks or the bodies of methods, try-catch clauses, etc. have the start and end of the block as their scope.

There are 4 kinds of scoping unit: blocks, methods, classes and interfaces The scope of a scoping unit definition: the parts of the source code in which reference to the declarations of that scoping unit can be made Scoping unit purpose: to permit a part of a program to use a set of declarations of (a block, a class, a method, an interface or a variable) The scope of a scoping unit is controlled by the access modifier keywords A local variable definition: is a variable declared (as a formal parameter or in a method body or in a nested block) The scope of a local variable that is declared in a block B is B The scope of a formal parameter is the body of the method of the parameter The scope of a (class or instance variable) is defined by its access modifier keyword A name space is similar to a scope; difference: scopes cannot be named; scopes can be nested; namespaces can be explicitly specified

Threads and Concurrency in Java

A thread is a sequence of executing statements that can be running, conceptually at least, at the same time as another thread. Several threads are said to execute concurrently. The main method is a thread that runs concurrently with any other threads.

Threads are supported by many operating systems and programming languages, and their effects are visible in many application programs. For example, when you are using a word processor, you may notice that at the same time as you are typing text, the system is recalculating where to place the end of the pages. In a complex spreadsheet, at the same time as you are editing cells, the program is calculating other cells that have been affected by earlier changes you made.

A thread definition: a kind of sequence of executing statements that can be running at the same time as another thread Threads can execute concurrently Threads are supported by many (operating systems and programming languages) Java supports thread on all platforms

To create a thread in Java, do the following:

  1. Create a class to contain the code that will control the thread. This is made to implement the interface Runnable. (It can also be make a subclass of Thread instead, but implementing Runnable is by far the preferred approach.)
  2. Write a method called run in your class. When the thread is started, this run method executes, concurrently with any other thread in the system, which includes the main. When the run method ends, the thread terminates. The run method acts like the 'main program' of the thread.
  3. Create an instance of Thread (or your subclass of Thread ) and invoke the start operation on this instance. If you implemented the interface Runnable in a class, you have to pass an instance of this class to the constructor of Thread, as is shown in the example below.

To create a thread in Java you: create a class C that must implement the interface 'Runnable'; purpose: to contain the code (= the run() method) that will control the thread ; create an instance T of (the class 'Thread' or a subclass of 'Thread') with an instance of C passed to the constructor; call start() on C to begin the run() method) When a thread is started, its run method executes concurrently with any other thread in the system The main method runs concurrently with any threads When the run method of a thread ends, the thread terminates The run method is similar to the main program of a class A run method can access all (classes and methods) that are visible to the thread

The third step above will differ slightly depending on what you did in step 1. If you implemented the Runnable interface, then pass your instance to a new instance of Thread. If you directly subclassed Thread, you can simply start your instance.

The following is a complete program that illustrates how threads work. The program starts three concurrent threads, each of which prints out a record of its progress. Since the threads are running concurrently, the output from the different threads is interleaved.

Take note of the following lines of code:

1. public class ThreadExample implements Runnable
2. {
3.   private int counterNumber; // Identifies the thread
4.   private int counter; // How far the thread has executed
5.   private int limit; // Where counter will stop
6.   private long delay; // Pause in execution of thread in millisecs
7.   // Constructor
8.   private ThreadExample(int countTo, int number, long delay)
9.   {
10.    counter = 0;
11.    limit = countTo;
12.    counterNumber = number;
13.    this.delay = delay;
14.  }
15.  //The run method; when this finishes, the thread terminates
16.  public void run()
17.  {
18.    try
19.    {
20.      while (counter <= limit)
21.      {
22.        System.out.println("Counter "
23.           + counterNumber + " is now at " + counter++);
24.        Thread.sleep(delay);
25.      }
26.    }
27.    catch(InterruptedException e) {}
28.  }
29.  // The main method: Executed when the program is started
30.  public static void main(String[] args)
31.  {
32.    //Create 3 threads and run them
33.    Thread firstThread = new Thread(new ThreadExample(5, 1, 66));
34.    Thread secondThread = new Thread(new ThreadExample(5, 2, 45));
35.    Thread thirdThread = new Thread(new ThreadExample(5, 3, 80));
36.
37.    firstThread.start();
38.    secondThread.start();
39.    thirdThread.start();
40.  }
41.}