1 / 51

Java Basics for PL/SQL Programmers

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). Survey. Years with PL/SQL? Less than 2, 2-4, 4-12 Years with Java? None 2, 2-4, 4-7, 7+

dinos
Download Presentation

Java Basics for PL/SQL Programmers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Basics for PL/SQL Programmers Peter Koletzke Technical Director & Principal Instructor

  2. I love coffee, I love teaI love the java jive and it loves me —The Ink Spots (1940)

  3. 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 …

  4. Agenda • Java concepts • Variables and data types • Control statements Rumor: There is a good book out on JDeveloper.

  5. 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

  6. 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

  7. PL/SQL Java 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 andgood design practices • PL/SQL does not enforce these

  8. 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

  9. 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.)

  10. 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

  11. Data & Code Paradigms Structured, Relational, Procedural Object-Oriented Class Applicationcode Data definition Table Data Data Object1 Object4 Data Data Datarow Data Data Object2 Object5 Applicationcode pointer Applicationcode pointer Data Data Object3 Object6 Applicationcode pointer Applicationcode pointer Data Data Applicationcode Applicationcode pointer Applicationcode pointer

  12. 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 • The difference is that Java (OO) has methods for the declared instance PL/SQL v_name VARCHAR2(20) := 'Frank'; v_commission NUMBER := 200; Instances of the data type The “data type” Java String coName = "ACME Rockets"; Person coEmployee = new Person();

  13. 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

  14. 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

  15. 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

  16. 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 • main() • set() and get() • Called “accessors” or “getters and setters” • Application-specific methods back red dot tail head mouth bottom leg hoof

  17. Example Class Package statement Class declaration package shapes; public class Box { private int height; private int width; int lineWidth; public Box() { height = 1; width = 1; } public int getHeight() { return height; } public void setHeight(int newHeight) { height = newHeight; } public int getWidth() { return width; } public void setWidth(int newWidth) { width = newWidth; } } Constructor Variable declarations(attributes, fields) Code block symbol

  18. Another Example Class imports package shapes; import java.util.*; public class Cube extends Box { int height; private int depth; public Cube() { height = 4; super.setWidth(3); depth = 2; } public int getDepth() { return depth; } public void setDepth(int newDepth) { depth = newDepth; } public int getVolume() { return height * getWidth() * depth; } } Subclass keyword Variables and methods are called “members” of the class. set() and get() methods

  19. About Methods • Method signature: public static void main (String[] args) Access specifier Return type Arguments 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

  20. 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

  21. Using Cube main() method public class TestCube { public static void main(String[] args) { Cube usefulCube = new Cube(); // getHeight() shows the getHeight from Box // height shows the height variable from Cube 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()); } } Object instantiation. Calls Cube() which calls Box() Call to method in external package 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

  22. 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) Runtime (java.exe) Source code (.java) Compiled bytecode (.class) Program session

  23. 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

  24. 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. */

  25. 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

  26. Agenda • Java concepts • Variables and data types • Control statements

  27. Variable Declarations • You can declare multiple variables on one line int i, j, k; int i = 1; • 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 declaration initialization

  28. 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

  29. Whole number byte (-128 to 127) short (-32,768 to 32,767) int (-2,147,483,648 to 2,147,483,647) long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) Decimal place float (3.4e-038 to 3.4e+038) double (1.7e-308 to 1.7e+308) More precise than float, but takes double the space (64 bits) Primitive Types - Number 9.2 quintillion American 9.2 trillion British

  30. 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); Primitive Types – Character and Logical

  31. 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"); } } } -- BOOLEAN operators may be TRUE, FALSE or NULL. v_test_condition BOOLEAN := TRUE; Java-PL/SQL Comparison Boolean Examples Java PL/SQL

  32. // decimal equivalent of letter 'a' char myFirstChar = 97; // using a characterchar mySecondChar = 'a'; // octal equivalent of letter 'a' char myThirdChar = '\141'; // Unicode (Hex) value for 'a' char myFourthChar = '\u0061' ; v_string_char CHAR(48) := 'Data type CHAR is a fixed length string in PL/SQL'; Java-PL/SQL Comparison Character Examples Java PL/SQL

  33. 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 createan object String testString; testString = new String(); • Reference type categories • Classes • Arrays • Interfaces declaration instantiation

  34. 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

  35. 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. 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'; Java-PL/SQL Comparison String Examples Java PL/SQL

  36. 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 • Unlike PL/SQL i available only during “for” loop { int masterVar; if (true) { int ifVar; } } masterVar available here ifVar not available here

  37. Error because i is declared in the if block. Member variable Different variable – local to method Error because i is already declared. This is OK for (i = 1; i <= 10; i++) Variable Scope Examples if (...) { int i = 17; ... } System.out.println("The value of i = " + i); public class VarTest { static int i = 2; public static void main(String[] args) { int i = 0; for (int i = 1; i <= 10; i++) { System.out.println(i); } }

  38. 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

  39. 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;

  40. Some Java Operators

  41. Agenda • Java concepts • Variables and data types • Control statements

  42. 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

  43. if else Example comparison equals class ShowQuarter { public static void main (String[] args) { int taxMonth = 10; String taxQuarter; if (taxMonth == 1 || taxMonth == 2 || taxMonth == 3) { taxQuarter = "1st Quarter"; } 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 ); } } Logical OR Logical AND

  44. whileExample class DemoWhile { public static void main (String[] args) { int i = 1; while (i <= 10) { System.out.println( "While loop count is " + i); i++; } } } Declare and initialize counter println() handles mixing of data types While loop count is 1 While loop count is 2 While loop count is 3 While loop count is 4 While loop count is 5 While loop count is 6 While loop count is 7 While loop count is 8 While loop count is 9 While loop count is 10 increment operator

  45. forExample 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 For loop count is 4 For loop count is 5 For loop count is 6 For loop count is 7 For loop count is 8 For loop count is 9 For loop count is 10 • Or declare the variable in the loop . . . for (int i = 1; i <= 10; i++) . . . Could also be i = i +1

  46. 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 raiseyour own exception in the code • throws– Declare which exception you will be throwing

  47. public class TestException extends Object { public static void main(String[] args) { int numerator = 5, denominator = 0, ratio; try { 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."); } } Java Exception Handling Will raise a divide-by-zero error.

  48. 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;

  49. 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

  50. 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

More Related