Professional Documents
Culture Documents
Course Objectives
Upon completing this course you should be able to:
Describe the three main OOP concepts. Differentiate between is a and has a Relationships Use Java standards for coding. Describe Java environment and how it works. Write java programs. Create packages and document them Create classes and interfaces. Create and manage a hierarchy of classes and interfaces Create objects out of classes. Use Java I/O capabilities. Connect to a database using JDBC Use Java API
Course Organization
Part 1: OOP Model Part 2: Java Basics Part 3: Java implementation of OOP Model Part 4: Java OOP Design Issues Part 5: Introduction to Java API
Java I/O Java JDBC
Part 1
OOP Model
Introduction To OOP
Philosophy:
Abstraction Growth:
Machine Language Assembly Language Non-procedural Languages (BASIC) Procedural Languages (C, Pascal) OOP languages (C++, Java)
OOP model is to eliminate the mapping from the problem space to solution space as possible.
Objects
Objects attributes and behaviors are encapsulated together a data type. Objects have a lifecycle:
Objects Interfaces
An object has to have an interface. The interface will
Provide a way to let other objects to communicate with it. Hide the details of the object implementation.
Implementation Hiding
Breaks up the playing field into:
Class creators (those who create new data types) Client programmers (those who use these types for their own tasks. They only deal with the interfaces.)
The goal of the class creator is to build a class that exposes only whats necessary to the client programmer and keeps everything else hidden. Two reasons for controlling the access:
To keep client programmers hands off portions they shouldnt touch. To allow the library designer to change the internal workings of the class without worrying about how it will affect the client programmer.
Implementation Reuse:
Software reusability is not so easy to achieve as many would hope; it takes experience and insight to produce a good design. OOP provides ways for reuse:
Composition: Inheritance(Reusing the interface)
Polymorphism
Allows you to make the derived types behave differently from their base types. It uses late binding instead of early binding Example:
Bird Move() Goose Move() Penguin Move()
Part 2
Java Basics
History of C++
First there was C. C initially became widely known as the development language of UNIX OS. C++ evolved as an extension to C. It mainly provides the capabilities of Object-Oriented Programming to C world. C++ is a hybrid language. Both C-like style and object-oriented style can be developed using it.
History of Java
Java first was developed in 1991 by James Gosling at Sun Microsystems to be used with interactive TV technology which had failed to find a market. When The World-Wide Web became popular in 1995 , Java came to life again. Java is now considered as the native language of the Internet. Java is a C/C++ based language. Java is a Full object-oriented language
Java Environment
Draft .java file .class File Byte code on RAM Verified Byte code Editor Compiler Class Loader Byte code Verifier .java file .class File Byte code on RAM Verified Byte code
Interpreter
Program skeleton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//the skeleton of a java application package packagename; import packagename.ClassName; public class ProgramName { // Define program variables here. . . . // Define program methods here. . . . //Define the main method here.
Notes
Java
is a case sensitive language Braces must occur on matching pairs Coding styles should be followed.
Comment Styles
Comments are used to clear the logic of the code and to increase the readability if it. Comments are ignored by the compiler. Java uses three types of comments:
Single-line comment(//). Example: //single-line comment here Multiple-line comment(/**/). Example: /* line 1 here line 2 here */ Documentation comment(/***/). It is multiple-line and used with javadoc utility to create application documentation.
A string is a group of characters We use class String to define a string. Example: String name; Strings are bounded by double quotations. Example: String name = Jane; We can concatenate two or more strings using the operator + Strings can contain escape characters like \n, \t, \\, \.
Variables Definition
Variables are used to represent the data that a program deals with As the name might imply, the data that a variable holds can change. We have to define a variable before using it Here is an example of defining a variable: int number; String name;
-32,768 32,767
-2,147,483,648 - +2,147,483,647 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 -3.40292347E+38 - -+3.40292347E+38 -1.79769313486231570E+308 to +1.79769313486231570E+308
Arithmetic Operations
Operation
Addition
Operator
Java Expression
Subtraction
Multiplication
Division
Modulus
+ * / %
a + 8
b - 7
p * 10
c / 9
b % 6
Operator
Java Expression
if (x == 1) if (y != 5) while (x > y) while (x < y) if (X >= y) if ( y <= z)
Assignment Operators
Operator = += -= *= /= %= Expression c = 5; a += 10 ; a -= b; c *= 13; a /= b; b %= c ; Equivalent to c = 5 a = a + 10; a = a b; c = c * 13; a = a/b; b = b% c;
Equivalent to
Count = count + 1; Count = count - 1;
++ --
Logical Operators
|| (logical OR)
Returns true if either of its conditions are true
Precedence
Operator
( )
Associativity
From left to right
High
++
* + < == & ^ | && || ?: = += <= /
-% > >= !=
-=
*=
/=
Low
implements import
instanceof int
protected public
If if/else structures
if statement looks like: if (condition) { } Conditions are evaluated to either true or false
switch statements
Useful to test a variable for different values switch ( value ){ case '1': actions case '2': actions default: actions } break; causes exit from structure
While Structure
If multiple statements needed, enclose in braces Control variable only exists in body of for structure If loopContinuationTest is initially false, body not executed
Methods
Methods
Modularize a program All variables declared inside methods are local variables
Known only in method defined
Parameters
Communicate information between methods Local variables
Benefits
Divide and conquer
Manageable program development
Software reusability
Existing methods are building blocks for new programs Abstraction - hide internal details (library methods)
Method Definitions
Method-name: any valid identifier Return-value-type: data type of the result (default int)
void - method returns nothing Can return at most one value
return Statement
Returning control
If nothing returned: return;
Or until reaches right brace
Calling methods
Three ways
Method name and arguments
Can be used by methods of same class square( 2 );
Coercion of arguments
Promotion rules
Specify how types can be converted without losing data If data will be lost (i.e. double to int), explicit cast must be used If y is a double,
square( (int) y );
Duration of Identifiers
Exist in block they are declared When block becomes inactive, they are destroyed
Static duration
Created when defined Exist until program ends Does not mean can be referenced/used anywhere
Scope
Where identifier can be referenced Local variable declared in block can only be used in that block
Class scope
Begins at opening brace, ends at closing brace of class Methods and instance variables
Can be accessed by any method in class
Block scope
Begins at identifier's declaration, ends at terminating brace Local variables and parameters of methods
When nested blocks, need unique identifier names
Method scope
For labels (used with break and continue) Only visible in method it is used
Method Overloading
Method overloading
Methods with same name and different parameters Overloaded methods should perform similar tasks
Method to square ints and method to square doubles
public int square( int x ) { return x * x; } public float square( double x ) { return x * x; }
Arrays
Array
Group of consecutive memory locations
Array name Position number Format: arrayname[position number] First element at position 0
Declaring/Allocating Arrays
Declaring arrays
Specify type, use new operator
Allocate number of elements Place brackets after name in declaration
Two steps:
int c[]; //declaration c = new int[ 12 ]; //allocation
One step:
int c[] = new int[ 12 ];
Primitive elements are initialized to zero or false while Non-primitive references are initialized to null
Passing arrays
Multiple-Subscripted Arrays
Represent tables
Arranged by m rows and n columns (m by n array) Can have more than two subscripts
Array of arrays
Fixed rows and columns
arrayType arrayName[][] = new arrayType[ numRows ][numColumns ]; int b[][] = new int[ 3 ][ 3 ];
Initializer lists
arrayType arrayName[][] = { {row1 sub-list}, {row2 sub-list}, ... }; int b[][] = { { 1, 2 }, { 3, 4 } };
Java Applets
Java applets are programs that run on a java enabled browser. Java applets do not have main methods. To compile your program, use command: c:\> javac MyAppletName.java To run your program, use command: c:\> appletviewer my_html.html Applet Developint Process:
Step 1: Write the applet program Step 2: compile .java file and get .class file Step 3: create HTML file Step 4: test the applet using appletviewer Step 5: Publish the applet
Applets can use almost all java API capabilities. Applets have a great graphical capabilities. Applets can play sounds. Applets make the web page extremely interactive Applets can usually make network connections to the host they came from. Applets can interact with other applets on the same page.
An applet cannot load libraries or define native methods. It cannot read or write files on the host that's executing it. It cannot make network connections except to the host that it came from. It cannot start any program on the host that's executing it. It cannot read certain system properties. Windows that an applet brings up look different than windows that an application brings up.
Part 3
Introduction
Java OOP is build on the single rooted hierarchy which means that all classes should be inherited from a single base class. In Java the name of this ultimate base class is simply Object. A class in Java represent a data type that Encapsulates data (attributes) and methods (behaviors) that are closely related. The class is the unit of Java programming.
Packages
Directory structures that organize classes and interfaces Mechanism for software reuse
Creating packages
Create a public class
If not public, can only be used by classes in same package
Choose a package name and add a package statement to source code file Compile class (placed into appropriate directory) Use Java standards in naming the packages.
import
Use import when classes are not of same package. If no package specified for a class, it is put in the default package which includes compiled classes of the current directory If class in same package as another, import not required
Create a directory called classes inside directory c:\jdk1.2\jre\ Use the following command for compilation:
javac d c:\jdk1.2\jre\classes MyClasse.java
Once the package has been created you can use import statement to use its classes.
A class in Java is just a blueprint telling what the objects created from it will look and act like. Every class in Java is a subclass of the ultimate base class Object Every Class has three components:
Instance variables (Class Attributes). Member methods (Class Behavior) Constructors. ( For initialization and consistency)
Class Declarations
Class Constructors
All Java classes have constructors that are used to initialize a new object of that type. A constructor has the same name as the class. Example
public Stack() { items = new Vector(10); }
Java supports name overloading for constructors so that a class can have any number of constructors. Example:
public Stack(int initialSize) { items = new Vector(initialSize); }
The compiler differentiates these constructors based on the number of parameters in the list and their types. Constructors cannot return values. There is no return type, not even void.
Member variables represent the state of the object. They should be initialized in some way when creating the object to make sure that the object is in a consistent state. We use modifiers when declaring Member variables.
Method Declaration
Methods are the ways through which objects communicate with each other A method's declaration provides a lot of information about the method to the compiler, to the runtime system, and to other classes and objects We use modifiers when declaring Methods.
Methods Overriding
Overriding a method in a subclass means rewriting or modifying its code so that it acts differently from what it used to. Method overriding is related to a very important feature of OOP known as polymorphism Example: Overriding methods init() or paint() in applets.
The Object class defines and implements behavior that every class in the Java system needs. The following will be the hierarchy that every class in Java will end up part of.
Overriding Methods
The ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then supplement or modify the behavior of that superclass.
A Subclass is more specific than a superclass Every subclass can be described by its superclass, but not vice-versa Unlike C++, Java does not support multiple inheritance. To inherit from a class use keyword extends
class TwoDimensionalShape extends Shape { ... }
The Object class sits at the top of the class hierarchy tree in the Java platform. This class defines the basic state and behavior that all objects must have. Your classes may want to override the following Object methods:
clone - equals/hashCode - finalize toString
The clone Method:You use the clone method to create an object from an existing object. The finalize Method: The Object class provides a method, finalize, that cleans up an object before it is garbage collected. The toString Method: Object's toString method returns a String representation of the object. The getClass Method: The getClass method is a final method that returns a runtime representation of the class of an object.
In Java, you can use access specifiers to protect both a class's variables and its methods when you declare them. The Java language supports four distinct access levels for member variables and methods: private, protected, public, and, if left unspecified, package. Private:
The most restrictive access level is private. A private member is accessible only to the class in which it is defined. Inheritance does not apply on the private members. They are Just like secrets. Use private keyword to create private members.
Protected:
Allows the class itself, subclasses, and all classes in the same package to access the members. Use the protected access level when it's appropriate for a class's subclasses to have access to the member, but not unrelated classes. Protected members are like family secrets. To declare a protected member, use the keyword protected
Public:
The easiest access specifier is public. Any class, in any package, has access to a class's public members. Declare public members only if such access cannot produce undesirable results if an outsider uses them. There are no personal or family secrets here; this is for stuff you don't mind anybody else knowing. To declare a public member, use the keyword public.
Package
The package access level is what you get if you don't explicitly set a member's access to one of the other levels. This access level allows classes in the same package as your class to access the members. This level of access assumes that classes in the same package are trusted friends.
To summarize:
X X
X X X X
Class Scope
Class scope
Includes Instance variables and methods Class members are accessible to class methods. They can be referenced simply by name. Outside scope, cannot be referenced by name Visible (public) members accessed through a handle
objectReferenceName.variableName or .methodName()
Block scope
Variables defined in a method known only to that method If variable has same name as class variable, class variable is hidden in that method.
Static variables
Class data members are divided into two groups:
Instance variables: every object of the class has its own copies of them. Class variables: they are allocated once for the class. All objects of class share the same variable.
Keyword static is used to create class variables. static class variables shared among all objects of class
One copy for entire class to use static class variables exist even when no objects do
static methods
Can only access static members Have no this reference
static variables are independent of objects
Examples:
The main method in public static void main(String []args) Method exit() in System.exit(); Method showMessageDialog() in JOptionPane.showMessageDialog(. . .);
Initializing Objects
Initialization is a must every time an object is created out of a class. Java compiler will initialize all class members and creating default constructors that initialize data members as follows: 0 for primitive numeric types, false for boolean, null for references. Initialization mainly happened in the class constructors. A class could have more than one way (constructor) of initialization. Initializers are passed as arguments to constructor
Object Instantiating
Classes only describe data types. To put then in use at runtime, objects have to be created (instantiated) from them. new keyword is used to instantiate an object from a class. Example:
No objects can be instantiated from Abstract classes. You can not use new here.
Composition
Composition is a powerful way of software re-use Composition is related to the has a relationship in the OOP model.
Each object has a reference to itself . It is called this reference Implicitly used to refer to instance variables and methods Used inside methods
If a parameter or a local variable has the same name as an instance variable, use this.variableName to explicitly refer to the instance variable. Use variableName to refer to the parameter
Abstract Classes
Sometimes, a class that you define represents an abstract concept and, as such, should not be instantiated. For example, the Number class in the java.lang package represents the abstract concept of numbers. Number class makes sense only as a superclass to classes like Integer or Float. An abstract class is a class that can only be subclassed-- it cannot be instantiated. To declare that your class is an abstract class, use the keyword abstract before the class keyword in your class declaration:
abstract class Number { . . . }
An abstract class may contain abstract methods, that is, methods with no implementation. In this way, an abstract class can define a complete programming interface, thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface.
Inner Classes
Inner classes are classes defined inside other classes. Inner classes have access to all the members of the outer classes. Usually we use inner classes as helper classes of adapter classes. Inner classes can be anonymous (without names) They are used intensively to write event listeners such as ActionListener, MouseListener, KeyListener, and the like.
An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface. Two elements are required in an interface declaration-the interface keyword and the name of the interface. The public access specifier indicates that the interface can be used by any class in any package.
An interface can inherit from one or more commaseparated superinterfaces using keyword extends.
The interface body contains method declarations ; each followed by a semicolon (;). All methods declared in an interface are implicitly public and abstract. An interface can also contain constant declarations. All constant values defined in an interface are implicitly public, static, and final.
Implementing an Interface
An interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (the Java platform supports multiple inheritance for interfaces. For instance,
public class StockApplet extends Applet implements StockWatcher { public void valueChanged(String tickerSymbol, double newValue){} }
Part 4
Packages:
Package names are entirely in lower case. Package name should start with the web domain name reversed Examples:
package com.sun.java.lang; package edu.nmsu.is.us.sp;
Files:
The file name must have the same base name as the name of the public class defined in the file. Example:
If you have a public class named RecordList, the file containing this class should be named RecordList.java
Classes and Interfaces: Use meaningful identifiers for classes , and interfaces. Capitalize each word contained in a class identifier name. No underscores. Examples:
public class RecordList {} public interface PanelFace {}
Variables:
Use meaningful identifiers for variables. Capitalize each word contained in a name of a variable except the first word. Use nouns to identify variables as possible. For boolean variables, use identifirs that are like questions. Use all-caps indentifiers for constants. Examples:
int number; String myName; boolean isValid; final int CODE = 707;
Methods:
Use meaningful identifiers for methods. Capitalize each word contained in a name of a method except the first word. Use verbs to identify methods as possible. For the methods dealing with objects properties, start the method identifier with get or set. If the method returns boolean use is or are instead of get to name this method. Examples:
private boolean paint() boolean isObjectValid() Font getFont() void setFont(Font f)
General Considerations:
Use three-space indentation style. Example if(num < 10) { System.out.println(Not Enough); } Use comments to mark the beginning and the end of blocks Use three-line style to comment your code. Use either one of: // /* // This part is to or * This part is to // */ Use empty lines to increase the readability of your code Use spaces between the operators such as +, -, =, and the operands. Example: c = a + b;
Software
Constructed from existing, well-defined, carefully tested, portable, widely available components Speeds development of powerful, high-quality software
Use library classes as much as you can Never re-invent the wheel Organize your code so that you can use it again. Apply principle of least privilege
Each component has enough access to accomplish its task, nothing more Prevents accidental/malicious errors
If implementation changes
Clients can still use the same methods Do not know implementation details
Documentation Generator
Java has its own standard tool for creating API documentation on the fly. This tool is javadoc. javadoc goes through the source files looking for a comment of the style /** */ to add to the documentation. The result of the javadoc utility is HTML documentation that is the same as the Java standard API documentation in format.
PART 5
Java API
One of the most powerful freatures of Java is that it is an extensible language in the sense that new API libraries are always added to it. Java mainly comes with the following APIs:
java.lang java.util java.security java.rmi java.io java.net java.beans java.sql
Java also has a huge collection of windowing classes called JFC(Java Foundation Classes) which include:
Swing collection Drag and drop collection Accessibility collection - AWT collection - look and feel collection
Java I/O
Java I/O capabilities are based on the concept of streams. A stream is an ordered sequence of bytes that have a source and destination like this
Java stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate. Generally, the algorithms for sequentially reading and writing data are basically the same: Reading Writing
open a stream while more information read information close the stream
open a stream while more information write information close the stream
Character Streams
Byte Streams
Standard I/O
The term standard I/O refers to the Unix concept of a single stream of information that is used by a program. Following the standard I/O model, Java has System.in, System.out, and System.err. System.out, and System.err are already pre-wrapped as a PrintStream object, so they can be used write away. System.in must be wrapped as before you can read from it.
Standard I/o-Example
import java.io.*; public class StdInRead { public static void main(String[] args) throws IOException { System.err.print( "Enter Your input. Empty line to exit.\n"); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String s; while((s = in.readLine()).length() != 0) System.out.println("YOU ENTERED: " + s); } }
Java provides class File to let you deal with the files and directories. It is an abstract representation of file and directory pathnames. Using File you can do things like:
Checking whether or not files exists/Deleting them Creating/renaming/listing contents of directories Checking the path names Creating new files Creating the URL of the files
Concatenating Files
import java.io.*; public class Concatenate { public static void main(String[] args) throws IOException { File inF1 = new File(f1.txt"); File inF2 = new File(f2.txt"); FileInputStream in1 = new FileInputStream(inF1); FileInputStream in2 = new FileInputStream(inF2); SequenceInputStream s = new SequenceInputStream(in1, in2); int c; while ((c = s.read()) != -1) System.out.write(c); s.close(); }
Object Serialization
Javas object serialization allows you to take any object that implements the Serializable interface and turn it into a sequence of bytes that can later be fully restored to regenerate the original object. Object serialization is interesting because it allows you to implement lightweight persistence. Object serialization was added to the language to support two major features; Javas (RMI) and JavaBeans. To serialize an object, you create some sort of OutputStream object and then wrap it inside an ObjectOutputStream object. At this point you need only call writeObject( ) and your object is serialized and sent to the OutputStream. To reverse the process, you wrap an InputStream inside an ObjectInputStream and call readObject( ).
Object Serialization
import java.io.*; class Data implements Serializable { int i; Data(int x) { i = x; } public String toString() { return "THE DATA IS " + i; } } public class Serialize { public static void main(String[] args) throws IOException, ClassNotFoundException { Data dout = new Data(100); System.out.println("OUT OBJECT:: " + dout.toString()); ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("data.out")); out.writeObject(dout); out.close(); ObjectInputStream in = new ObjectInputStream( new FileInputStream("data.out")); Data di = (Data) in.readObject(); in.close(); System.out.println("IN OBJECT:: " + di.toString()); } }
JDBC
(Introduction)
A great promise of Java has been the ability to build platformindependent client/server database applications. This has come to fruition with Java DataBase Connectivity (JDBC). JDBC is designed to be platform-independent, so you dont need to worry about the database youre using while youre programming JDBC, like many of the APIs in Java, is designed for simplicity. The method calls you make correspond to the logical operations youd think of doing when gathering data from a database: connect to the database, create a statement and execute the query, and look at the result set. To allow this platform independence, JDBC provides a driver manager that dynamically maintains all the driver objects that your database queries will need
Database URL
Example:
String dbUrl = "jdbc:odbc:people";
If the statement above does not catch any exceptions it means that the driver is loading properly.
If the statement above does not catch any exceptions, it means that the configurations are correct and the connection is established properly.
The ResultSet object r contains the result coming back from the database. The following loop can be used to print the results.
while(r.next()) { System.out.println( r.getString(FIELD 1") + ", " + r.getString(FIELD 2) + . . .); }
Updating a database means changing the data or the structure of a database. We usually update a database by executing one of the following SQL commands:
DELETE CREATE TABLE UPDATE ALTER INSERT
To update a database in JDBC we use method executeUpdate() instead of executeQuery() method in the statement
Batch Jobs
JDBC allows programmers to create a list of SQL commands that can be sent as a batch to the database drivers. Use method addBatch(String sql) in a statement object to add the given SQL command to the current list of commands for this Statement object. The commands in this list can be executed as a batch by calling the method executeBatch().
Part 6
Exception Handling
The basic philosophy of Java is that badly formed code will not be run. The ideal time to catch an error is at compile-time, before you even try to run the program. However, not all errors can be detected at compile-time. The rest of the problems must be handled at run-time.
References
Detiel and Detiel, Java 2: How to program Bruce Eckel, Thanking in Java Java Tutorial at
http://java.sun.com/docs/books/tutorial/index.html