Session 2 Lecture Notes for First Course in Java

Chapter 2: An Overview of Java
course homepage      course calendar

24 March 2003

This lecture covers the reading in Chapter 2: An Overview of Java

Object-oriented programming
  • Encapsulation
  • Inheritance
  • Polymorphism
Statements and expressions

Declarations and assignments

Sample programs

Control statements

  • if
  • for
Code blocks

Language tokens

Built-in methods (libraries)
Quiz

Homework Assignment


Object-Oriented Programming

Sun's tutorial on object-oriented programming concepts: http://java.sun.com/docs/books/tutorial/java/concepts/index.html

[A good, easy-to-read introductory book with many diagrams: Object Technology: A Manager's Guide by David Taylor.  http://www.bookpool.com/.x/49jdnnq9t0/sm/0201309947 ]

Procedural languages, such as C, center around code, and what the code does. To write procedurally, you have to think like a computer.

Object-oriented languages, such as Java, center around objects, which is more like how human beings understand the world. For example, you can model your program on how you model your business, with objects such as Customer, Salesperson, Product, Order, Account. Objects are at a higher level than routines. Objects involve the abstraction of details. You design an object-oriented system by thinking about self-enclosed, discrete entities (objects) that send messages to each other.

[Note: Some Java applications serve a business workflow based on a business model of business objects. Corresponding to each business object (Customer, Salesperson, Order) can be a database table, which in  term corresponds to a Java object that contains the business logic for that business object. In such a scenario, a database field (table column), such as Name or ZipCode can correspond to an object attribute or property.]

The three key concepts of object-oriented programming are:

Encapsulation

Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far too small for you to see is the structure of the compound or molecule that does work in your bloodstream or organs to cure your disease. You don't even see the components of the mixture, which might be white medicine mixed with, say, green flour. The complexity is hidden from you. Your orders are simple and external to the encapsulation: take one green pill each day with water.

Encapsulation is like a black box. When you purchase a television set, you do not need to know the details of the electronics inside (raster-scanning cathode ray tube with magnetic electron gun, alternating current transformer, hundreds of capacitors, thousands of transistors). Instead, you only need to know how to plug in the UNIT, attach the cable, turn the on switch, and press buttons on the remote control. You have a UNIT that sends visual and audio messages to you, and you do not care about the hidden actions within the unit.

In Quality Assurance, the phrase "black box testing" means observing the behavior of the unit from outside, without having access to the internal source code.

(Philosophically speaking, even if we say we "know" a person, we do not know the details that are internal to that person, only the messages that the self-encapsulated "person unit" makes accessible or public in some way, such as through words or deeds. Even within the electronics of our own nervous system, an encapsulated program regulates our heartbeat without our conscious control. The messaging between brain and heart is hidden from us.)

A class has methods and attributes 

In Java, the unit of encapsulation is the class. Each object is an instance of a class. The class is a template for making objects. The class is similar to a cookie cutter, or a mold, for making things of a certain shape, things with certain attributes. If I define a class called dog, it might have an attribute for number of legs, which might be set to four:

int numberOfLegs = 4; 
(When I go to the pet store to buy a dog, I do not purchase the class of Dog. Rather, I purchase an instance (an embodiment) of the class Dog. 
I purchase Fido or Rover or Lassie or another actual dog to whom I might have not yet have assigned a name.)

Back to class of Dog (that is, to dogs in general).
Unless I only want a statue of a dog, I want the dog to be able to do things.
The dog class might have an action (or behavior, or method) for wagging its tail, which we can call the wagTail() method, and another action for bringing me the morning newspaper, the fetchPaper() method, or the barkAtStranger() method, or the eatFoodQuickly() method that distinguishes the class Dog from the class Cat..

I do not care about the bio-electro-chemistry that makes the tail muscles contract and produce tail wagging. I just want to see my dog happy, tail a-wagging.
I do not care about the intricate machinery in the dog's nose that enables the dog's identifyBySent() method. I just want my dog to recognize me at night, even in darkness, which my dog might do by using an acute sense of smell.

Encapsulation supports re-use of code (or patterns)

Encapsulation simplifies things for whatever communicates with the encapsulated object. The internals can change without affecting the overall behavior. For example, the interface to a piano is a set of piano keys and three pedals. Behind the scenes, inside the black box of the piano, are sophisticated mechanical hammers, springs, and strings. If you can play a cheap, honky-tonk, out-of-tune piano, you can also play the world's most expensive Steinway concert piano, and without having to understand Steinway's patented hammer action. Indeed, I can then also play an electric or electronic piano (or even a vibraphone or a xylophone), which might be a unit that encapsulates different methods than hammers striking strings, yet offer me the same user interface of a set of PianoKey objects. I can re-use my code that tracks the notes of scale, no matter which keyboard instrument I play.

Where is the messaging in this piano metaphor?

  1. The PianoKey object,
  2. upon the event of being pressed,
         event = PianoKey.keyPressed(middleCkey);
  3. sends a message to the Hammer object,
         message = PianoKey.prepareToHitString(middleCString);
  4. which in turn sends a message to the String object
         message = Hammer.bangOnString(middleCString);
  5. and the String object sends a message to the PianoPlayer object
         sound = middleCString.Ouch();

Inheritance

Inheritance enacts the reuse of code. For example, now that I have a messaging system for the middle C key, I can reuse that logic for all 88 keys on the piano. Each key can inherit attributes (properties) and behavior (methods) from the String object, the template or mold for all strings.

When you design a more complicated system, your class hierarchy will have more levels. For example, if you were designing a library catalog, you might layers such as these:

LibraryObject

LoanObject vs ReferenceObject

Periodical vs Book vs AudioTape vs VideoTape vs DVD

DailyPeriodical vs MonthlyPeriodical

ForeignLanguageMonthlyPeriodical vs EnglishMonthlyPeriodical

AsianLanguageMonthlyPeriodical vs EuropeanLanguageMonthlyPeriodical

JapaneseMonthlyPeriodical vs ChineseMonthlyPeriodical

All the objects in the hierarchy inherit a characteristic from the LibraryObject, that is, belonging to the library.

All the objects for loan, unlike the reference objects, can be "checked out" to customers.

All the periodicals, unlike books and such, are published on a recurring basis.

Therefore, whatever object is a member of the JapaneseMonthlyPeriodical class, will automatically inherit the logic common to LoanObject, that is, the ability to be "checked out". I do not have to rewrite the logic for the procedure of checking out a JapaneseMonthlyPeriodical and make it different from the procedure for checking out a EuropeanLanguageMonthlyPeriodical. It is like inheriting money or kingship: I do not have to do work to get the money or the crown.

Polymorphism

However, it might WANT to over-ride what an object inherits. For example, I might want the checkout period for AsianLanguageMonthlyPeriodical to be shorter or longer than for EuropeanLanguageMonthlyPeriodical. In other words, I might want to have different styles or forms of checkout rules. The ability to have many (poly) forms (morphs) is called polymorphism.

Suppose you have a class hierarchy involving three classes, Circle, Square, and Rectangle, which all inherit the calculateArea() method from the Shape interface. Polymorphism in the sense of an interface enforces that each class implementation has a calculateArea() method, but allows each implementation class redefine the required method to fit the shape. For example,

class Circle implements Shape  {
   public double calculateArea()   {
      circleArea = pi * radius * radius;
      return circleArea;
   }
}

class Triangle implements Shape  {
   public double calculateArea()   {
      triangleArea = base * (height/2);
      return triangleArea;
   }
}

Another case of polymorphism could be in banking. Suppose that my bank allows me to open two kinds of accounts: a standard account that only requires a minimum balance of one cent (but charges service fees), or a deluxe account requires a minimum of one thousand dollars (and provide services without fee). Therefore, the openAccount() method has two forms.

if (deposit => standardMinimum | deposit <=deluxeMinum)
{
     StandardAccount.openAccount();
}
else
{
     deluxeAccount.openAccount();
}

[Sneak Peek to a more detailed introduction to Object-Oriented Programming (OOP) and two sample programs with a simple class called Box]


Statements and Expressions

Statements

A statement is a command that you write in your program.
A statement must end with a semicolon (;) so that the parser in the Java compiler (javac) knows you end this point to be the end of your statement.

System.out.println("Hello Luke"); // pass a string argument to a method
double bodyTemperature = 98.6;  // assign a value to a primitive variable
HumanBeing.inalienableRight = pursuitOfHappiness;  // assign a value to a property of an object

Comments

Comments are for human code readers. The compiler ignores comments.
Insert comments in your code that you, and others who will use your code, know what the code is about.
It is more common for code to have too few comments than too many comments.

In the preceding statements, a comment follows each statement. 
Two slash characters (//) define the comment through the end of the current line.

/* A slash followed by an asterisk
defined the beginning of a multi-line comment,
which ends with the reverse, an asterisk, followed by a slash */ 

Expressions

An expression is a statement that returns a value. 
In both examples below, the Java virtual machine will:

  1. Perform a calculation or an evaluation.
  2. Return a return value.
sum = priceOfItem1 + priceOfItem2; // the return value is stored in the variable sum
selfEvidentTruth = HumanBeing.IsCreatedEqual();  // boolean return value must be true or false

Declarations and Assignments

A declaration is a statement that lets the compiler know that we are going to use a variable to refer to a value of a certain type.

An assignment gives (assigns) a value to a variable. Typically, in Java, we assign a value to a variable when we declare that variable.

For example,

int temperature = 70; // Fahrenheit
float drunk = .01; // in percent
final int BOILING_POINT = 212; // a constant
// We will learn about arrays in detail later.
// What follows is an array of characters 
// for the 7 days of the week.
// (Single quotes are for chars.)
// Each element has a unique index. 
// The first 's' (Sunday) has the index of zero.
// The second 's' (Saturday) has the index of 6.

char[] daysOfTheWeek = {'s', 'm', 't', 'w', 't', 'f', 's'};
// Use double quotes for strings.
String[] myDays = {"Sunday", "Monday", "Tuesday"};


Sample Programs

If there is no class that matches your classfile name, you get an exception.
D:\java\teachjava\spring2003\session1>java BadName
Exception in thread "main" java.lang.NoClassDefFoundError: BadName

/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
   // Your program begins with a call to main().
   public static void main(String args[]) {
      System.out.println("This is a simple Java program.");
      }
}

Enclose multi-line comments inside /*      */
Put single-line comments after //

//This is a wordy Java program.
//Call this file "Wordy.java".
class Wordy {
// Your program begins with a call to main().
public static void main(String args[]) {
   int year = 2003;
   System.out.println("This is a wordy Java program.");
   System.out.println("This program uses the following:");
   System.out.println("public static void main(String args[]) {");
   System.out.println("The keyword public means this class is available for calls from outside the class.");
   System.out.println("The keyword static means no class is initiated,"
      + "\nwhich is good because I do not have a class to initiate.");
   System.out.println("The keyword void means this class does not return a value.");
   System.out.println("The keyword String means that args[] is of type String.");
   System.out.println("The variable name args[] refers to an array"
      + "\nbecause some programs take command line arguments.");
   System.out.println("The print method prints to the screen without a new line.");
   System.out.print("So the year value will appear on THIS line: ");
   System.out.print(year);
   }
}
To assign a value to a variable, use the equal (=) operator.
class Assignment {
   public static void main(String args[]) {
      int x, y; // variable declarations

      x = 100; // this assigns x the value 100
      y = 10;

      System.out.println("The value of x is: " + x);
      System.out.println("The value of y is: " + y);
      System.out.println("The product of x and y is: " + x*y);
      System.out.println("The dividend of x / y is: " + x/y);
      }
}
Can you find the bug?
// INTENTIONALLY UNCOMPILABLE!
class HelloWorldApp2 {
   public static void main(String[] args) {
   System.out.println("Hello World!); //Display the string.
   }
}

Control statements

if statement

The most basic control statement is the if test. The syntax is involves a check for a Boolean true:

if(condition) statement;

The output is:

The length of the string is: 30
The string does not have 5 letters

Let us discuss:

What is the difference between (a) and (b)?

(a)
  if (isLeapYear == true)
(b)
  if (isLeapYear)
Answer: (a) is redundant. It is better to write (b).

for loop

Loops allow you to take advantage of a strength of the computer, speed.

The most common loop is a for loop. The syntax is:

 for (initialization; condition; increment) statement;

Example:

public class MyForLoop {
	public static void main(String[] args) {
		int sum = 0;
		for (int i = 1; i <= 5; i++) {
		System.out.println("This is iteration " + i);
		System.out.println("This value of sum is now " + sum);
		sum += i;
		System.out.println("The value of i is now " + i);
		System.out.println("The value of sum is now " + sum + "\n");
		}
	}
}

The output is:

This is iteration 1
This value of sum is now 0
The value of i is now 1
The value of sum is now 1

This is iteration 2
This value of sum is now 1
The value of i is now 2
The value of sum is now 3

This is iteration 3
This value of sum is now 3
The value of i is now 3
The value of sum is now 6

This is iteration 4
This value of sum is now 6
The value of i is now 4
The value of sum is now 10

This is iteration 5
This value of sum is now 10
The value of i is now 5
The value of sum is now 15

Notes:

Code blocks

Think of a code block as a unit of code. Just as an English sentence can have many clauses and commas, but still be a single unit (the sentence), so many lines of code can belong to a single code block. A class definition resides a code block. We have seen how within a class definition code block, we can have code blocks for a for loop. An if statement can also have multiple statements within its code block.

if (s.length() > s2.length()  { // if true, execute both statements in the block
    System.out.println("s is longer than s2.");
    System.out.println("s2 is shorter than s.");
}

Tip: When you begin a code block, type both the beginning curly brace and the ending curly brace before you fill in the block with code. That way you will not forget to close your code block.

Note: The "scope" of a variable is defined by the code block in which it resides.

Language tokens

Parsing

When you invoke the javac compiler, it parses the tokens in your source code. The parser ignores the contents of comments as well as white space. Therefore, the following are the same:

When you name identifiers (variables, methods, classes), the characters must be contiguous (no spaces), cannot start with a numeral, and cannot include operators.

Separators

CHARACTER NAME USE
;
semicolon to end a statement
.
dot operator to separate an object from one of its methods
( )
parenthesis to contain a list of parameters for a method;
to contain the condition in a control statement
{ }
curly braces to define a block of code
[ ]
brackets to declare an array

Key words and reserved words

You cannot use the following as identifiers in your code.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

true false null  
abstract double int strictfp **
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto * protected transient
const * if public try
continue implements return void
default import short volatile
do instanceof static while

Built-in methods (libraries)

Documentation on the 1.4 APIs: http://java.sun.com/j2se/1.4.1/docs/api/index.html

The Java software development kit comes with many built-in methods. This Java environment includes these methods to support major types of functionality, such as security, XML, networking, and input and output. Having a rich set of pre-built methods saves you time. Here's an example.

/* This program uses API introduced in 1.1.
   It tells you the language version of your Java.
   In my case, in United States English: en_US */

public class Useless {
   public static void main(String[] args) {
   System.out.println(java.util.Locale.getDefault());
   }
}

Earlier, we saw that the String object has a method, length(),  for getting the length (number of characters) in the string.

The Java platform offers predefined formatting for numbers: http://java.sun.com/docs/books/tutorial/java/data/numberFormat.html

Let's now take a tour of the API documentation: http://java.sun.com/j2se/1.4.1/docs/api/index.html


Quiz

  1. Name the three concepts (or buzzwords) in object-oriented programming?
  2. A Java class is the unit of which major feature of object-oriented programming?
  3. True or False: A class is an instance of an object?
  4. What are the "reserved words" in the HelloWorld program?
  5. List two types of control statements.
  6. Which aspect of OOP is hierarchical?
  7. Which aspect of OOP specializes an object, making it unique among the member of it class?
  8. Which aspect of OOP "hides" data and behavior?
  9. True of False: the main() method is a "property" of every Java application?
  10. Match the word with the correct definition:

    (6.1) block
    (6.2) parse
    (6.3) compile
    (6.4) comment

    (a) to process the syntax of tokens in source code
    (b) to convert source code to byte code
    (c) the section of code to treat as a single statement, even if it has multiple lines
    (d) the part of the source code that does not become byte code
     

Homework

The example that follows this table of arithmetic operators uses the modulus operator (%).

Operator Name Use Description
+ addition op1 + op2 Adds op1 and op2
- subtraction op1 - op2 Subtracts op2 from op1
* multiplication op1 * op2 Multiplies op1 by op2
/ division op1 / op2 Divides op1 by op2
% modulus op1 % op2 Computes the remainder of dividing op1 by op2

The program finds the integers between 1 and 100 that are a multiple of 13.

public class Check13Backwards {
    public static void main(String[] args) {
        int num = 100;
        for (int i = 100; i > 0; i--) {
            if (num % 13 == 0)
            System.out.println(num + " is a multiple of 13");
            num--;
        }
    }
}

Note that I decrement instead of increment by use -- instead of ++.

The output is:

91 is a multiple of 13
78 is a multiple of 13
65 is a multiple of 13
52 is a multiple of 13
39 is a multiple of 13
26 is a multiple of 13
13 is a multiple of 13

Your homework is to write a program that has an if statement inside of a for loop, or a for loop inside of an if statement.

________________________
course homepage      course calendar