JAVA 3 Copyright 2008 by Patni Day-wise Schedule Day 1 Introduction to Java Language Fundamentals OOP Concepts Applied to Java Day 2 Important Classes and Keywords in Java Packages and Interfaces Eclipse, an IDE 4 Copyright 2008 by Patni Day-wise Schedule Day 3 Exception Handling Documenting in Java javadoc Java Coding Conventions Code Reviews and Review Checklist Day 4 Collections Framework in Java Java Property files Day 5 Files and Streams Introduction to Multithreading in Java 5 Copyright 2008 by Patni Day 6 Multithreading in Java (Contd.) Day 7 Java Applets Day 8,9 JDBC Day 10 Networking Concepts Day 11 Security in Java 2 Day-wise Schedule 6 Copyright 2008 by Patni Introduction to Java 7 Copyright 2008 by Patni Javas Lineage C language was result of the need for structured, efficient, high-level language replacing assembly language C++, that followed C, became the common (but not the first) language to offer OOP features, winning over procedural languages such as C Java, another object oriented language offering OOP features, followed the syntax of C++ at most places, but offered many more features Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 8 Copyright 2008 by Patni Features of Java Completely Object-Oriented Simple Distributed : full support for TCP/IP protocol, developing distributed applications is easy Robust : Strongly typed language Secure J ava is completely object oriented. In C++, being more compatible to C, allows code to exist outside classes too, but in J ava, every line of code has to belong to some or other class. Thus it is closer to true object oriented language. J ava is simpler than C++, since concepts of pointers or multipleinheritance is not there. 9 Copyright 2008 by Patni Features of Java Architecture Neutral : Platform independent Interpreted and Compiled Dynamic Multithreaded : Concurrent running tasks 10 Copyright 2008 by Patni Features added in Java 1.1 Java-Beans : Component Technology Serialization Remote Method Invocation JDBC Java Native Interface Inner classes 11 Copyright 2008 by Patni Features added in Java 2 (Java 1.2) Java Swing CORBA : Common Object Request Broker Architecture Digital Certificates : ensures security policies Collection API : e.g. linked list, dynamic array 12 Copyright 2008 by Patni Features added in Java 1.3 XML Processing JDBC 3.0 API Swing Drag and drop Internationalization Performance Improvement in Reflection APIs JNDI Java Print service API 13 Copyright 2008 by Patni Features added in 1.4 New Security certificates added New Swing Features New I/O API Logging Secure Sockets Assertions It should be mentioned to the participant that current version of J ava is 1.5, although not covered as part of this training. 14 Copyright 2008 by Patni Platform Independence Unix on Pentium System Class file containing Bytecodes Macintosh PowerPC system Class Loader Bytecode verifier JIT compiler PowerPC machine level instructions Windows Pentium PC system Class Loader Bytecode Verifier JIT compiler Pentium machine level instructions Java compiler .java file Class Loader Bytecode verifier JIT compiler 15 Copyright 2008 by Patni Platform Independence (Contd.) Platform independence primarily helps Java Applets to be executed on any platform Allows execution of Applet class files compiled on remote system, downloaded over the internet Typically, however, on Java based Web-applications (i.e. J2EE applications), Java classes are compiled and executed on the same platform 16 Copyright 2008 by Patni Difference between JRE and JDK JRE is the Java Runtime Environment'. It is responsible for creating a Java Virtual Machine to execute Java class files (i.e run Java programs) JDK is the Java Development Kit'. It contains tools for Development of Java code (e.g. Java Compiler) and execution of Java code (e.g. JRE) JDK is a superset of JRE. It allows you to both write and run programs It should be noted that J RE is re-distributable but J DK is not re-distributable. J RE can be bundled along with your own software that you intend to sell commercially too. However, one cant bundle J DK along with ones own software. J DK is freely downloadable, but not freely redistributable. 17 Copyright 2008 by Patni Relation between Java and Sun Sun Microsystems defined and published Java Language Specification Sun also offers freely downloadable reference implementation of Java Language in the form of Sun JDK and Sun JRE Other companies can also provide implementation of Java Specification Few examples of companies who provide their own JRE are: IBM, Microsoft, BEA 18 Copyright 2008 by Patni First Simple Program //this is my first program class Example { /* the execution starts here */ public static void main(String args[]) { System.out.println(Welcome to Java ); } } 19 Copyright 2008 by Patni Compile and Run Program To compile the program: c:\javac Example.java To run it: c:\java Example 20 Copyright 2008 by Patni Language Fundamentals 21 Copyright 2008 by Patni Data types Type Size/Format Description byte 8-bit Byte-length integer short 16-bit Short Integer int 32-bit Integer long 64-bit Long Integer float 32-bit IEEE 754 Single precision floating point double 64-bit IEE 754 Double precision floating point char 16-bit A single character boolean 1-bit True or False 22 Copyright 2008 by Patni Default Values Integer : 0 Character : \u0000 Decimal : 0.0 Boolean : false Object Reference : null 23 Copyright 2008 by Patni Variables Basic unit of storage in a Java program Three types of variables: Instance variables Static variables Local variables Each variable type has different scope Formal parameters (i.e. arguments to function) are similar to local variables 24 Copyright 2008 by Patni Operators Arithmetic operators: +, - , * , / ,% ++, -- +-, -=, *= , /= , %= Relational operators: == , != , >=,>,<=,< assignment(=), ternary(?) Please find additional inputs about in Appendix-H 25 Copyright 2008 by Patni Introduction to Classes The general form of a class class < class_name>{ type var1;.. Type method_name(arguments ){ body }.. } //class ends. 26 Copyright 2008 by Patni Introduction to Classes A Simple Class class Box{ double width; double height; double depth; double volume(){ return width*height*depth; } //method volume ends. }//class box ends. 27 Copyright 2008 by Patni Declaring Objects class impl{ public static void main(String a[]){ //declare a reference to object Box b; //allocate a memory for box object. b = new Box(); // call a method on that object. b.volume(); } } 28 Copyright 2008 by Patni Types of class members default access members (No access specifier) private members public members protected members 29 Copyright 2008 by Patni Memory Management Dynamic and Automatic No delete operator Implemented by Garbage Collector Garbage Collector is the Lowest Priority Daemon Thread It runs in the background when JVM starts Collects all the unreferenced objects Frees the space occupied by these objects System.gc() method can be called to hint the JVM that it should invoke garbage collector, however, there is no guarantee that it would be invoked. It is implementation dependent There is a common misconception that system.gc() invokes the garbage collector, however that is not true. It just gives a request or hint to J VM to start garbage collector, but J VM may not start it immediately or even till end of the program execution. It is J VM implementation dependent issue, as to when it would start. It can even do some optimization by starting garbage collection, only when certain amount of memory is consumed etc. 30 Copyright 2008 by Patni Arrays A group of like-typed variables referred by common name Declaring an array int arr []; arr = new int[10] int arr[] = {2,3,4,5}; int two_d[][] = new int[4][5]; Java arrays are asymmetrical arrays 31 Copyright 2008 by Patni Arrays Arrays of objects too can be created Example 1 : Box Barr[] = new Box[3]; Barr[0] = new Box(); Barr[1] = new Box(); Barr[2] = new Box(); Example 2: String[] Words = new String[2]; Words[0]=new String(Bombay); Words[1]=new String(Pune); 32 Copyright 2008 by Patni Casting of Variables To convert one variable value to other, wherein two variables correspond to two different data types Double d = 10.5; float f = (float) b; Widening does not require casting Casting of References can be done, if two classes are related to each other by inheritance relationship If the casting is not proper, it throws ClassCastException 33 Copyright 2008 by Patni UpCasting & DownCasting Upcasting Object o = new String(HELLO); Serializable s = new String(New); DownCasting String s1 = (String) o; String s2 = (Serializable) s 34 Copyright 2008 by Patni Parameter Passing Parameters or arguments passed to a function are passed by value for primitive data-types (e.g. int, char) Parameters or arguments passed to a function are passed by reference for non-primitive data-types (e.g. All Java objects) Java does not have concept of passing parameters by address or pointers, similar to what we have in C or C++ (using * to denote a pointer to object) Trainer can demonstrate this by showing a code such as this: void myFunction(int a) { a++; System.out.println(a); } . int x =45; System.out.println(x); myFunction(x); System.out.println(x); Output will be, 45 46 45 This is an example of pass-by-value. In above example, use Integer class, instead of int, and it becomes example of pass-by-reference. The output should be 45 46 46. 35 Copyright 2008 by Patni Java is Object Oriented 36 Copyright 2008 by Patni Inheritance One of the major pillars of OO approach Allows creation of hierarchical classification Advantage is reusability of the code Once a class is defined & debugged , same class can be used to create further derived classes Already written code can be extended as and when required to adopt different situations 37 Copyright 2008 by Patni Inheritance (Contd.) Inherited members can be used with the super keyword super() ;// calls parent class constructor super.overriden() ;// calls an overriden method of the base class 38 Copyright 2008 by Patni Inheritance (Contd.) Class Base { public void meth1() { System.out.println(Method1 of Base); } } Class Derived { public void meth1() { super.meth1(); System.out.println(Method1 of Derived); } } 39 Copyright 2008 by Patni Inheritance (Contd.) class Test { public static void main(String args[]){ Derived d1=new Derived(); d1.meth1(); } } 40 Copyright 2008 by Patni Inheritance (Contd.) Output: Method1 of Base Method1 of Derived 41 Copyright 2008 by Patni Polymorphism An objects ability to decide what method to apply to itself depending on where it is in the inheritance hierarchy Can be applied to any method that is inherited from a super class Allows to design & implement systems that are more easily extensible Need to give example of Polymorphism referring to sample J ava class. 42 Copyright 2008 by Patni Abstract class A class that provides common behavior across a set of subclasses, but is not itself designed to have instances that work One or more methods are declared but may or may not be defined Advantages: Reusability of code Help at places where implementation is not available Example of Abstract class Shape Hierarchy You have two hierarchies : Point-Circle-Cylinder and Line-Square-Cube Here common method is area() if I create an array that contains the objects of all these classes. How can I do it generically ? Can Point p =new Line() be valid ? of course not, no inheritance !!!! So I force a super class Shape which would contain the method area(). Now what implementation I am going to write in that method. I dont know, at runtime whose area() is going to be called. So the information that I dont know I put it as abstract. Important points about abstract class : 1. You cannot create object of abstract class : why ? e.g. if a surgeon know how to perform an operation but he doesnt know how to stitch back the cut stomach will I allow him to touch me? 2.An abstract class can contain concrete methods. 3.An abstract class may not contain any abstract methods. 4. In J ava a pure virtual method is called as abstract method. abstract class Shape{ public abstract float area(); } 43 Copyright 2008 by Patni Abstract class (Contd.) Any class that has even one method as abstract should be declared abstract Abstract classes cant be instantiated Abstract modifier cant be used for constructors & static methods Any sub class of an abstract class should implement all methods or declare itself to be abstract An abstract class need not have only abstract methods; can have concrete methods too In C++, an abstract class is called a pure virtual function & istagged with a trailing 0; Eg : Class MyClass { public:: virtual void area() =0; .. } 44 Copyright 2008 by Patni Encapsulation Encapsulation describes the ability of an object to hide its data and methods from the rest of the world - one of the fundamental principles of OOP (Object Oriented Programming) Encapsulation is implemented using different access specifiers such as private, protected, public etc Need to mention to participants that access specifiers are discussed in detail in later. 45 Copyright 2008 by Patni Important Keywords and Classes in Java 46 Copyright 2008 by Patni Constants Use the final keyword before the variable declaration and include an initial value for that variable Eg:- final float pi = 3.141592; final boolean debug = false; final int maxsize = 30000; 47 Copyright 2008 by Patni Final Classes and Methods Final Classes Final classes cannot be inherited All methods in a final class are implicitly final Final Methods final methods cannot be overridden Methods declared as static are implicitly final Also methods declared private are implicitly final 48 Copyright 2008 by Patni Static Members You can declare both methods and variables to be static Static methods has got following restrictions They can call only static methods They can access static data only Cannot refer to this or super Static methods can access non-static variables and non- static methods, provided explicit instance variable is made available to the method 49 Copyright 2008 by Patni Nested classes Class within another class The scope of a nested class is bounded by the scope of its enclosing class Nested classes are of two types: Static Non-static Nested classes should be used to reflect and enforce the relationship between two classes 50 Copyright 2008 by Patni Anonymous Inner classes These classes do not have a name Are defined at the location they are instantiated using additional syntax with the new operator Typically used to create objects on the fly in contexts such as return value of a method, an argument in a method call or in initialization of variables 51 Copyright 2008 by Patni Object Superclass Cosmic super class Ultimate ancestor every class in Java implicitly extends Object A variable of type Object can be used to refer to objects of any type Eg. Object obj = new Emp(); Methods in Object class are : void finalize() Class getClass() String toString() 52 Copyright 2008 by Patni The System Class The System class is the class used to interact with any of the system resources It can not be instantiated Contains a lot of methods and variables to handle system I/O Among the facilities provided by the System class are standard input, standard output, and error output streams 53 Copyright 2008 by Patni The System Class Some of the methods in System class: System.gc(): is a suggestion and not a command It is not guaranteed to cause the garbage collector to collect everything System.exit(0); 54 Copyright 2008 by Patni String Handling String is handled as an object of class String and not as an array of characters String class is a better and a convenient way to handle any operation But one main restriction with this class is that once an object of this class is created, the contents cannot be changed 55 Copyright 2008 by Patni Some methods of String class length() : length of String indexOf() : searches for the occurrence of a char, or String within other String substring() : retrieves substring from the object trim() : to remove spaces valueOf() : converts data to String 56 Copyright 2008 by Patni The String Class str1 String str =new String(Pooja); String str1 =new String(Sam); Pooja Sam str str1 String str =new String(Pooja); String str1 =str; Pooja str Heap Stack 57 Copyright 2008 by Patni StringBuffer Class Peer class of String class that represents fixed length, immutable char sequence StringBuffer represents growable and writeable character sequence Insertions at particular positions are possible through this class 58 Copyright 2008 by Patni Wrapper Classes Primitives are not a part of object hierarchy Primitives are passed by value Object representation of primitives is required Wrapper classes provide a way to encapsulate simple values as objects Integer, Double, Float, Character are all wrapper classes 59 Copyright 2008 by Patni Packages and Interfaces 60 Copyright 2008 by Patni Interfaces Their need Interface defines a data-type without implementation The interface approach is sometimes known as programming by contract Its essentially a collection of constants & abstract methods An interface is used via the keyword "implements" Thus a class can be declared as class MyClass implements Sun, Fun{ ... } But a var of type Object is useful only as a generic place holder for arbitrary values. To do anything specific, you have to have an idea of the original type & apply a cast. Eg. Emp e =(Emp)obj; 61 Copyright 2008 by Patni Interfaces A Java interface definition looks like a class definition that has only abstract methods, although the abstract keyword need not appear in the definition public interface Testable { void method1(); void method2(int i, String s); } 62 Copyright 2008 by Patni Declaring and Using Interfaces public interface simple_cal { int add(int a, int b); int i=10; } //Interfaces are to be implemented. class calci implements simple_cal { int add(int a, int b){ return a+b; }} 63 Copyright 2008 by Patni Interfaces - rules Methods in an interface are always public & abstract Data members in a interface are always public, static & final A sub class can only have a single super class in Java But a class can implement any number of interfaces Thus flexibility is introduced in usage of polymorphism C++has multiple inheritance & all the complications that come with it, such as virtual base classes, dominance rules & transverse pointer casts. Few C++programmers use multiple inheritance, & some say it should never be used. 64 Copyright 2008 by Patni Interfaces & Abstract classes Abstract classes are used only when there is a is-a type of relationship between the classes You cannot extend more than one abstract class Abstract class can contain abstract as well as implemented methods 65 Copyright 2008 by Patni Packages Are a named collection of classes Are a way of grouping related classes & interfaces A package can contain any number of classes that are related in purpose, in scope or by inheritance Convenient for organizing your work & separating your work from code libraries provided by others Consider a lib wwith a large no of unordered collection of books. Imagine the time you spend in searching for a book on java!!! But suppose books are categorised & arranged in sections? Accessing would be a lot easier. 66 Copyright 2008 by Patni Packages : Their need Allow to organize classes into units Reduce problems with naming conflicts Allow to protect classes, variables & methods in a larger way than on a class-to-class basis 1. Like folders , subfolders, sub-sub-folders etc on your local directory system!!! Packages create groupings for related interfaces & classes. Eg. A set of lib classes for performing statistical analysis could be grouped together in a stats package.the package could be placed in a archive file together with a manifest describing the package & shipped to customers for use in their applications. 2. Packages create namespaces that help avoid naming conflicts between types. Interfaces & classes in a package can use popular public names like list & constants that make sense in one context but might conflict withthe same name in another package. 3. Packages provide a protection domain for developing application frameworks. Code within a package can cooperate using access to identifiers that are unavailable to external code. Package nesting Packages can contain other packages. The java class lib itself is distributed over a number of packages like java.lang, java.awt, java.net etc. Nesting packages guarantees the uniqueness of package names 67 Copyright 2008 by Patni Using packages To use a public class of a package, simple use the full package name E.g. Java.util.Date = new java.util.Date(); import statement: allows to import all the public classes in a package E.g. import java.awt.*; If the required class is in java.lang package, it can be used directly Diff between import & #include.: Import is a statement; include is a directive. Include bloats the size of the executable, import merely indicates where class can be found.thus, size of executable doesnt increase. 68 Copyright 2008 by Patni Defining A Package package com.patni.trg.demo; // import statements here. public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } 69 Copyright 2008 by Patni Defining A Package public void show() { if(bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); } } 70 Copyright 2008 by Patni Compiling A Package Specify the path of the directory, where com directory is to be created Example javac d . Balance.java javac d E:\JavaAss\MyAss Balance.java 71 Copyright 2008 by Patni Package scope access Default: features of a class having default scope can be accessed by all classes in the same package Protected: enables a feature to be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared 72 Copyright 2008 by Patni Private No Modifier Protected Public Sameclass Y Y Y Y SamePackageSubclass N Y Y Y SamePackagenon-subclass N Y Y Y Different PackageSubclass N N Y Y Diffrent Packagenon-subclass N N N Y
Access Specifiers 73 Copyright 2008 by Patni Access Specifiers Package P2 Package P1 Class A Class C Class B Class F Class G 74 Copyright 2008 by Patni Classpath For java to be able to use a class, it has to be able to find that class on the file system Otherwise, the runtime flags an exception that the class does not exist Java uses 2 elements to find classes The package name The directories listed in classpath variable 75 Copyright 2008 by Patni Classpath(Contd.) classpath : points to various places where java classes live The specific location that Java compiler considers as root of an package hierarchy is controlled by classpath e.g. classpath = c:\jdk1.2.2\bin; c:\jdk1.4.2_03; d:\java; 76 Copyright 2008 by Patni How compiler locates a file Compiler searches through all directories specified in the classpath variable If . is specified in classpath, then it also checks current directory If compiler still does not locate the file, it flags a ClassNotFound Exception 77 Copyright 2008 by Patni Eclipse, an IDE 78 Copyright 2008 by Patni What is an IDE? An application or set of tools that allows a programmer to write, compile, edit, and in some cases test and debug within an integrated, interactive environment IDE combines the editor, compiler, runtime environment and debugger all in the single integrated application. (e.g. When one attempts to compile code with syntax errors, IDE shows the error messages, and lets one jump to that line by clicking on error message) 79 Copyright 2008 by Patni Some examples of an IDE Eclipse JDeveloper WSAD (WebSphere Studio Application Developer) JBuilder 80 Copyright 2008 by Patni Using Eclipse as an IDE The Eclipse Project is an open source software development project dedicated to providing a robust, full-featured, commercial-quality, industry platform for the development of highly integrated tools and rich client applications 81 Copyright 2008 by Patni Using Eclipse as an IDE Our objective is to code Java programs faster with Eclipse 3.0 as an IDE Eclipse3.0 features include: Creation and maintenance of the Java project Developing Packages Debugging a java program with variety of tools available Running a Java program 82 Copyright 2008 by Patni Using Eclipse as an IDE Developing the Java program will be easier as Eclipse editor will provide: Syntax highlighting Content/code assist Code formatting Import assistance Quick fix Trainer should explain each of these features to participants. 83 Copyright 2008 by Patni Eclipse-Plugins Lomboz Checkstyle JDepend PMD Ant 84 Copyright 2008 by Patni Exception Handling 85 Copyright 2008 by Patni Exception Handling Exception is an object that describes an exceptional condition Java Exception handling is managed by 5 keywords try, catch finally throw throws 86 Copyright 2008 by Patni Exception Handling RunTime Exception Compile Time Exception Exception Error Throwable Unchecked Exception Checked Exception Common misconception found in new programmers in Java is Compile- time exceptions are those that occur at compile time and runtime exception are those that occur at runtime. This is misleading. They need to be explained clearly that -- Checked exceptions are sometime called Compile time exception, but they do not really occur at compile time. Rather, they are checked by complier at compile time, to ensure that programmer has caught them or specified them in throws clause of the signature. For unchecked exceptions, also called Runtime exceptions, compiler does not insist to handle them in code. 87 Copyright 2008 by Patni Some Examples Checked Exceptions include: IOException SQLException ClassNotFoundException Unchecked Exceptions include: ArithmaticException NullPointerException ArrayIndexOutOfBoundsException 88 Copyright 2008 by Patni Using try and catch class demo { public static void main(String a[]) { try { int d = 0; int a = 42 /d; } catch(ArithmeticException ae) { System.out.println(ae); } }} 89 Copyright 2008 by Patni Throw and Throws clause It is a way to throw an exception explicitly Must be an object of Throwable or its subclasses Example: public void passgrade(int a, int total) { if (a > total) throw new ArithmeticException(); } 90 Copyright 2008 by Patni Throws clause If method is capable of throwing an exception, then caller needs to be informed, so that they can guard themselves against the exception public void passgrade(int a, int total) throws ArithmeticException { if (a > total) throw new ArithmeticException(); } Throws clause is not commonly used for Exceptions of type Error, RuntimeException, or its subclasses 91 Copyright 2008 by Patni Finally clause Finally clause creates a block of code that will be executed whether or not an exception is thrown Usage: try { int j = 0; int I = d/j; } catch (ArithmeticException ae) { System.out.println(ae); } finally { System.out.println(Always Executed); } 92 Copyright 2008 by Patni Application Specific Exceptions class ApplicationException extends Exception { private int detail; ApplicationException(int a) { detail = a;} ApplicationException(String args) { super(args); } public String toString(){ return "ApplicationException["+detail+"]";} } 93 Copyright 2008 by Patni Documenting in Java - javadoc 94 Copyright 2008 by Patni What is javadoc? Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, inner classes, interfaces, constructors, methods, and fields To generate javadocs for the class some commenting styles must be followed in the program 95 Copyright 2008 by Patni Javadoc Comments A general javadoc comment /** * This is the typical format of a simple documentation *comment that spans two lines */ Documentation comments are recognized only when enclosed between /** and */ and placed immediately before class, interface, constructor, method, or field declarations At this stage, trainer may show how a typical J avadoc generated HTML page looks like. Visiting a framed version of J avadoc, with left-frame listing all the classes of a given package and right-frame showing documentation of a particular class would be good enough. 96 Copyright 2008 by Patni Javadoc Comments (Contd.) Class and interface Documentation tags @see,@deprecated,@author,@version and more Example: /** * A class representing a window on the screen. * For example: * @author patni * @see java.awt.BaseWindow */ class Window extends BaseWindow { ... } 97 Copyright 2008 by Patni Field Documentation tags: @see,@deprecated,@since,@serial and more Example: /** * The X-coordinate of the component. * * @see #getLocation() */ int x = 1263732; Javadoc Comments (Contd.) 98 Copyright 2008 by Patni Javadoc Comments (Contd.) Constructor and Method Documentation Tags @see,@param,@return,@since,@throws,@exception and more /** * Returns the character at the specified index. An index * @param index the index of the desired character 99 Copyright 2008 by Patni Javadoc Comments (Contd.) * @return the desired character. * @exception StringIndexOutOfRangeException * if the index is not in the range <code>0</code> * to <code>length()-1</code>. * @see java.lang.Character#charValue() */ public char charAt(int index) { ... } 100 Copyright 2008 by Patni Java Coding Conventions 101 Copyright 2008 by Patni Coding Conventions Every project in Patni MUST follow consistent Java Coding Conventions, unless overridden by client for that project Coding conventions (also known as Coding Guidelines) are set of suggestive guidelines defined for a project, that helps to enforce consistent coding style across developers within the project For example, it ensures consistent and readable names of variables, classes or methods across application 102 Copyright 2008 by Patni Coding Conventions (Contd.) Examples of Coding Conventions Guidelines Class level member variable should be m_x<varname> where m indicates member variable, x should be replaced with i for integer, s for String etc. e.g. m_sUserName // String that stores User Name Function Arguments variables (formal parameters) should be a_x<varname> where a indicates argument variable, x should be replaced with i for integer, s for String etc. e.g. a_iProjectCode // integer argument to hold proj-code First letter of every class should always be in upper case. Variable names such as String string1 = new String() should be avoided. Instead, sensible variable name should used New fresh programmers (in J ava or any other language) tend to name a variable such as this String string1 =new String(); int x =45; Later, once coding is completed, they search and replace variable string1 with sensible name such m_sUserName, to comply with coding convention set in the project. This should be avoided. The culture should be developed to never ever name a variable without following its convention. Once it becomes a habit, it would never be forgotten and never need to be imposed 103 Copyright 2008 by Patni Coding Conventions (Contd.) How do Coding Conventions help the project? Helps to define the consistent ways of naming a variable or a class or a method within application Improves readability of the code Helps during defect fixing and maintenance phase, since variable names are indicative of its scope, type etc Makes debugging of code person-independent Saves efforts on documentation, since variable/method or class names becomes self-describing 104 Copyright 2008 by Patni Coding Conventions (Contd.) How to use Coding Conventions on the project? Typically defined by client or senior team member or PL before the start of the coding phase If not defined for a project, refer to conventions defined by Sun (http://java.sun.com/docs/codeconv/index.html) Should be read and understood by every developer before starting the code (to avoid rework later on) Should be adopted as part of the coding-culture itself, and not as add-on activity applied after functional coding is done Should come naturally to every developer Should get caught during code-reviews, if not followed New fresh programmers (in J ava or any other language) tend to name a variable such as this String string1 =new String(); int x =45; Later, once coding is completed, they search and replace variable string1 with sensible name such m_sUserName, to comply with coding convention set in the project. This should be avoided. The culture should be developed to never ever name a variable without following its convention. Once it becomes a habit, it would never be forgotten and never need to be imposed 105 Copyright 2008 by Patni Coding Conventions (Contd.) Coding Conventions can be found on Patni KC Patni KC Home -> Quality Processes -> Coding Standards -> Java Coding Standards Coding Conventions defined by Sun (http://java.sun.com/docs/codeconv/index.html), that can be used for rest of the assignments within this course Coding Conventions Trainer should open the attached PDF, and do a quick walk-through of Section 9 which defines the naming conventions to be used. Rest of the sections should be left as reading exercise for participants. Trainer should insist on following these conventions for rest of the lab assignments within the course. 106 Copyright 2008 by Patni Code Reviews and Review Checklist 107 Copyright 2008 by Patni Reviews Being SEI-CMMi Level 5 company, reviews are part of the life in Patni Reviews do take place for every work product created in SDLC of a project (e.g. Design review, test case review, code review etc.) Various types of reviews in Patni Self-Review Peer-to-peer review Peer review SDLC stands for Software Development Life Cycle Trainer can give high level understanding of what reviews mean to participant. Explain 3 different types of reviews at high level only. 108 Copyright 2008 by Patni Peer to Peer Code Reviews Code is reviewed by Peer (colleague) Why Peer to Peer Reviews are required? Everyone has a blind spot. Cant catch ones own mistake Helps to catch the defect early in the life-cycle Defects found in reviews may be difficult or impossible to find in testing (e.g. coding convention defects) It takes more efforts to find the same defect during testing (Cost of finding defect in testing is higher than cost of finding defect in reviews) Enforces consistency amongst developers and clarifies misunderstood points during review discussions 109 Copyright 2008 by Patni Java Code Review Checklist Code reviews should be done using a checklist, and should cover functional reviews too Typically code-review checklists are created senior team member (GL) or PL or sometimes provided by client too If not defined for a project, refer to checklists available on Patni KC Should be read and understood by every developer before starting the code creation and code reviews Checklist must be used by code-creator for self-review. This will reduce the efforts during peer-to-peer review Should be adopted as part of the coding-culture itself 110 Copyright 2008 by Patni Java Code Review Checklist (Contd.) Typically Java Code Review checklist looks like this Sample Java Code review checklist One of the important points that code-review checklist ensures is enforcing coding conventions (or coding guidelines) discussed in earlier slides Review Findings of code-review should be captured as code- review defects. Defects should be fixed by code-creator, and re-verified by the person reporting the defect There could be a walk-through of few bullets in this code review checklist, primarily for Section 2 Core J ava. Other sections can be skipped for now. This checklist may be used for code-reviews of rest or few of the code-assignments on this course. 111 Copyright 2008 by Patni Collections Framework in Java 112 Copyright 2008 by Patni What is Collections Framework? A Collection is a group of objects Collections framework provide a a set of standard utility classes to manage collections Collections Framework consists of three parts: Core Interfaces Concrete Implementation Algorithms such as searching and sorting 113 Copyright 2008 by Patni Collections Hierarchy 114 Copyright 2008 by Patni Collection Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); 115 Copyright 2008 by Patni Collection Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); 116 Copyright 2008 by Patni Collection Array Operations Object[] toArray(); Object[] toArray(Object a[]); 117 Copyright 2008 by Patni Map is in the sorted key order. SortedMap For classes implementing key-value pair kind pf mappings. Can not contain duplicate keys. Map An ordered collection (i.e. sequence). Duplicates and multiple null values allowed. List Maintains the elements in sorted order. SortedSet Maintains a set of unique elements. Set Defines the operations that all classes that maintain collections typically implement Collection Description Interfaces Collection Interfaces 118 Copyright 2008 by Patni Linked List Linked List TreeMap TreeSet Balanced Tree Resizable Array Hash Map Hash Set Hashtable SortedMap Map List SortedSet Set Data Structures Interfaces Concrete Implementations Array List 119 Copyright 2008 by Patni The Classes Legacy classes Vector HashTable Stack 120 Copyright 2008 by Patni Java Property files 121 Copyright 2008 by Patni Java Property files java.util.Properties is a platform-independent generalization of the DOS SET environment, or the Windows *.INI files. In Java, even each object could have its own list of properties. A program can determine if an entry is missing in the property file and provide a default to using it its place 122 Copyright 2008 by Patni Java Properties Java.util.Properties class: The Properties class represents a persistent set of properties. The Properties can be saved to path from where the properties file would be picked up. Each key and its corresponding value in the property list is a string 123 Copyright 2008 by Patni Types of properties Property files provide a means of storing key-value pair,which could be used by the programs in execution Properties can be categorized as: User specific properties System properties 124 Copyright 2008 by Patni Types of properties User specific properties: These properties are part of the Application.properties containing a key value pair, which can be mentioned by the program in run #application.properties file contents password=tiger url=jdbc:oracle:thin:@192.168.12.16:1521:oracle8i driver=oracle.jdbc.driver.OracleDriver username=scott 125 Copyright 2008 by Patni Types of properties System properties: System properties give information about the environment of the program ,in which it is running such as JVM it is running in, Operating System name and version, java home and many more properties 126 Copyright 2008 by Patni System Properties System properties are read from System class, which give information about the environment of the Java program in which it is running, such as: Java.vm Java.version User.language Java.home User.region etc 127 Copyright 2008 by Patni Files and Streams 128 Copyright 2008 by Patni Streams Files are necessary for persisting data Java views each file as a sequential stream of bytes Stream is generic term for flow of data Different streams are used to represent different kinds of data flow When a file is opened, an object is created and a stream is associated with the object 129 Copyright 2008 by Patni Streams(Contd.) Thus, an object from which we can read a sequence of bytes is input stream Thus, an object to which we can write a sequence of bytes is output stream The source or destination of data can be files, network connections or even blocks of memory The Java I/O class libraries allows user to handle any data in the same way 130 Copyright 2008 by Patni Java.io package Provides an extensive set of classes for handling I/O to & from various devices Contains many classes each with a variety of member variables & methods It is layered ie. It does not attempt to put too much capability into 1 class Instead a programmer can get the features he wants by layering one class over another 131 Copyright 2008 by Patni I/O Handling All Java programs automatically import java.lang package This package defines a class called System, which encapsulates several aspects of run-time environment It contains three predefined stream variables called in,out, and err (public static) 132 Copyright 2008 by Patni Input streams 133 Copyright 2008 by Patni Output streams 134 Copyright 2008 by Patni InputStream class An abstract class that defines methods for performing I/p Serves as base class for all other InputStream classes Defines a basic interface for reading streamed bytes of information Data in InputStream is transmitted one byte at a time The typical scenario when using an input stream is to create an InputStream-derived object and then tell it you want to input information by calling an appropriate method. If no input information is currently available, the InputStream uses a technique known as blocking to wait until input data becomes available. An example of when blocking takes place is the case of using an input stream to read information from the keyboard. Until the user types information and presses Return or Enter, there is no input available to the InputStream object. The InputStream object then waits (blocks) until the user presses Return or Enter, at which time the input data becomes available and the InputStream object can process it as input. 135 Copyright 2008 by Patni InputStream class : some methods int read() : Returns an integer representation of the next available byte of input int read(byte buffer[]): int read(byte buffer[], int offset, int numbytes) int available() void close() void mark(int numbytes) int read(byte buffer[]): Attempts to read up to buffer.length bytes into buffer and returns the actual number of bytes that were successfully read int read(byte buffer[], int offset, int numbytes) :Skips over numbytes of input, returning the number of bytes actually skipped Void mark(int numbytes) :Places a mark at the current point in the input stream that will remain valid until numbytes are read int available() :returns the number of bytes of input currently available for reading 136 Copyright 2008 by Patni Using the Stream variables import java.io.*; class ReadKeys { public static void main (String args[]) { StringBuffer sb = new StringBuffer(); char c; try { while((ch =(char)System.in.read()) != '\n')) { sb.append(c); } } catch (Exception e) { ... } String s = new String(sb); System.out.println(s); } } 137 Copyright 2008 by Patni OutputStream void write (int b): Writes a single byte to an output stream void write(byte buffer[]) void write(byte buffer[], int offset, int noBytes) void flush() void close() 138 Copyright 2008 by Patni FileInputStream The FileInputStream class creates an InputStream that you can use to read the contents of a file. It has two constructors: FileInputStream(String filepath) throws FileNotFoundException FileInputStream(File fileobj) throws FileNotFoundException 139 Copyright 2008 by Patni FileOutputStream The FileOutputStream class creates an OutputStream that you can use to read the contents of a file. It has two constructors: FileOutputStream(String filepath) FileOutputStream(File fileobj) 140 Copyright 2008 by Patni ByteArrayInputStream ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source. This class has two constructors , each of which requires a byte array to provide the data source ByteArrayInputStream(byte array[]) ByteArrayInputStream(byte array[],int start,int numbytes) 141 Copyright 2008 by Patni Chaining of streams Each class accesses the output of the previous class through the in variable Example FileOutputStream fos = new FileOutputStream(c:\a.txt); DataOutputStream dos = new DataOutputStream(fos); 142 Copyright 2008 by Patni Character Streams: Readers/Writers Reader and Writer classes are designed for character streams Reader is an input character stream that reads a sequence of Unicode characters Writer is an output character stream that writes a sequence of Unicode characters 143 Copyright 2008 by Patni Reader hierarchy 144 Copyright 2008 by Patni Writer hierarchy 145 Copyright 2008 by Patni File class File class doesnt operate on streams Represents the pathname of a file or directory in the host file system Used to obtain or manipulate the information associated with a disk file, such as permissions, time, date, directory path etc An object of File class provides a handle to a file or directory and can be used to create, rename or delete the entry 146 Copyright 2008 by Patni File class Some methods canRead() exists() isFile() isDirectory() getAbsolutePath() getName() 147 Copyright 2008 by Patni File class methods (Contd.) getPath() getParent() Length() : returns length of file in bytes as long lastModified() Mkdir() List() : obtain listings of directory contents 148 Copyright 2008 by Patni Serialization Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable 149 Copyright 2008 by Patni Object Serialization Allows an object to be transformed into a sequence of bytes that can be later re-created into an original object After deserialization, the object has the same state as it had when it was serialized(barring any data members that are not serialized) For a object to be serialized, the class must implement the Serializable interface 150 Copyright 2008 by Patni RandomAccessFile RandomAccessFile encapsulates a random-access file RandomAccessFile(String FileObj, String access); RandomAccessFile(String filename, String access) access can be r or rw void seek( long newPos); 151 Copyright 2008 by Patni Multithreading in Java 152 Copyright 2008 by Patni Multithreading A multithreaded program contains two or more parts that can run concurrently. Each part of that program is called thread, and each thread defines a separate path of execution There are two distinct types of multitasking: process based & thread based Thread is also known as lightweight process 153 Copyright 2008 by Patni Multithreading The Main thread When a Java program starts up, there is already one thread running It is the thread from which other child threads will be spawned It must be the last thread to finish execution. When the main thread stops, your program terminates If the main thread finishes before a child thread has completed, then the Java run-time system may hang 154 Copyright 2008 by Patni Main Thread Although the main thread is called automatically when program starts, it can be controlled by a thread object How? Obtain a reference to it by calling the method currentThread() (a public static member of Thread class) static Thread currentThread(){ } This returns a reference to the thread in which it is called. Once a reference to the main thread is obtained, it can be controlled just like any other thread 155 Copyright 2008 by Patni Multithreading Creating new Threads java.lang.Thread Creating a thread involves two steps: writing the code that is executed in the thread and writing the code that starts the thread There are two ways to create a thread Implementing Runnable interface Extending Thread class 156 Copyright 2008 by Patni Runnable interface Need to implement run() public abstract void run() Instantiate an object of type Thread within that class Thread defines several constructors Thread ( Runnable threadOb, String threadName ); The new thread will not start running until its start() method isnt invoked In turn, start() executes a call to run(). synchronized void start ( ) 157 Copyright 2008 by Patni Extending Thread class The extending class must override the run() method, which is the entry point for the new thread It must also call start() to begin execution of the new thread 158 Copyright 2008 by Patni LifeCycle of Thread Ready to run Dead Running scheduling Terminates Start Sleeping Blocked Waiting Non-runnable state Entering non-runnable Leaving non-runnable 159 Copyright 2008 by Patni States of Java Thread Not Runnable Still alive, but it is not eligible for execution It can move to not runnable stage because of following reasons: 1. The thread is waiting for an I/O operation to complete 2. The thread has been put to sleep for a certain period of time (using the sleep() method) 3. The wait() method has been called 4. The thread has been suspended (using suspend() method) 160 Copyright 2008 by Patni States of Java Thread Dead When a thread terminates, it is DEAD. Threads can be DEAD in a variety of ways which include 1. When its run() method returns 2. When stop() or destroy() method is called 161 Copyright 2008 by Patni Methods invoked on Threads interrupt() : interrupts a thread interrupted() : true if current thread has been interrupted and false otherwise isInterrupted() : determines if a particular thread is interrupted stop() : stops a thread by throwing a ThreadDeath object which is a subclass of error 162 Copyright 2008 by Patni The Thread Class Methods getPriority(): Obtains thread priority start(): To start the operation of a thread sleep(): suspends the thread for some time run(): body of the thread suspend()/resume(): suspends a thread & resumes 163 Copyright 2008 by Patni Methods invoked on Threads getName(): returns the name of the thread toString(): returns a string consisting of the name of the thread, priority of the thread and the threads group currentThread(): returns a reference to the current Thread join(): waits for the thread to which the message is sent to die before the current thread can proceed 164 Copyright 2008 by Patni Methods invoked on Threads isAlive(): returns true if start has been called but stop has not setName(): sets the name of the thread Yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute 165 Copyright 2008 by Patni Pre-emptive VS Nonpre-emptive Pre-emptive : The OS interrupts programs without consulting them Non pre-emptive: The programs are interrupted only when they are ready to yield control With non preemptive scheduling, the scheduler runs the current thread forever, requiring that the thread explicitly to tell it when it is safe to start a different thread. With preemptive time - slicing, the scheduler runs the current thread until it has used up a certain tiny fraction of a second, & then preempts it, suspends it, and resumes another thread for the next tiny fraction of a second 166 Copyright 2008 by Patni Scheduling & Priority Thread-scheduling: A mechanism used to determine how runnable threads are allocated CPU time A Thread-scheduling mechanism is either preemptive or non preemptive Scheduling can be controlled through priorities setPriority() getPriority() Three types of priorities can be set viz MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY 167 Copyright 2008 by Patni Scheduling & Priority The job of Java scheduler is to keep a highest priority thread running at all times If timeslicing is available, it ensures that several equally high - priority threads execute for a quantum in a round - robin fashion 168 Copyright 2008 by Patni Multithreading JVM implementation dependent The early Solaris Java platform runs a thread of a given priority to completion or until a higher priority thread becomes ready At that point preemption occurs, I.e the processor is given to the higher - priority thread while the previously running thread must wait 169 Copyright 2008 by Patni Multithreading policies In 32-bit Java implementations for Win 95 & Win NT, threads are time sliced Each thread is given a limited amount of time to execute on a processor When that time expires the thread is made to wait while other threads of equal priority get their chance to use their quantum in round - robin fashion 170 Copyright 2008 by Patni Multithreading policies Thus, on Win 95 and Win NT, a running thread can be pre - empted by a thread of equal priority Whereas on the early solaris implementation, a running thread can only be pre-empted by a higher priority thread 171 Copyright 2008 by Patni Thread Synchronization Implemented using synchronized keywords A method can be synchronized so that only one thread at a time can access the method This is possible using a technique called as object monitor Even an object can be synchronized 172 Copyright 2008 by Patni Inter thread Communication final void wait(): tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify() final void notify(): wakes up the first thread that called wait() on the same object final void notifyall(): wakes up all the threads that called wait() on the same object. The highest priority thread will run first 173 Copyright 2008 by Patni Applets 174 Copyright 2008 by Patni What is an applet ? Applets are small programs stored over web server Transported over the net Installed automatically Run as a part of web page Need an environment of web browser 175 Copyright 2008 by Patni Applet basics Any applet has to inherit from an Applet class The methods in the Applet class are init() start() paint(Graphics g) stop() destroy() 176 Copyright 2008 by Patni Applet basics(Contd.) Adding an applet to html document <html> <applet code=myapplet.class width=400 height=400> </applet> </html> Running an Applet c:\appletviewer ex.html 177 Copyright 2008 by Patni Applet basics(Contd.) Applets do not have a main method Applets must run under the environment of web browser Applets do not have the right/permission to access the file system on client machine They can not perform any I/O operation 178 Copyright 2008 by Patni A Simple Applet import java.applet.Applet; import java.awt.*; public class simpleapp extends Applet { public void init(){ //any initialization setBackground(Color.black); setForeground(Color.yellow); } public void paint(Graphics g){ g.drawString(Hello World,100,100); } } 179 Copyright 2008 by Patni Other Applet methods repaint(): to request painting again update() showStatus(String) getDocumentBase(): URL of HTML file getCodeBase(): URL of applet file getParameter(String): to retrieve the parameter value from HTML document 180 Copyright 2008 by Patni JAR files < applet archive=appletbundle.jar code=appletname.class width=w height=h></applet> JAR files can be made by using the jar tool Jar cf appletbundle.jar *. class image.* To display the content of the jar file Jar tf appletbundle.jar To extract the content of the jar file Jar xvf appletbundle.jar 181 Copyright 2008 by Patni Applets Applet Life Cycle Features You add components to a Swing applet's content pane, not directly to the applet The default layout manager for a Swing applet's content pane is BorderLayout You should not put painting code directly in a JApplet object 182 Copyright 2008 by Patni Applets (Contd.) Threads in Applet It's generally considered safe to create and manipulate Swing components directly in the init method 183 Copyright 2008 by Patni Applets (Contd.) Embedding an Applet in an HTML Page <applet code="TumbleItem.class" codebase="example- 1dot4/" archive="tumbleClasses.jar tumbleImages.jar" width="600" height="95"> <param name="maxwidth" value="120"> <param name="nimgs" value="17"> <param name="offset" value="-57"> <param name="img" value="images/tumble"> 184 Copyright 2008 by Patni Applets (Contd.) Your browser is completely ignoring the <applet> tag! </applet> 185 Copyright 2008 by Patni Demo : Applet Demo HelloSwingApplet.java 186 Copyright 2008 by Patni Java Database Connectivity 187 Copyright 2008 by Patni Java Database Connectivity JavaSoft worked with D/B tool vendors to provide DBMS independent mechanism to write client side applications The result is JDBC API JDBC API is designed to allow developers to create database front ends without having to continually rewrite the code An API that is D/B independent and uniform across databases 188 Copyright 2008 by Patni Java Database Connectivity A standard to write which takes all app. designs into account This is possible through a set of interface that are implemented by the driver Driver is responsible for converting a standard JDBC call to a native call 189 Copyright 2008 by Patni What is JDBC Java Database Connectivity (JDBC) is a standard SQL database access interface, providing uniform access to a wide range of relational databases JDBC provides a common base on which higher level tools and interfaces can be built 190 Copyright 2008 by Patni What does JDBC Do ? JDBC makes it possible to do three things: 1) Establish a connection with a database 2) Send SQL statements 3) Process the results 191 Copyright 2008 by Patni Why JDBC ? Java is a write once, run anywhere language Java based clients are thin client Suited for network centric models It provide a clean , simple, uniform vendor independent interface JDBC support all the advance features of latest version ANSI SQL JDBC API provides a rich set of methods 192 Copyright 2008 by Patni Database Connectivity JDBC ODBC 193 Copyright 2008 by Patni ODBC Architecture ODBC API ODBC Driver Manager Application Application Oracle Driver SQL Server Driver DB 2 Driver SQL * Net Net Lib ESQL/DRDA Oracle Database SQL Server DB 2 Application Service Provider API 194 Copyright 2008 by Patni JDBC Architecture JDBC Driver Manager Application Application Oracle Driver SQL Server Driver JDBC -ODBC Driver SQL * Net Net Lib Oracle Database Sybase Application ODBC Driver SQL Server JDBC API Service Provider API 195 Copyright 2008 by Patni So why not just use ODBC from Java? ODBC relies on the multiple use of void * pointers and other C features that are not natural in java ODBC driver manager and drivers must be manually installed on every client machine. JDBC code is automatically installable, portable, and secure ODBC is procedure oriented, while JDBC is object oriented 196 Copyright 2008 by Patni Two-tier and Three-tier Models JDBC API supports both two-tier and three-tier models for database access Java Applet or HTML browser Application server (JAVA) JDBC HTTP,RMI,CORBA Propriety protocal Client GUI Database server Business logic JAVA Application JDBC DBMS Propriety protocol Three-tier JDBC Two-tier JDBC 197 Copyright 2008 by Patni JDBC API - java.sql Statement PreparedStatement CallableStatement Connection Driver ResultSet DatabaseMetaData ResultSetMetaData Interfaces in java.sql 198 Copyright 2008 by Patni JDBC components Driver Manager Driver Manager Driver Connection Statement ResultSet PreparedStatement CalllableStatement ResultSet ResultSet 199 Copyright 2008 by Patni Database access from Java Steps Involved Loading the Driver Establishing the connection Passing Sql Query 200 Copyright 2008 by Patni Loading Drivers Class.forName()throws ClassNotFoundException - sun.jdbc.odbc.JdbcOdbcDriver - jdbc.driver.oracle.OracleDriver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }catch(ClassNotFoundException e) { System.out.println(Exception : + e);} 201 Copyright 2008 by Patni Types of Driver Type I : Jdbc-Odbc Bridge Driver Type II : Partly Java, partly native code implementing Vendor specific API Type III : Pure Java driver requesting either to type I or II as another layer Type IV : Pure Java requesting directly to the database 202 Copyright 2008 by Patni Establishing Connection A JDBC URL has the following syntax String url= jdbc:<subprotocol>:<subname> // for odbc String url= jdbc:odbc:employee ; // for jdbc String url= jdbc:oracle:thin:@tech:1521:ORCL ; Connection con = DriverManager.getConnection (url,"myLogin", "myPassword") 203 Copyright 2008 by Patni Retrieving Data from Table ResultSet executeQuery( String sql) throws SQLException ResultSet rs = stmt.executeQuery("SELECT name, age FROM student"); Retrieving data from Resultset boolean next( ) throws SQLException void Close ( ) throws SQLException XXX getXXX( int index ) throws SQLException 204 Copyright 2008 by Patni Retrieving data from ResultSet String query = " SELECT name, age FROM student "; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("name"); BigDecimal n = rs.getBigDecimal("age"); System.out.println(s + " " + n); } The output will look something like this: Smith 20 Rahul 19 205 Copyright 2008 by Patni RowSets A RowSet object contains a set of rows from a result set or some other source of tabular data, like a file or spreadsheet. Because a RowSet object follows the JavaBeans model for properties and event notification, it is a JavaBeans component that can be combined with other components in an application 206 Copyright 2008 by Patni Types of RowSets JdbcRowSet: A connected scrollable ,updatable RowSet CachedRowset:A disconnected RowSet WebRowSet:A connected RowSet that uses the HTTP protocol internally to talk to a Java Servlet that provides data access 207 Copyright 2008 by Patni Inserting Data into Tables executeUpdate( ) throws SQLException Statement stmt = con.createStatement(); stmt.executeUpdate("INSERT INTO student " + "VALUES (1, 'Smith', ' Bombay' , 20, 7646234 ) )"; stmt.executeUpdate("INSERT INTO st_ course " + "VALUES (1, 1, 01-01-1999, 'Very Good' )"); 208 Copyright 2008 by Patni Updating Tables executeUpdate() Statement stmt = con.createStatement(); stmt.executeUpdate( "UPDATE course+ SET fees = fees+2000.00" ); 209 Copyright 2008 by Patni Using PreparedStatement PreparedStatement prep = con.prepareStatement( "UPDATE"+ " course values set fees = ? WHERE c-id = ?"); prep.setInt(1, 2); prep.setBigDecimal(2, 8000.00); prep.executeUpdate ( ); prep.setInt(1, 4); prep.setBigDecimal(2, 9000.00);prep.executeUpdate ( ); 210 Copyright 2008 by Patni DataSource and Connection Pooling DataSource:The JDBC 2.0 extension API introduced the concept of data sources, which are standard, general- use objects for specifying databases or other resources to use 211 Copyright 2008 by Patni What is a DataSource? A DataSourceobject is the representation of a data source in the Java programming language. In basic terms, a data source is a facility for storing data. It can be as sophisticated as a complex database for a large corporation or as simple as a file with rows and columns. A data source can reside on a remote server, or it can be on a local desktop machine 212 Copyright 2008 by Patni Applications access a data source using a connection, and a DataSourceobject can be thought of as a factory for connections to the particular data source that the DataSourceinstance represents What is a DataSource? 213 Copyright 2008 by Patni Comparison between DriverManager and DataSource While directly creating a connection by calling DriverManager.getConnection(..) , you are creating a connection by yourself and when closing close() on it, the link to database is lost. On the other hand we get a connection from a datasource, when you call the close() on it, it will not close the link to database, but will return to a connection pool where it can be reused by some other classes 214 Copyright 2008 by Patni Comparison between DriverManager and DataSource(Contd.) It is always better to use a connection pool because creating connections are expensive. DataSource has its usability in the distributed computing environment,as it can be used with JNDI lookups Another major advantage is that the Dat aSour ce facility allows developers to implement a Dat aSour ce class to take advantage of features like connection pooling and distributed transactions 215 Copyright 2008 by Patni Using Callable Statement String sql=execute getEmployes ? ; CallableStatement call=con.prepareCall(sql); call.registerOutParameter(1,Types.INTEGER); call.execute(); int val=call.getInt(1); System.out.println(There are +val + employees); 216 Copyright 2008 by Patni Using Transactions con.setAutoCommit(boolean commit) con.commit() con.rollback() try { con.setAutoCommit(false); // perform transactions con.commit() con.setAutoCommit(true); } catch (SQLException e) { con .rollback() ;} 217 Copyright 2008 by Patni Java Networking 218 Copyright 2008 by Patni Course Objectives Understand basic networking concepts and Java Networking API Develop simple Java Applications using some commanly used classes from java.net package in Java SDK Objective of the session is to understand the new features as brought in by J ava 5 as listed below. J 2SE 5.0 Design Themes Language Changes Generics & Metadata Library API Changes Concurrency utilities Conclusions and Resources 219 Copyright 2008 by Patni Networking Basics 220 Copyright 2008 by Patni Networking Basics Computers communicate over internet using protocols Transmission Control Protocol (TCP) User Datagram Protocol (UDP) Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 221 Copyright 2008 by Patni Transmission Control Protocol (TCP) A connection-based protocol that provides a reliable flow of data between two computers Guarantees data delivery from one end of the connection to the other , an error is reported otherwise Provides a point-to-point channel for applications that require reliable communications Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are examples of applications that require a reliable communication channel Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 222 Copyright 2008 by Patni User Datagram Protocol (UDP) Provides for communication that is not guaranteed between two applications on the network Is not connection-based like TCP Order of delivery of message is not important , and each message is independent of any other An example of a service that doesn't need the guarantee of a reliable channel is the ping command A reliable channel would invalidate this service altogether since it is to test the communication Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 223 Copyright 2008 by Patni Understanding Ports A complete destination network address for connection is made up of <ipaddress>:<port no.> Port number defines a virtual cannel for connecting to an application on the sever, where as the IP address merely defines which server to connect The computer is identified by its IP address, which IP uses to deliver data to the right computer on the network Ports are identified by a number, which TCP and UDP use to deliver the data to the right application Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 224 Copyright 2008 by Patni Understanding Ports In connection-based communication such as TCP, a server application binds a socket to a specific port number This has the effect of registering the server with the system to receive all data destined for that port In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 225 Copyright 2008 by Patni Understanding Ports Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services These ports are called well-known ports Your applications should not attempt to bind to them Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 226 Copyright 2008 by Patni Networking in Java 227 Copyright 2008 by Patni java.net package for networking The java.net Package defines the java classes for networking Through these classes in java.net, Java programs can use TCP or UDP to communicate over the Internet The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 228 Copyright 2008 by Patni java.net.URL The java.net.URL class represents Uniform Resource Locator URL j avasoft =new URL ("http://www.j avasoft.com/"); the above line , creates an java object for the url URL j avasoft =new URL ("http://www.j avasoft.com/pages/"); URL j avasoftGames =new URL (j avasoft, "J avasoft.game.html"); create URL object for the page http://www.javasoft.com/pages/javasoft.game.html Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 229 Copyright 2008 by Patni java.net.URL Each of the four URL constructors throws a MalformedURLException if the arguments refer to a null or unknown protocol try { URL myURL =new URL(. . .)} catch (MalformedURLException e) { . . . // exception handler} URLs are "write-once" objects, once you've created a URL object, you cannot change any of its attributes (protocol, host name, filename, or port number) Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 230 Copyright 2008 by Patni java.net.URL The URL class provides several methods that let you query URL objects String getProtocol() Returns the protocol identifier of the URL String getHost() Returns the host name of the URL int getPort() Returns the port number of the URL, 1 if not set String getRef() Returns the reference of the URL String getFile() Returns the filename of the URL These getXXX methods are used to get information about the URL regardless of the constructor that you used to create the URL object Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 231 Copyright 2008 by Patni java.net.InetAddress The InetAddress class encapsulates Internet addresses It supports both numeric IP addresses and host names The InetAddress class has no public variables or constructors Its methods support for common operations on Internet addresses static InetAddress getLocalHost() static InetAddress getByName(String host) byte[] getAddress() String getHostName() String getHostAddress() Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 232 Copyright 2008 by Patni Socket A socket is one endpoint of a two-way communication link between two programs running on the network A socket is bound to a port number on the server so that the TCP layer can identify the application that data is destined to be sent The server just waits, listening to the socket for a client to make a connection request The client knows the hostname of the machine on which the server is running and the port number to which the server is connected and makes the connection request accordingly Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 233 Copyright 2008 by Patni Socket 1 2 If connection is accepted, a new socket is created on the client side The client can use this socket to communicate with the server The client and server can now communicate read/write from their sockets Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 234 Copyright 2008 by Patni Socket and ServerSocket class java.net.Socket class implements client side of the connection java.net.ServerSocket class implements server side of connection URLs are a relatively high-level connection to the Web and use sockets as part of the underlying implementation Reading from and writing to a socket --- code example client,server Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 235 Copyright 2008 by Patni Socket and ServerSocket class java.net.Socket class methods for read/write InputStream getInputStream() Returns an input stream for this socket OutputStream getOutputStream() Returns an output stream for this socket java.net.ServerSocket class method to listen to client Socket accept() Listens for a connection to be made to this socket and accepts it Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 236 Copyright 2008 by Patni Datagram The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent datagram communication using UDP These classes help write Java programs that use datagrams to send and receive packets over the network DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called OOP was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called J ava 237 Copyright 2008 by Patni Security in Java 2 238 Copyright 2008 by Patni Course Objectives Introduce basic security concepts on Java platform Objective of the session is to understand the new features as brought in by J ava 5 as listed below. J 2SE 5.0 Design Themes Language Changes Generics & Metadata Library API Changes Concurrency utilities Conclusions and Resources 239 Copyright 2008 by Patni Java Security The original security model provided by the Java platform, known as the "sandbox" model. JDK 1.1 introduced the concept of a "signed applet. JDK 1.2 introduces a number of improvements over JDK 1.1 All code, regardless of whether it is local or remote, can be subject to a security policy. The security policy defines the set of permissions available for code from various signers or locations and can be configured by a user or a system administrator . The runtime system organizes code into individual domains. 240 Copyright 2008 by Patni JDK 1.2 Security Model 241 Copyright 2008 by Patni Cryptography Architecture The first release of the JDK Security API in JDK 1.1 introduced the Java cryptography architecture (JCA) JDK 1.1 Cryptography services an implementation of one or more digital signature algorithms message digest algorithms key-generation algorithms 242 Copyright 2008 by Patni Cryptography Architecture Java cryptography architecture (JCA) JDK 1.2 adds five more types of services Keystore creation and management Algorithm parameter management Algorithm parameter generation Key factory support to convert between different key representations Certificate factory support to generate certificates and certificate revocation lists (CRLs) from their encodings 243 Copyright 2008 by Patni Cryptography Architecture JDK 1.2 introduces certificate interfaces and classes for parsing and managing certificates Certificate Interfaces and Classes Certificate - is an abstraction for certificates that have various formats but important common uses CertificateFactory - is used to generate certificate and certificate revocation list (CRL) objects from their encodings X509Certificate - This abstract class for X.509 certificates provides a standard way to access all the attributes of an X.509 certificate. 244 Copyright 2008 by Patni Cryptography Architecture Key Management Classes and Interfaces KeyStore class - supplies well-defined interfaces to access and modify the information in a keystore, which is a repository of keys and certificates Key specification interfaces - which are used for "transparent" representations of the key material that constitutes a key 245 Copyright 2008 by Patni Cryptography- Security Related Tools JDK 1.2 introduces three new tools: The keytool is used to create pairs of public and private keys, to import and display certificate chains, to export certificates, and to generate X.509 v1 self-signed certificates and certificate requests that can be sent to a certification authority. The jarsigner tool signs JAR (Java ARchive format) files and verifies the authenticity of the signature(s) of signed JAR files. The Policy Tool creates and modifies the policy configuration files that define your installation's security policy 246 Copyright 2008 by Patni Applet Restrictions Most of the browsers installs a security manager, applets typically run under the scrutiny of a security manager Applets are not allowed to access resources unless it is explicitly granted permission to do so by the security policy in effect. To access system resources from an Applet, set up a Policy File to Grant the Required Permission using policytool command. 247 Copyright 2008 by Patni Code and Document Security If you electronically send someone an important document (or documents), or an applet or application to run, the recipient needs a way of verifying that the document or code came from you and was not modified in transit. Digital signatures, certificates, and keystores all help ensure the security of the files you send. 248 Copyright 2008 by Patni Code and Document Security (Contd ..) Digital Signatures - The basic idea in the use of digital signatures is as follows You "sign" the document or code using one of your private keys, which you can generate by using keytool or security API methods. That is, you generate a digital signature for the document or code, using the jarsigner tool or API methods. You send to the other person, the "receiver," You also supply the receiver with the public key corresponding to the private key used to generate the signature The receiver uses the public key to verify the authenticity of the signature and the integrity of the document/code. 249 Copyright 2008 by Patni Code and Document Security (Contd..) A receiver needs to ensure that the public key itself is authentic before reliably using it to check the signature's authenticity It is more typical to supply a certificate containing the public key rather than just the public key itself 250 Copyright 2008 by Patni Code and Document Security (Contd..) Certificates -A certificate contains A public key The "distinguished-name" information of the entity (person, company, or so on) whose certificate it is A digital signature. A certificate is signed by one entity, the issuer, to vouch for the fact that the enclosed public key is the actual public key of another entity, the owner. The distinguished-name information for the signer (issuer). Keystores - Private keys and their associated public key certificates are stored in password-protected databases called keystores 251 Copyright 2008 by Patni Thank you