Java Basics for
PL/SQL Programmers
Peter Koletzke
Technical Director &
Principal Instructor
I love coffee,
I love tea
I love the java jive
and it loves me
—The Ink Spots (1940)
2
Survey
• Years with PL/SQL?
– Less than 2, 2-4, 4-12
• Years with Java?
– None
– 2, 2-4, 4-7, 7+
• Other languages?
–C
– C++
– Smalltalk
– COBOL, Basic, JCL, Perl …
3
Agenda
• Java concepts
• Variables and data types
• Control statements
Rumor: There is a
good book out on
JDeveloper.
4
Advantages of Java
• Platform independence
– Same code runs on PDA and mainframe
• Looks like C++
– Does not act like C++ (“C--” ?)
• “Simple”
– No pointers
– Manages memory for you
• Memory allocation
• Garbage collection
• Lots of deployment options
• Client/server, JSP, etc.
• A well-developed user community
– Open-source support
5
Drawbacks of Java
• Emerging language
– Currently hot
– No mass acceptance
• Microsoft is still in the game
– Technologies are changing rapidly
• Less available technical expertise
– New talent is Java-oriented, however
• It’s a 3GL
– Some IDEs help create code
• More complex than PL/SQL
– Not as fast as PL/SQL
• In the database, at least
– Needs object-oriented thinking
6
Java vs. PL/SQL
• More than just a new syntax
– Not just, { } instead of BEGIN and END
• Need an object-oriented approach
– Not always more efficient
– Build the application from classes rather
than functions and procedures
• Java actually enforces reuse and
good design practices
• PL/SQL does not enforce
these
7
Java is Object-Oriented
• All code is base on classes
• Implements inheritance, polymorphism, and
encapsulation
• Objects are built from classes
– Objects have two aspects
• Contain information
– Information is stored in the objects
• Provide operations (behavior, methods) to examine or
affect the information
– Information is changed or retrieved when operations on the
object are called
– Logic and data are merged
• Not a relational concept
• One of Codd’s 12 rules for relational databases was
independence of data and logic
8
Basic OO Terms
• Class
–
–
–
–
Fundamental building block, one file
All code is contained in classes
A “pattern” or blueprint for code objects
Source code (.java) is compiled (.class)
• Method
– Unit of code contained in a class
– Procedures and functions
• Object
– An instance of a class
– The “car” made from a blueprint
• Variable
– A named memory area created from a
primitive data type (int, float, boolean, etc.)
9
What’s Different About That?
• Parallel in PL/SQL
– A table with a package of DML procedures or
functions that act on that table
– We do this all the time, right?
• The difference?
– PL/SQL is procedural and structured with little
inheritance; objects are not at the core
– Objects are loosely bound to behavior in PL/SQL
– Java and other OO languages use objects as the
core
– Different paradigms
10
Data & Code Paradigms
Structured, Relational,
Procedural
Object-Oriented
Class
Data
definition
Application
code
Table
Data
Data
Data
Data
Data
row
Object1
Object4
Data
Data
Object2
Application
code pointer
Data
Object3
Application
code pointer
Data
Application
code
Application
code pointer
Object5
Application
code pointer
Data
Object6
Application
code pointer
Data
Application
code pointer
11
Another Way to Think About Objects
• Think of a class as an abstract data type
– Each “thing” created from the data type has
the same characteristics as the data type
PL/SQL
Instances of
the data type
v_name VARCHAR2(20) := 'Frank';
v_commission NUMBER := 200;
Java
The “data type”
String coName = "ACME Rockets";
Person coEmployee = new Person();
– The difference is that Java (OO) has
methods for the declared instance
12
Java Classes
• One “public” class per file
– Public classes are available everywhere
• All code is contained in classes
– File name is the public class name
• Spelled exactly the same
• Upper/lower case exactly the same
• Each public class stored in its own
source file
– Has same name as class
– Uses .java extension
– Compiled into a .class file
13
Java Classes
• Related class files stored in libraries of
packages
– Stored in Java archive files (JAR) or zip files
– A package corresponds to a directory
• To use a class, declare an instance
– For example,
String empName = new String();
– This creates an object, empName
• Objects are passed by reference
from one method to another
– May be as complex as desired
14
Simple Example
public class HiThere {
public static void main (String[] args) {
System.out.println("What's Happening?");
}
}
• First line declares the class
– Specifier public – available everywhere
– { } represent the start and end of the code block
• Second line declares a method – the method signature
– JVM looks for method main() when application starts
– void declares a return type of nothing
– Remainder used to pass parameters to main()method
• Third line calls external method to show message in
console – command line window
15
Anatomy of a Class
•
•
•
•
•
Package that the class belongs to
Import statements for libraries used
Class declaration
Variable declaration
Methods
– Special methods
• Constructor
– Same name as class
– Creates the object and initializes the data
head
red dot
back
tail
• main()
• set() and get()
– Called “accessors” or “getters and setters”
– Application-specific methods
mouth
bottom
hoof
leg
16
Example Class
package shapes;
Constructor
public class Box {
private int height;
private int width;
int lineWidth;
public Box() {
height = 1;
width = 1;
}
Package statement
Class declaration
Variable declarations
(attributes, fields)
public int getHeight() {
return height;
}
Code block
symbol
public void setHeight(int newHeight) {
height = newHeight;
}
public int getWidth() {
return width;
}
public void setWidth(int newWidth) {
width = newWidth;
}
}
package shapes;
import java.util.*;
public class Cube extends Box {
int height;
private int depth;
public Cube() {
height = 4;
super.setWidth(3);
depth = 2;
}
Variables and
methods are
called “members”
of the class.
Class imports
Subclass keyword
set() and get()
methods
public int getDepth() {
return depth;
}
public void setDepth(int newDepth) {
depth = newDepth;
}
public int getVolume() {
return height * getWidth() * depth;
}
}
About Methods
• Method signature:
Access specifier
Return type
Arguments
public static void main (String[] args)
Does not require
an object to use
the method
Method name
• Return type can be variable type or object type
• Overloading allowed
– More than one method with the same name
– The arguments must be different types
19
About Constructors
• Looks a bit like a method, but is not a method
• No return type (not even void)
– For example, Cube(int quantity)
• Responsible for instantiating the class
– Creating the object
– Initializes variables
• Called from other methods:
– Cube usefulCube = new Cube();
• There is a default (non-declared)
constructor for every class
20
Using Cube
public class TestCube {
main() method
Object instantiation.
Calls Cube() which
calls Box()
public static void main(String[] args) {
Cube usefulCube = new Cube();
// getHeight() shows the getHeight from Box
Call to method
// height shows the height variable from Cube in external package
System.out.println (
"The height of Cube from Box is " + usefulCube.getHeight() +
" and of usefulCube is " + usefulCube.height);
// getDepth and getVolume are from Cube
System.out.println (
"The depth of usefulCube is " + usefulCube.getDepth() +
" and the volume of usefulCube is " + usefulCube.getVolume());
}
}
Output
The height of Cube from Box is 1 and of usefulCube is 4
The depth of usefulCube is 2 and the volume of usefulCube is 24
Compiling & Running the Code
• Java source file is compiled by javac.exe
– Compiled files called “bytecode” files
• Bytecode is executed in a Java runtime
environment (JRE)
– Also called a Java Virtual Machine (JVM)
Compiler
(javac.exe)
Source code
(.java)
Runtime
(java.exe)
Compiled
bytecode
(.class)
Program
session
22
Calling Sequence
• Java application executable is a class file and
supporting libraries
– For example: HiThere.class
– Compiled from source file: HiThere.java
• Other required class files and libraries must be
available
– CLASSPATH environment variable contains list of
directories for class files
• The file name must match the class name
– File names are case sensitive, too
• Command line (or desktop icon) runs the
application:
java HiThere
• Contains a starting method called main()
– Accesses libraries in the class path
23
Basic Java Parts
• Executable program blocks - { } symbols
– Collection of declarations, specifiers, and methods
– Code blocks can be nested
• Comment styles
– Single line
// This is a single-line comment.
int count; // it can end a line
– Multiline
/* This is a multiline comment in
Java, the same as in SQL. */
/* It can be one line */
– Javadoc – text generates into HTML file
/** This is Javadoc text. */
24
Naming Conventions
• Java is a case-sensitive language
– Keywords are in lower case
• for, while, if, switch, etc.
• Case compliance is enforced for keywords
• There are conventions for other names
– Normally, no underscores used
• For example, EmpLastName not EMP_LAST_NAME
– Package names are all lower case
– Class names are mixed case
• EmployeeDataAccess
– Method and variable names are init-lower
• EmployeeDataAccess, getCity(), setCity()
– Constants use all uppercase and underscores
• MAX_LOAD, MIN_HEIGHT
25
Agenda
• Java concepts
• Variables and data types
• Control statements
26
Variable Declarations
• You can declare multiple variables on one line
int i, j, k;
int i = 1;
declaration
initialization
• You can initialize at the same time
int i = 2, j, k = 10;
• Variable and object declarations can take place
anywhere
– Java supports objects created on the fly
– Should still declare variables and objects in a
“declare” section
• Code is more consistent
• Code stands out and is easier to maintain
27
Types - Categories
• Primitive
– Hold a single value
– Cannot be passed by a pointer or
reference
– Not based on classes
• The only thing in Java that is not
• Reference (objects)
– A named memory location for a value or
set of values
– Reference it by name (no addresses)
– Technically, these are objects not variables
28
Primitive Types - Number
• Whole number
– byte
– short
– int
– long
(-128 to 127)
9.2 quintillion American
(-32,768 to 32,767)
9.2 trillion British
(-2,147,483,648 to
2,147,483,647)
(-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)
• Decimal place
– float
– double
(3.4e-038 to 3.4e+038)
(1.7e-308 to 1.7e+308)
• More precise than float, but takes double
the space (64 bits)
29
Primitive Types –
Character and Logical
• Character
– char (integer of 16 bytes, 0 to 65,536)
– Single character or symbol
– Handles Unicode (an international character set)
• Logical
–
–
–
–
–
boolean (true or false)
Two values only (there is no null logical)
true is not a number like –1
No quotes around the symbol
For example:
boolean isTrue = true;
isTrue = (2 < 1);
30
Java-PL/SQL Comparison
Java
Boolean Examples
class BooleanOperators {
public static void main (String args[]) {
boolean testCondition = true;
if (testCondition) {
System.out.println("My condition was TRUE");
testCondition = false;
if (myTestCondition)
System.out.println("This line never prints"); }
}
}
PL/SQL
-- BOOLEAN operators may be TRUE, FALSE or NULL.
v_test_condition BOOLEAN := TRUE;
31
Java-PL/SQL Comparison
Character Examples
Java
// decimal equivalent of letter 'a'
char myFirstChar = 97;
// using a character
char mySecondChar = 'a';
// octal equivalent of letter 'a' char myThirdChar =
'\141';
// Unicode (Hex) value for 'a'
char myFourthChar = '\u0061' ;
PL/SQL
v_string_char CHAR(48) := 'Data type CHAR is a fixed
length string in PL/SQL';
32
Reference Types
• A memory location for a value or set of values
– You type an object using these types
– Called a “reference variable” or “object”
• Use new operator to create an object
String testString;
testString = new String();
declaration
instantiation
• Reference type categories
– Classes
– Arrays
– Interfaces
33
Typing Based on a Class
• Core concept of creating objects
Classname objectname = new Classname();
• Most any class can be used to create an
object
– Exceptions: abstract classes, classes with private
constructors
• Data and behavior of the class are available
to the object
• There are classes that implement primitives
– These have methods (primitives do not)
– Called wrapper classes
34
Java-PL/SQL Comparison
String Examples
Java
The String class defines a multi-character variable:
// The String class is initialized and assigned here
String myString;
myString = "Any size string here";
// You can also combine declaration and assignment
String myString = "Whatever here";
// notice the double quotes around the value.
PL/SQL
The VARCHAR data type is a variable length string.
v_varchar VARCHAR2(100);
v_varchar := 'Up to 100 characters';
-- declare and assign
v_varchar VARCHAR(100) := 'Data type VARCHAR is a
variable length string in PL/SQL';
35
Variable Scope
• Variables last within the curly brackets or
structure that encloses them
for (int i = 0; i < 10; i++) {
• Like PL/SQL nested blocks
• Curly brackets for if..else, loops count
i available only
during “for” loop
– Unlike PL/SQL
{
int masterVar;
if (true) {
int ifVar;
}
masterVar
available here
ifVar not
available here
}
36
Variable Scope Examples
if (...) {
Error because i is
int i = 17;
declared in the if block.
...
}
System.out.println("The value of i = " + i);
public class VarTest {
static int i = 2;
Member variable
public static void main(String[] args) {
int i = 0;
Different variable
for (int i = 1; i <= 10; i++) {
– local to method
System.out.println(i);
}
}
Error because i is already
declared. This is OK
for (i = 1; i <= 10; i++)
37
Global Variables
• May need methods or variables that are
independent of class instantiations
• Use keyword static
– Member is instantiated when class is
referenced for the first time
– Act as global variables that are accessed
by all instances of the class
– Also used with main() method in
application classes
• Java is case-sensitive
38
Constants
• Useful at various levels
– Member
– Local
– Same scoping rules
• Use keyword final (like CONSTANT in PL/SQL)
– Final variables must be initialized in same statement
– Final methods mean the method cannot be overridden
in a subclass
– Final classes cannot be inherited
• final only applies to method and class declarations
• Can be overridden in a subclass
– For example,
static final double PI = 3.141592;
39
Some Java Operators
Function
PL/SQL
Java
Concatenation
||
+
Modulus (remainder)
MOD
%
:=
=
Assignment
Increment
i := i + 1
i++
Addition assignment
i := i + 5
i += 5
=
==
Not equal to
!=
!=
Logical AND
AND
&
Logical OR
OR
|
Ternary if-then-else
DECODE
? :
Bitwise unary not
[nothing]
~
Equal to
40
Agenda
• Java concepts
• Variables and data types
• Control statements
41
Standard Structured Language
Control Structures
• Sequence
– Code executes in the order in which it is written
– Calls to other code return to the calling point
• That’s it for sequence
• Conditional branching
– if else, switch
• Iteration
– while, for, do while
• Jump statements
– break – to exit a structure
– continue – to start loop over
– return – to go back to calling routine
– No goto
42
if else Example
class ShowQuarter {
public static void main (String[] args) {
int taxMonth = 10;
String taxQuarter;
}
}
comparison equals
Logical OR
if (taxMonth == 1 || taxMonth == 2 || taxMonth == 3) {
taxQuarter = "1st Quarter";
Logical AND
}
else if (taxMonth >= 4 & taxMonth <= 6) {
taxQuarter = "2nd Quarter";
}
else if (taxMonth >= 7 & taxMonth <= 8) {
taxQuarter = "3rd Quarter";
}
else if (taxMonth >= 10 & taxMonth <= 11){
taxQuarter = "4th Quarter";
}
else {
taxQuarter = "Not Valid";
}
System.out.println("Your current Tax Quarter is: " +
taxQuarter );
while Example
class DemoWhile {
public static void main (String[] args) {
int i = 1;
Declare and
initialize counter
while (i <= 10) {
println() handles
System.out.println(
mixing of data types
"While loop count is " + i);
i++;
While loop count is 1
}
}
}
increment
operator
While
While
While
While
While
While
While
While
While
loop count
loop count
loop count
loop count
loop count
loop count
loop count
loop count
loop count
is 2
is 3
is 4
is 5
is 6
is 7
is 8
is 9
is 10
44
for Example
class DemoFor {
public static void main (String[] args) {
int i;
for (i = 1; i <= 10; i++) {
System.out.println("For loop count is " + i);
}
For loop count is 1
}
For loop count is 2
}
For loop count is 3
• Or declare the variable in the loop
. . .
for (int i = 1; i <= 10; i++)
. . .
For
For
For
For
For
For
For
Could also be i = i +1
loop count
loop count
loop count
loop count
loop count
loop count
loop count
is
is
is
is
is
is
is
4
5
6
7
8
9
10
45
Exception Handling
• Code block is surrounded by handler
– Like PL/SQL (BEGIN EXCEPTION END)
• try – Used to start the block
• catch – Defines which exception you are
waiting for
• finally – Code that executes after the try
block (regardless of exceptions)
• throw – If you want to raise
your own exception in the code
• throws – Declare which exception you
will be throwing
46
Java Exception Handling
public class TestException extends Object {
public static void main(String[] args) {
int numerator = 5, denominator = 0, ratio;
Will raise a dividetry {
by-zero error.
ratio = numerator / denominator;
System.out.println("The ratio is " + ratio);
}
catch (Exception except) {
// display error message
except.printStackTrace();
}
finally {
System.out.println("After finally.");
}
System.out.println("The end.");
}
}
47
PL/SQL Example
DECLARE
v_numerator INTEGER = 5;
v_denominator INTEGER = 0;
v_ratio INTEGER;
BEGIN
BEGIN
-- The start of the (try) block
-- problem code
v_ratio := v_numerator / v_denominator;
EXCEPTION
--This is like the catch block
WHEN OTHERS
THEN
dbms_output.put_line(
'Exception: ' || SQLCODE ||', '|| SQLTERM);
END;
dbms_output.put_line(
'This is printed because the error is
handled correctly');
END;
48
Summary
•
•
•
•
•
•
•
•
There are many reasons to use Java
Java is object-oriented
Java is a case-sensitive language
Java has basic control statements for loops
and conditions
All Java code is inside classes
Classes are grouped into packages
Variables can be typed from primitive data
types or from classes
Recognized naming conventions
49
More Information
• The source - java.sun.com
• Java 2, The Complete Reference, 5th Ed
– Herb Schildt, Osborne McGraw-Hill
• Refactoring: Improving the Design of Existing
Code
– Martin Fowler, Addison-Wesley
• Java How to Program
– Harvey M Deitel et al., Prentice-Hall
• Java Black Book,
– Steve Holzner, The Coriolis Group
50
 Books co-authored with Dr. Paul Dorsey
 Personal web site:
http://ourworld.compuserve.com/
homepages/Peter_Koletzke
Designer
Handbook
Developer
Advanced
Forms & Reports
http://www.quovera.com
JDeveloper 3
Handbook
Also
co-authored
with Avrom
Faderman
ORACLE9i
JDeveloper
Handbook
• Founded in 1995 as Millennia Vision
Corp.
• Profitable for 5 years without outside
funding
• Consultants each have 10+ years
industry experience
• Strong High-Tech industry background
• 200+ clients/300+ projects
• JDeveloper Partner
• More technical white papers and
presentations on the web site
51
Descargar

Java Language - Computer & Information Science @ IUPUI