Escolar Documentos
Profissional Documentos
Cultura Documentos
Introduction to Java
Java is an object-oriented programming language.
It runs within a Java Virtual Machine.
Everything is an object e.g. okButton is an object (an instance of the Button class)
Objects have methods e.g. okButton.setLabel("OK");
Java Class Libraries (core API) provide classes and methods for common programming tasks e.g. java.lang
(basic java functions), java.awt (fonts, graphics, GUI components), java.sql (SQL-based Database Access)
The Java source code goes through the compiler which creates intermediate code called bytecodes in the
form of class files. This does not get converted into machine executable instructions yet in Java but this
stage is instead delayed until runtime.
Java Development Kits (JDK)
Platform-specific.
Used by programmers to create Java software.
Consist of a compiler, core class libraries, tools for testing and debugging and a JVM.
Platform-specific.
Only provide what is necessary to run Java programs (i.e. a JVM).
Java Applications
Java Applets
Java Servlets
Run within the servers JVM and sends HTML to the browser. No JVM is required at the browser
side.
Build the web pages that are sent to the client to be processed by the web browser.
Started either when the web server is started or when the URL is accessed for the first time.
Methods (e.g. init(), service(), destroy())
Java Compatible
Logo appearing on products that create or run Java software and have passed the certification
process.
Logo appearing on Java-based software products that run within a Java Compatible JVM.
Java compatible
Consists of Java compiler, Java class libraries, Tools and JVM for OS/400.
AUTOEXEC:
Batch File:
Lines to add:
SET PATH=C:\JDK1.1.8\BIN;%PATH%
SET CLASSPATH=C:\ATSAJV1;%CLASSPATH%
Create a simple test program open a text editor like Notepad and enter statements like Test.java. Save file.
Compiling a program
Open a DOS prompt window. If appears as a full screen, press Alt and enter to place it in a
window.
Doskey (so can use arrow keys to access previous commands or F7 to see all with F9 and number
to run a specific command)
cd \atsajv1 - to make ATSAJV1 the current directory.
Setpath if not changed autoexec.
javac Test.java. If the DOS prompt appears and no other text was displayed then the compile was
good.
Running a program
java Test
If problems, type set to view the environment variables such as path and classpath details.
JDK Documentation
Access index.html in directory where you installed the JDK. Will open documentation in browser. Choose
to access either locally (if downloaded and installed the JDK documentation) or on Java Software website.
Scroll down to Java Platform 1.1 Core API Specification.
AppletViewer Utility
e.g. appletviewer testapplet.html
Click on Applet tag top left useful are Tag and Properties (set network and class access to unrestricted to
allow an applet to be tested)
Uses same JVM version as the JDK. A java enabled browser may use a different version of the JVM.
The appletviewer utility processes the applet tag in the HTML only and ignores other tags.
Useful documentation on-line e.g. Package index bookmarked.
Note: Java is very case-sensitive !!!
Java Basics
e.g. Computer.java
Class
Method
Java ignores blank lines and spaces between names, keywords and operators.
A semi-colon indicates the end of a line of executable code.
Usually a block of code is started on an existing line i.e. { on same line.
Java programs typically output their results to a graphical interface. A simple way is to use the
built-in java function System.out.println.
Java Application
Instance Variables
Defined after the class name and before (or between) any methods.
Format is: data-type variableName;
If same type, can be defined on one line e.g. int cpuSpeed, memory;
Local Variables
Local to a method
Defined by and used in the method
Scope is limited to the method in which it is declared
Values are not available to other methods
Can have the same names as instance variables and will be used (i.e. the instance variable is
hidden). If use the same names, will have to qualify with "this" if want to reference the instance
variable.
Can be defined in a parameter list
Static Variables
A common use is to keep track of the number of instances of an object that have been created.
Incrementing
numberOfComputers = numberOfComputers + 1; is the same as
numberOfComputers++;
same for -Comments
Single line comments begin with // and continue to the end of the line
Multiple line comments can span multiple lines when enclosed between /* and */
Data Types
Note: String is not a primitive data type. It is a type of object defined in the core APIs. It has a capital "S".
Primitive data types: byte, short, int, long, boolean, char, float, double.
Naming Conventions
No technical restriction on length and can consist of most characters on keyboard. The first character must
be alphabetic, an underscore or a dollar sign.
Length
Class Xxxxx {
}
< 15 chars
Example
One or more words (usually
nouns), no separators, first
letter of each word is
uppercase.
Class TestClass {
}
Method
GetCustomerName
Variable
FirstName
A Constructor is a special type of method that initialises instance variables when an instance is
created
A return type is not specified since it is implicitly an instance of the object.
Every class has a constructor a default one exists if one is not explicitly coded.
A default constructor initialises primitive data type variables to zero.
The constructor method name is the same as the class name.
The constructor is defined like a method.
The name of the constructor must be the same as the class name.
The constructor can accept incoming parameter values and use them to set the values of the
instance variables.
"this" is a lot like the word "me" in that the person referred to depends on who is saying it.
"this" is a means of referring to a current instance of an object without having to know its name.
The name of the instance is established outside of the constructor. Inside the constructor the
variables are qualified with "this".
When a constructor method is explicitly coded, the default constructor is no longer available.
this() Invocation
A special technique for calling the primary constructor from other constructors in the same class.
It must be the first executable line in the constructor and is often the only executable line.
If-Then-Else
if(condition) statement;
if(condition) {
statement1;
statement2;
statement3;
}
No endif
if(condition) statement;
else statement;
if(condition) {
statement1;
statement2;
statement3;
}
else {
statement4;
statement5;
}
Relational Operators
== equal to
!= not equal to
>
>=
<
<=
Logical Operators
&& and
|| or
Multiple Methods with the Same Name
A method name can be used more than once as long as the parameter list is unique.
The data types in a parameter list are what makes one methods signature different from another.
Known as method overloading.
Constructor methods are usually overloaded by at least one version that accepts no parameter
values and thus serves as a default constructor
It avoids naming conflicts by organising java classes using a hierarchical file system and Internet
host/domain name conventions.
Typically consists of the top level domain (com, net, org etc) followed by the domain or company
name, followed by naming elements that identify the group of Java classes.
A class is made part of a package by including a package stmt at the top of the java source file
e.g. package com.xyzcorp.admin.hr.utils;
If no package name is specified the compiled class will belong to the "default package".
Examples
Package name com.xyzcorp.admin.hr.utils
Directory structure c:/java/classes/com/xyzcorp/admin/hr/utils/Computer.class
Classpath setting CLASSPATH = c:\java\classes
Java run command java com.xyzcorp.admin.hr.utils.Computer
Or: Com.ats.ajv1
C:\atsajv1\com\ats\ajv1\Computer.class
CLASSPATH = c:\atsajv1
Java com.ats.ajv1.Computer
Cd \atsajv1
Md com
Md com\ats
Md com\ats\ajv1
First, create directory structure then create source within structure with package code.
Access Control Modifiers
public can be accessed by classes in any package
Package this is the default. Can be accessed only by other classes in the same package
protected Can be accessed only by other classes in the same package
and by subclasses referenced from other packages
private Can be accessed only by methods in the same class
A superclass is a class from which another class inherits methods and variables.
A subclass is a class that inherits methods and variables from another class.
Extends keyword is used in the class declaration. It identifies the superclass and makes the current
class a subclass of it.
e.g. public class SomeSubClass extends SomeClass {
An instance of the subclass inherits the instance methods and variables from the superclass.
In the subclass source, the primary constructor will accept some variable parameters from the
superclass and some from the subclass.
The "super" keyword invokes the constructor for the superclass with its parameters. It must be the
first executable line in the subclass constructor method.
The remaining code of the subclass constructor needs only to set the values of the subclass
instance variables.
An instance method in a subclass will override a method of the same name in the superclass.
Accessor Methods
Applet Basics
e.g. testapplet
How it works
Web browser requests the webpage.html file
Web server send the file plus the applet class
The applet class is loaded into the browsers JVM only once so if you change the applet you need to exit
the browser and restart it.
Every applet is a subclass of java.applet.Applet.class (which is itself a subclass).
Methods
1.
2.
3.
4.
5.
6.
Start is called after init and each time the web browser returns to the web page containing the
applet
Paint is called after start and each time the web browser window is uncovered or redisplayed
Stop is called when the web browser leaves the web page but the applet remains in memory
Destroy frees up resources used by the applet and is called when the applet is terminated
immediately after the stop method
Other inherited methods exist
Example HTML:
<applet code="TestApplet.class" width=150 height=30>
The applet tag determines the size of the area in which the applet displays its results. It must be large
enough to accommodate the results or some portions may not appear as intended.
Code this is required and identifies the applet class file. If the applet belongs to a package the fully
qualified name must be specified and the directory structure must be present on the server.
Width/height these are required and specify the size of the applet area in terms of pixels.
Codebase specifies the directory path where the applet class is located. If not used it defaults to the same
path as the HTML file,
Archive contains a collection of support classes (not Java class libraries) needed by the applet
Name if multiple applets are embedded in a single HTML file and need to communicate with each other,
they must be referred to by name
Align/vspace/hspace same as IMG tag. They align the applet area in relation to text and other objects
embedded in the HTML file
Param this passes a single parameter name and value to the applet. Multiple parameters can be used.
Alt specifies a string of alternate text to be displayed if the browser is not Java-enabled but is able to
recognise the applet tag.
Classes and packages can be imported into the applet source to shorten references to objects within them.
Coded after package statement and before class declaration. Can use wildcard *. The java.lang package is
implicitly imported into every class you create.
Every class is a subclass of java.lang.object.
Java must be enabled in your browser.
The Java Console should be enabled for debugging etc change in Internet Settings and restart PC.
Classes in the Abstract Window Tool (AWT) Package
Java.awt.Font
Java.awt.Graphics
Java.awt.Color
The abstract modifier is a means of requiring that a class be subclassed or that a method be
overridden
Label
TextField
Button
Push button
List
TextArea
Choice
Checkbox
CheckboxGroup
Scrollbar
Disabling a component makes it unresponsive to user actions and will look grayed-out.
Components added on the fly are unreferenceable and do have names assigned to them
automatically but are difficult to use.
Buttons and checkboxes have their own labels.
Retrieving HTML Parameter Data from the Web Page via getParameter()
Only string data can be passed.
HTML e.g. <applet code="ParameterApplet.class" width=200 height =80>
<param name=parameter1 value="value1">
<param name=paramtere2 value="value2">
JAVA e.g. labelno1.setText(getParameter("parameter1"));
add(labelno1);
String parm2 = getParameter("parameter2"));
add(new Button(parm2));
Boolean primitive data type true or false.
e.g. if (overdue == true) or just if (overdue)
FlowLayout
FlowLayout is the default layout manager. Components appear on the panel in the order in which they are
added and are centered.
Insets
Represent the amount of pixel space between the components and the 4 edges of the panel.
Default is 10 units for top, bottom, left and right.
this left-adjusts the components an sets the Hgap to 10 and the Vgap to 1
GridLayout
BorderLayout
The [] brackets can appear after the data type or after the variable name:
e.g. int[] intArray; or int intArray[]
Can be declared with initial values:
e.g. String[] months = {"Jan, "Feb", "Mar"}
Can also store objects:
e.g. Component[] components = getComponents();
add(components[1]);
Can be set to a specific size:
e.g. int[] days = new int[12];
Can be multi-dimensional:
e.g. String [] [] twoDimArray = new String [2] [3];
Have a length variable that yields the number of elements they contain:
e.g. for (int i = 0; i < components.length; i++)
For Loop
For (loop counter initialisation,; condition for continuation; loop iteration interval)
The condition is tested at the beginning of the loop.
The iteration is done at the end of the loop.
If you declare the counter in the for loop then its scope is limited to the loop.
The counter can be declare and initialised before the for loop.
The counter can be incremented or decremented by any amount.
Multiple counters and incrementers can be specified but only 1 condition e.g. for (i=0, j=10; i<=j; i+=2, j+
+)
Boolean expression e.g. for (; button.isEnabled();)
Instanceof Operator
The instanceof operator tests whether or not an object is an instance of a particular class.
e.g. if (a instanceof Computer)
Event Handling
e.g. Eventapplet, PriceCalcApplet, Quiz3
Events are initiated by the user, issued by a component, heard by a listener and processed by the listener
interface methods implemented in the applet.
Steps for handling an event:
1.
2.
3.
4.
5.
Similar components that use the same type of listener will call the same interface method. To distinguish
one from another, call the event objectss getSource() method to assign the result to a generic object, then
use "if" blocks to compare this object to the component in question and condition your code. See examples.
Types of Event Listeners:
Component
ComponentListener
Container
ContainerListener
TextField/TextArea
TextListener
Changes to text
List/Choice
ItemListener
Button/List/TextField
ActionListener
Component
FocusListener
Keystrokes
KeyListener
Scrollbar
AdjustmentListener
Mouse
MouseListener
Mouse
MouseMotionListener
Interfaces
Use implements keyword in the class declaration statement e.g. public class ClassA extends
Applet implements InterfaceX, InterfaceY {
The methods declared in the interface must also be declared in the class that implements the
interface.
Some interfaces declare several methods. A class that does not need certain interface methods can
code them to do nothing.
Declaring
e.g. public interface InterfaceX {
The interface keyword indicates that the source file will be compiled as an interface rather than a
class.
Access to an interface must be public or package.
Variables are implicitly static and final and must be initialised.
An interface can extend another interface.
A class that implements an extended interface must implement all the methods in the hierarchy.
Deprecation
Each primitive data type is represented by a wrapper class in the java.lang package.
Most of them have a valueOf() method that converts a String into an instance of the wrapper class.
Most of them have methods for converting instances of the wrapper class into a primitive data
type.
The toolbox contains 100% pure java classes and interfaces for accessing AS/400 objects.
Programs that use toolbox classes will run in any JVM.
It has been modified more than once as enhancements and fixes are added.
Installation on the AS/400 is not required. For development purposes, the jt400.jar (or jt400.zip)
file must be copied to the PC and cited in the CLASSPATH variable change AUTOEXEC or
SETPATH.BAT.
It can be installed on the AS/400 as Licensed Program Product 576xJC1, maintained with PTFs
and distributed to developers and applications.
The latest version can be obtained from www.as400.ibm.com/toolbox. Downloads, evaluation
copy, download evaluation copy, select jt400All.zip link. Uncompress using WinZip select zip
file on PC, choose only jt400.jar and jt400.zip and press Extract Check "selected files" and DO
NOT use folder names.
The toolbox classes provide access to the AS/400 through the several host servers: *SIGNON,
*DATABASE, *DDM, *FILE, *DTAQ, *RMTCMD, *NETPRT, *SVRMAP, *CENTRAL
The AS400 class establishes a connection to the AS/400, requests services for accessing data
queues, IFS and database files, running commands and programs, obtaining information about the
AS/400, ending the connection and many other things.
The constructors allow you to build objects that represent AS/400s. Various constructors accept the
system name or IP address, user ID and password.
The connectservice() method establishes a connection to an AS/400 host server.
The disconnectService() method breaks a connection to an AS/400 host server.
The CommandCall class is an object that allows CL commands to be run on the AS/400 and get
messages that indicate their success or failure.
The constructors allow you to build command objects associated with a specific AS/400 system
and/or a specific command string.
The run() method executes the command.
Built-in applet security prevents reading and writing to client files, initiating client programs,
displaying a window without identifying it as an applet or unsigned window and connecting to a
host that is not the originator of the applet.
The Applet Viewer utility allows you to test applets that connect to the AS/400 and are unrestricted
by network and class access (set in properties).
In order to insure that a deployed applet is served from the server rather than the development PC,
it may be necessary to rename the class file on the PC.
The codebase attribute of the applet tag is the directory path to the applet class file. The path is
relative to the html files directory unless it has a leading slash which makes it an absolute path
from the web server root. To point to a peer directory, use the "../" sequence.
If no archive is specified in the applet tag, the packages of classes used in the applet must be
available from the server.
The archive attribute of the applet tag is the path to a jar (Java ARchive) file, a zip file or a cab file
(MS). The path and file is relative to the codebase path unless it has a leading slash.
The entire archive file (jar, zip or cab) will be downloaded to the client.
An archive can be created that contains only the classes needed by the applet which makes it
smaller and quicker when it is downloaded. There are class file dependencies over and above those
actually referenced in the applet. The later toolboxes include a JarMaker utility. Uncompress all of
the classes related to AS400ToolboxInstaller and JarMaker.
Use the jt400.jar file as is and specify archive = "jt400.jar" in the applet tag. It will be downloaded
to the client PC.
2.
3.
Uncompress the jar/zip file in the web server directory structure and omit the archive attribute
from the applet tag. Each class file will be downloaded as needed. There are class file
dependencies over and above those actually referenced in the applet. The web access log will tell
you which ones.
Reduce the size of the archive file by placing in it only the classes used by the applet. Specify
archive = "400cmd.jar" in the applet tag. The JarMaker utility can extract the necessary classes
from jt400.jar and place them in a separate jar file.
e.g. In DOS prompt - C:\Atsajv1>java utilities.JarMaker s jt400.jar d 400cmd.jar rf
com/ibm/as400/access/AS400.class,com/ibm/as400/access/CommandCall.class
Classes/Interfaces used:
Com.ibm.as400.access.AS400JDBCDriver
Java.sql.DriverManager
Java.sql.Connection
Java.sql.Statement
Java.sql.ResultSet
Overview:
Register the AS/400 JDBC Driver with the SQL Driver Manager
Create a Connection object and establish a connection
Create a (SQL) statement object
Create a ResultSet object by executing the SQL statement
Process the result set
Registering the JDBC driver allows it to be used as a subprotocol when connecting to the database. The
database connection is expressed as a JDBC URL.
A JDBC driver is registered using the java.sql.DriverManagers registerDriver() method.
Once the driver is registered there are 3 types of objects used for SQL actions:
Java.sql.Connection
Java.sql.Statement (for static SQL) or java.sql.PreparedStatement (for dynamic SQL)
Java.sql.ResultSet
The objects are usually created as instance variables to achieve persistence (global scope).
The connection to the DB2/400 database is established when the DriverManagers getConnection() method
is called and the JDBC URL is specified.
A static SQL statement can be created (or allocated) using the Connection objects createStatement()
method.
A static SQL statement can be composed and executed using the Statement objects executeQuery()
method. Its results are placed in a ResultSet object.
A dynamic SQL statement can be composed using the Connection objects prepareStatement() method.
A dynamic (prepared) SQL statements parameter markers can be replaced with real values using the
Statement objects methods for specific data types.
A dynamic (prepared) SQL statement can be executed using the Statement objects executeQuery() method.
Its results are placed in a ResultSet object.
The ResultSet is typically processed by a "while" block that reads each row and extracts data from
columns.
SQL-related errors and warnings are described by the SQLException, SQLWarning and Data Truncation
exception classes in the java.sql package and "thrown" by the JDBC driver. Some SQL errors are caught as
generic Exceptions.
An exception objects getMessage() method returns the descriptive text of an exception. An SQLException
objects getSQLState() and getErrorCode() methods get the SQL state and SQL code respectively.
An exception objects printStackTrace() method sends the backtrace to the standard error stream.
Additional debugging information can be obtained by setting the errors and trace JDBC properties to "full"
and "true" respectively.
Creating the 400jdbc.jar file:
C:\atsajv1>java utilities.JarMaker s jt400.jar d 400jdbc.jar rf
com/ibm/as400/access/AS400JDBCDriver.class
When deploy on AS/400:
The "throws" keyword, specified in a method declaration, throws exceptions back to the caller. At least one
type of exception to throw must be specified. Methods that throw exceptions must be called from within a
try/catch block. The need for this capability arises when exceptions occur in non-view classes where they
dont have direct access to the user interface.
The Statement and PreparedStatement classes (java.sql package) have an executeUpdate() method for
executing SQL statements that dont return a result set.
The BigDecimal class (java.math package) is well-suited for handling numbers with a fixed number of
digits and decimal places.
The Vector class (java.util) is similar to an array but the size of vector objects can be changed and its
element can store different types of objects.
The JDKs jar utility allows you to build jar files from scratch e.g. cust400.jar.
Examples of MVC:
Model customer.java and custListData.java
View custMaintApplet.java
Controller customerDataStore.java