Vous êtes sur la page 1sur 54

C++ : CUI GUI (Graphics) - Expensive Drawbacks : C++ suports Real World Programming.

Means one program can be used in another computer. But with in the Geographical Area. C++ doesn't support for Web and Enterprise Level Applications SOLUTION J A V A 1990 James Ghosling, Peter Smith Project Name : Elctronic Consumers or Project Name : Project Green Idea : Communicate with other systems in d. Designing using C++ Language 1991 Introduced a new Language called "OAK" OAK - Greek Latin word "Everything" 1993 1994 1995 First time GUI based WWW appeared onto the computers through APPLETS New Java Web Browser, to support for execution of APPLETS. Called as HotJava Renamed to JAVA Java is a country name. Located between North Korea and South Korea. JAva location is famous for exporting other parts of the world 1997 1998 Advanced Networking Concepts are Advanced GUI applications to make java Coffee Beans to improved Portable. and JSP' the worl

2000 Advanced Web Applications called Servlets s are introduced 2002 2003 Advanced Reusable Components called EJB's are introduced. Struts

2009

Android

Java Applications : CUI GUI Web Character User Interface Graphical User Interface Web applications

Mobile Mobile Devices Applications AI Artificial Intelligense

Java characterstics : 1. 2. 3. 4. 5. 6. 7. 8. 9. Simple Platform Independent Portable Robust or Faster Distributed Reliable and Scalable Multi Threaded Secured Compiler and Interpreter

Java Architecture : 1. Java File 2. Class File .java -> Compiler -> .class -> Interpreter -> Hardware Byte Code Byte Code = ASCII + UNICODE ENGLISH + Asian Languages 3. Java Virtual Machine (JVM) Components of JVM : 1. 2. 3. 4. Class Loader Starts the Execution engine Just In time Compiler Garbage Collection i. Reference Collectors ii. Tracing Collectors iii. Compacting Collectors

4. Application Programming Interface (API) .class Byte Code JVM API Java API

Harware Machine Code (0,1) Java Security Levels :

1. Compiler Level Security 2. Class Loader Security 3. Byte code Verifier Byte Code Verifier : 1. Checks for the Structure of the Programs 2. Checks for the validity of the Variables, Methods and es. Java Programming Constructs : 1. Variables Is a name, which holds a values Which can be changed during the Program executions. Every variable in Java, occupies into its respected memory x = 100; Types : a. Class Variables class a { var; } b. Instance Variables class A { for(a=0; { } } c. Local Variables class A { method() { var; } } d. Static Variables a = 100; a = 200 static a = 100; a = 100 2. Data Types : Defines the Type of data is being used. location Classnam

Types : i. Primitive or Fundamental Integer Group : byte short int long 1 2 4 8 Byte Bytes Bytes Bytes 0 0 0 0

Floating Point Group : float 4 Bytes .123456 double 8 bytes .123456 123456 Boolean Group : boolean 1 bit Character Group : char 2 Bytes null 0/1

ii. Abstract or Derived String 8 Bytes 3. Operators Operates on Operands Values of Variables

Operand : a + b i. UNARY a. unary

Operates on 1 - and ! a = 10 -a = 0-10= -10 a = true; !a = FALSE

b. increment c. decrement PRE int a = 10; ++a; 1. 2. 3. Faster a = 10 + 1; a = 11;

++ -POST int a = 10; a++; a = 10; a = 10 + 1; a = 11 Slower

Known ii. BINARY a. Arithmetic b. Assignment

Unknown Operates on >1 +, -, *, / and % = a = 10; b = a; c. ArithmeticAssignment +=, -=, *=, /=, %= a+=5 a-=5; a*=5; a/=5; a%=5; d. relational a a a a a = = = = = a a a a a + * / % 5 5; 5; 5; 5;

<, >, <=, >=

e. comparision == and != f. Logical && || ! g. Bit-Wise h. Shift i. Ternary &&, || and ! Both If any one Inversion or Reverse &, |, ^ and ~ <<, >>, >>> ?, :

(cond)?T-Stmts:F-Stmts; 4. Conditional Statements i. If Statements a. b. c. d. Simple If If ... Else Else If Ladder Nested If

ii. SWITCH .. CASE Statements Meu Driven with integers or rs 5. Looping Statements Loop : Repetition Depicts " REUSABILITY" i. WHILE ii. DO .. WHILE iii. FOR characte

6. Arrays Collection of Similar or Homogeneous elements under the same Data Type, referred by a common NAME. int a; 1 variable int a..z; 26 variables; int aa..az, ba..bx; 50 Variables int a1,a2...a50; int a[50]; i. Single Dimensional data-type var[size]; int a[10], b; data-type[size] var; int[10] a,b; data-type var[size] = {Elements}; int a[3] = {1,2}; int a[3] = {1,2,3}; int a[3] = {1,2,3,4}; data-type var[] = {Elements}; int a[] = {1,2}; 2 int a[] = {1,2,3}; 3 int a[] = {1,2,3,4}; 4 ii. Multi Dimensional data-type var[R][C]; int a[3][3], b; data-type[R][C] var; int[3][3] a,b; data-type var[R][C] = {Elements}; int a[3][2] = {1,2}; int a[3][3] = {1,2,3}; int a[3][2] = {1,2,3,4}; data-type var[][C] = {Elements}; int a[][2] = {1,2}; 2 int a[][3] = {1,2,3}; 3 int a[][2] = {1,2,3,4}; 4 Importance : [2^32] -> 2 GB - 4 GB [2^64] -> 20 GB - 40 GB [2^64][2^64][2^64] Ranges : int float chars 7. Functions or Methods Set of instructions to execute a specific task of the given program. Syntax : <Access> return-type Method-name() 0 to n-1 0 to n-1 0 to n-1, n (/0) 50 Variables

{ code; } Types : i. Non Parameterized <Access> return-type Method-name() { code; } ii. Parameterized <Access> return-type Method-name(param) { code; } Parameters can be called : a. By Value a 10 0x101 x 20 0x103 b. By Reference a 20 0x101 x 20 0x101 Method Overloading : Same Method name with different es in the same class. Signatures : 1. 2. 3. 4. Example : add(int , int) add(int, float) add(float, int) Name of the Methods Type of Paramters No of Parameters Order of the Parameters Signatur b 10 0x102 y 10 0x102 b 20 0x102 y 10 0x104

add(float, float) Method Overriding : Same method name with same parammeters in different classes while inheritance. class A { void Display() { S.o.p("Hi"); } } class B extends A { void Display() { S.o.p("Welcome"); } } 8. Accesses Permissions for acceptance or denying. Types : i. Specifiers Used on CLASSES

public Can be access all the properties to other classes. Open to alkl with in all FOLDERS private Only to that class. protected Only to the sub classes.

default Open to all with in the FOLDER Level ii. Modifiers Used on VARIABLES and METHODS

public Can be access all the properties to other classes. Open to alkl with in all FOLDERS private Only to that class. protected Only to the sub classes.

default Open to all with in the FOLDER Level static Constant, never changes the

values even after the program successfully completed final Stop overriding. To makes the variables static in the calling classes. Contains only the definition. No Implementation methods(); methods() { code; } Definition Implementation

abstract

native To call the other language like C, C++ methods into the current JRE. synchronized Sharing the same resource to the multiple, but allowing only one to access at a time. 9. Classes and Objects Class Collection of Objects class ClassName { } Rules : Every Ist character of each word should be in CAPITAL Letters StudentDetails Follows by all the Rules of Variables. Object Is an instance of a class, which exhibits a well defined behaviour of that class Object contains both variables and Methods. Calling Objects : ClassName ob = new ClassName(); new -> Allocates memory to the Objects

ClassName() -> Constructor, used for invoking the objects and initializing the member variables with the default

values obj.variables; obj.methods(); 10. Principles of OOPs : i. Encapsulation Hides the data and code for providing the security Hides only the unessentials. Can be done by using Accesses i.i. Abstraction Shows the essentials perspective of the viewer Can be done by using Methods and Objects ii. Inheritance Aquiring the properties from one to another One Super / Base / Parent class Which gives the properties Another Sub / Derived / Child class Which accepts the properties. Types : i. Single Inheritance a. Single Level A | B b. Multi Level A | B | C c. Heirarchical Level A | B C ii. Multiple Inheritance a. Multipath A | B

| D b. Hybrid A | B | D Properties can be derived into the Sub class by using keyword "extends" iii. Polymorphism Many Forms

Same fom exists more than one wither physically or Programmatically. Types : i. Static Physically Done by using Overloading Programmatically Done by using Objects

ii. Dynamic

11. Interfaces and Abstract classes : Abstract Classes : If a class contains one or more abstract methods or a class is declared as an abstract. Syntax : class A { abstract class A { abstract method1(); method1(); abstract method2(); method2(); method3() } { code; } class B extends A { method1() { code; } method2() { } }

} class B extends A { method1() { code; } method2() { } }

Drwabacks of abstract Classes :

i. Always it should be a PARENT CLASS. ii. Need to be written multiple times for multiple Sub Classes Interfaces : Prototype to the classes. Syntax : interface InterfaceName extends Interface { public return-type method(param); public return-type method(param); } To implement the abstract methods of an interface into any of the classes, we use a keyword "implements" class ClassName extends SuperClassName implements InterfaceName1, Interf aceName2..... { abstract methods() { Implementation; } } interface A { public void Disp1(); } interface B { public void Disp2(); } class C implements A, B C.java { public void Disp() { S.o.p("Ok"); } p s v m(String args[]) { C c = new C(); c.Disp(); } } 12. Exception Handling : Programs Compile Syntax Errors Execute Run time Errors or Exceptions. A.java

B.java

Exception : normal flow of execution

Is an abnormal termination of the program, which disturbs the

Heirarchy of Exceptions : Object | Throwable Exception | User defined Checked (Known) Checked Exceptions : i. ClassNotFoundException class ADD { } Add.java ADD.class Error Pre Defined | Unchecked (Unknonw)

class CALC { Add a = new Add(); } ii. MethodNotFoundException Display(); iii. InvalidArgumentException int add(int , int) int add('a',10.45); iv. IllegalAccessException private methods(); a.methods(); Unchecked Exceptions : i. ArithmeticException / 0 B.java A.java display();

ii. ArrayIndexOutOfBoundsException int a[3] = {1,2}; int a[3] = {1,2,3}; int a[3] = {1,2,4,5,6,7}; iii. ArrayStoreException int a[3] = {1, 'a'}; iv. NegativeArrayException int a[-3] = {1};

v. NullPointerException String s=""; S.o.p("this is String : "+s); ClassName obj; obj.method(); vi. NumberFormatException int add(int, int) int add("a","b"); To handle all the above or any other exceptions, we need Exception Handlers . Statements to Handle the Exceptions : i. TRY ii. CATCH iii. FINALLY Contains erroreneous code Handles the exceptions of TRY Whether an exception is rainsed or not in TRY, to do some statements Can Throw a single Exceptional Object. Used for User defined Exceptions Can Throw Multiple Exceptional Objects. Alternate for the TRY .. CATCH in methods

iv. THROW

v. THROWS

Syntax : try { try { code; finally stmts;

code; } } catch(ExceptionType obj) { { stmnts; } } try { code; } catch(ExceptionType obj) { stmnts; } finally { stmts; } Multiple Catch Blocks to TRY :

try { code; } catch(ExceptionType obj) { stmnts; } catch(ExeptionType obj) { } catch(ExceptionType obj) { } catch(Exception e) { } If the Exception in catch block at first catch, it shown a compile time error, UNREACHABLE CODE ERROR Nested Try .. Catch : try { code; try { code; } catch(ExceptionType e) { } } catch(Exception obj) { stmnts; } THROWS : Alternate for TRY .. CATCH. method-name() { try { code; } catch(ExceptionType obj) { } catch(ExceptionType obj) { } } or

method-name() throws ExceptionType, ExceptionType { code; } THROW : Used for User Defined Exceptions

class AgeException extends Exception { public String getMessage() { return "Invalid Age"; } } class MainAgeDemo { public void setAge(int age) { if(age < 13 || age > 30) throw new AgeException(); S.o.p("Age is : "+age); } p s v m(String args[]) { MainAgeDeme mad = new MainAgeDemo(); mad.setAge(20); mad.setAge(-20); } } 13. Conversions and Castings : Data type to Data Type conversion Conversion : When converting from one data type another data type which was compatible each other Types : i. Implicit or Widening Conversion : From LOW to HIGH priority data type. These are default process int a = 10; double d = a; 10.00

ii. Explicit or Narrowing Conversion : From HIGH to LOW priority data type. double d = 15.25; int i = d; Error

(type)var; int i = (int)d; Valid Castings : When converting from one data type another data type which are incompatible each other int i = 10; String s = i; "10"

String s = "10"; int i = s; Error int i = Integer.parseInt(s); 14. Super and This Keywords : Super : Refers the parent class Objects class SuperClassName { super-var; super-constructors() { } super-methods() { } } class SubClassName extends SuperClassName { super(); Constructor super.var; Variables super.methods(); Methods } This : Refers the Current class Objects class CurrentClassName { cur-var; int a, b; Class CurrentClassName() { this(params); } CurrentClassName(param) { } int add(int a, int b) Instance { this.a = a; this.b = b; } int mul(int x, int y) {

a = x; b = y; } } 15. Multi Threading : Software Application Program Instruction program Task Thread Coll of Application Coll of Programs sequence of instructions Small executable task of a given

In the system, the applications can be controlled in two ways : i. Process Based ii. Thread Based Processor takes care Programming thru

i. Single Processed ii. Multi Processed Advantages with the threads : i. Improved the performance ii. Simultaneous access on the resources. iii. Program structure simplification Pitfalls of threads : i. Race Condition ii. Lock Starvation iii. Deadlocks To create Multi Threading in JAVA, we take a support from the Parent class, java.lang.Thread class Syntax of Thread class : Thread t = new Thread(); Thread t = new Thread(String name); Thread t = new Thread(String, int priority); Thread t = new Thread(String, int, ThreadGroup tg); Methods : i. setName(String) Sets a name to the Thread

t.setName("Name"); ii. getName() Returns the name of the Thread

S.o.p(t.getName()); iii. setPriority(int priority) Specifies new priorities priorities : Default Thread.HIGH_PRIORITY Thread.NORM_PRIORITY Thread.LOW_PRIORITY Thread.HIGH_PRIORITY+10 Thread.HIGH_PRIORITY+15 A thread with HIGH priority always execute first. iv. getPriority() Returns the priority of the Thread v. start(); To start the execution of the given Thread object 10 5 0

t1.start(); t2.start(); t3.start(); t4.start(); vi. wait() To make the thread to be wait until the previous thread finishes its execution

t1.wait(); vii. notify() Which notifies the waiting threads for their executions

t1.notify() If the threads are N, notify() should be used for (N-1) times viii. notifyAll() Notifies all the Threads,n but the execution will be done on the bases of priority notifyAll(); ix. sleep(long ms) Makes the thread to be wait for a certain amount of duration t2.sleep(10*60*1000); After the specified amount of time finished, the Thread starts its execution by putting the previous thread in the Dead stage Life Cycle of threads :

i. New Stage : When the Thread is created for the Ist time, the Threads are in New Stage How to create Threads : a. By extending parent class "Thread" b. By implementing interface "Runnable" ii. Runnable Stage : Every created should be started for their execution by using start(). Then the Threads are in Runnable Stage. iii. Not Runnable : If the Threads are : a. Waiting for another thread to complete by using wait() method b. Waiting for another thread for a particular duration of time by using sleep() c. If the Thread blocked by another iv. Dead or Terminated Stage : If the Threads completed their execution normally or stopped by using stop() method. How to make Multi threads : i. isAlive() Returns the state of the Thread, means either DEAD or ALIVE

t1.start(); if(t1.isAlive() == false) { t2.start(); } if(t2.isAlive() == false) { t3.start(); } ii. join() another ChildThread : t1 Joins one thread object to

MainThreadClass c1 c2 c3 c1.t1.join();

c2.t1.join(); c3.t1.join(); How to create Threads : a. By extending parent class "Thread" class ChildThread1 extends Thread { ChildThread1() { super("Child-1"); start(); } public void run() { Running code; } } class ChildThread2 extends Thread { ChildThread2() { super("Child-2"); start(); } public void run() { Running code; } } class MainThreadClass { p s v m(String args[]) { ChildThread1 c1 = new Child1() ChildThread1 c2 = new Child1() } } b. By implementing interface "Runnable" class ChildThread implements Runnable { Thread t1, t2, t3; ChildThread() { t1 = new Thread("Child-1"); t2 = new Thread("Child-2"); t3 = new Thread("Child-3"); t1.start(); t2.start(); t3.start(); } public void run() { Running code; } } class MainThreadClass

{ p s v m(String args[]) { ChildThread c1 = new ChildThread(); } } 16. Packages Folder, which contains collection of classes and interfaces which are organized in a format. Steps to Create a Package : i. Create a program which contains the package definition. include "package" keyword in the beginning of the program package Package_Name; or package Package_Name.SubPackage; <access> class ClassName { code; } ii. Save and Compile the Program iii. Create the folders on the names of Package_Name and SubPackage iv. Copy .class files into the respected Folders. v. Execute the Sub Programs by creating Main Program in the parent Folder means starting folder or i. Create a program which contains the package definition. include "package" keyword in the beginning of the program package Package_Name; or package Package_Name.SubPackage; <access> class ClassName { code; } ii. Save these files in the parent folder. iii. Compile the programs by using following command javac -d . ClassName.java

or javac -d . *.java -d Create a directory on the name of Package_Name or SubPackage Identifies the Packages and Sub Packages

iv. Execute the Sub Programs by creating Main Program in the parent Folder means starting folder How to call packaged programs into Other programs : To call the programs of one package into another package, Ist of all the access should be PUBLIC To call them, we use "import" keyword. import Packa_Name.SubPack.ClassName; or import Packa_Name.SubPack.*; * calls all the ClassName.class files to the Other program In user defined packages, * can't work. To work explicitly, we should add these .class files to the CLASSPATH set CLASSPATH=%classpath%;Driver:\Folder\Fold; Pre Defined Packages : Types : i. java lang Before 1997 Contains all the necessary elements and classes supported to create Basic Java Programs Default package for all Java Programs. No need to import awt Supports to create GUI applications.

applet Support to create java enabled web applications called APPLETs util Supports for Java based Data Structures and All the Utilities programs Supports for read and write operations

io

net sql rmi

Supports for Networking applications Supoprts for Database applications Supports advance Netwokring applications called Remote Method Invocation After 1997 (x - eXtended) Supports for Advanced GUI and portable applications

ii. javax swing

servlet Supoprts for Advanced Web Applications and server side applications servlet.jsp Supports for creating Java Server Pages applications, an alternate to Servlets 17. java.lang package : Supports all the basic java programming elements. Classes : Object Is a parent for all other classes of Java. Making java as pure object oriented. Class Manages the classes and Objects created inside of a program

System Provides the system devices information like input, output and error devices System.in System.out System.err Math Input Output Error

Contains all the Mathmatical and Trignometric Methods or Operations Math.abs(-10) 10 Math.ceil(10.25) 11.00 Math.floor(10.25); 10.00 Math.round(12.49); 12.00 Math.max(1,2); 2 Math.min(1,2); 1 Math.pow(2,3); 8 Math.random(); 0.0 - 1.0

Wrapper Are the super classes for all the data types of Java int float double Integer Float Double

char

Character

String Handles the String operations length() String indexOf(char) Index of specified character inside the String Length of the given

lastIndexOf(char) Index of the character inside the String which located at last position equals(str) Checks the equality

equalsIgnoreCase(Str) Checks the equality by ignoring the cases toUpperCase() toLowerCase() trim() Convert to Upper case Converts to Lower case Removes the white spaces before and after the string

replace(old, new) Replaces the Character(s) with in the String substring(start, end) Finds the String in another String getChars(start, end) Returns the Character of a given String in char array hashCode() Converts into hash code

Exception Provides all the exceptional statements to handle the Runtime Errors Thread Support for multi Threading applications using java 19. Java.awt package : AWT Abstract Abstract Window Toolkit Only the definition with out any code

Window Support for GUI based Desktop apps Toolkit Tools support to design and develop GUI

apps Heirarchy of AWT : java.lang.Object | java.awt.Component | Containers | Panels | Applet Frame Component : Self contained software device, which can be plugged into any target applications

Components Levels : i. High Level or Containers Applet Are java enabled web applications, which execute only in java web browsers Frame Supports to create and design GUI based Window or Desktop applications

Dialog Are part of the Frame applications to display the messages. ii. Mid Level or Mid Containers : Panel To add the Low LEvel to High Level

iii. Low Level or Control Components : Label Used for displaying captions

TextField Used to accept an input from the end user in the format of Text Box TextArea Used to accept an input if it is in more than one line

Choice Accepts one item from given group of items Example : Select Country List Accepts one or multiple items from the given group of items Example : Education Qualifi Technical Skills

Checkbox

Used to accept one or more items from the given Example : Select Hobbies Select Gender To make checkbox items as a single unit.

CheckboxGroup

Menu

USed for designing Menus for GUI appls

MenuBar Place which contains multiple menus, and can be placed at top of the GUI applications MenuItem Items of each Menu.

Button Submitting the data to the database, or another applciations or to the file 19. javax.swing package : Differences between AWT and SWINGS : AWT SWING ---------------------------------------------------------------------------------------1. Components are heavy weight 1. Components are Light Weight during the load and execute durng the load and execute 2. LEssa No. of Components 3. No Pluggable Look And Feel (PLAF) 4. Sharp edges 2. Huge no of components 3. Contains PLAF 4. Rounded Edges

5. No images to all components 5. Images can be used for reliable components.] Heirarchy of Swings : java.lang.Object | javax.swing.JComponent | JContainers | JPanels | JApplet JFrame JComponent : Self contained software device, which can be plugged into any target applications

Components Levels :

i. High Level or Containers JApplet Are java enabled web applications, which execute only in java web browsers JFrame Supports to create and design GUI based Window or Desktop applications ii. Mid Level or Mid Containers : JPanel To add the Low LEvel to High Level JTabbedPane Container which can have their own sub containers called TABS, where each tab can contain many Components iii. Low Level or Control Components : JLabel Used for displaying captions JTextField Used to accept an input from the end user in the format of Text Box JTextArea Used to accept an input if it is in more than one line JComboBox Accepts one item from given group of items Example : Select Country JList Accepts one or multiple items from the given group of items Example : Education Qualifi Technical Skills

JCheckBox Used to accept multiple items from the given Example : Select Hobbies Select Gender JRadioButton Used to accept a single item from the given group of items ButtonGroup To make Button related items as a single unit. JMenu JMenuBar USed for designing Menus for GUI appls Place which contains multiple menus, and can be placed at top of the GUI applications

JMenuItem

Items of each Menu.

JButton Submitting the data to the database, or another applciations or to the file Extra Components of SWINGs : JPasswordField Represents for Passwords JFileChooser JColorChooser JOptionPane JScrollPane JTree JTable JSlider 20. java.util package : Util package contains all the utilities which are not necessary for basic programming. Data Structure : organized format of data in memory Drawbacks of an Arrays : i. Fixed size elements int a[3] = {1,2,3}; ii. Not easier for Data insertions, deletions and updations Insertions Deletions Queues Updation Maintain Linked Lists, Queues and Stacks Hashing Searching Techniques Sorting Techniques Classes : Linked Lists, Queues and Stacks Double Linked List, Stacks and Used for Open and Save As options Used for colors. Used for displaying Messages. It is an alternate for Dialogs Adds the Scroll bars to the GUI basing on kind of Applications Prepares the data in Tree format Foir Tabular format representation USed for sliding (Volume)

i. BitSet

Growable array of elements which contains the data in bit format

BitSet bs = new BitSet(); bs.add(10); i0000 1010 bs.add('a'); c0110 0001 ii. StringBuffer Advanced class to the Strings.

String s = "GIET "; s = s.trim() + ", Gunupur"; StringBuffer sb = new StringBuffer(s); sb.length(); 4 sb.capacity(); 4+16 sb.append(string) Adds the data at end sb.reverse(); s1 = MADAM I AM ADAM s2 = sb.reverse(s1); iii. StringTokenizer Devides the huge string into small parts called Tokens. String s = "This is an Example for String Tokenizer"; StringTokenizer st = new StringTokenizer(s, " "); int n = st.countTokens(); 7-1 while(st.hasMoreTokens()) { S.o.p(st.nextToken()); } iv. Arrays Super class for representing the arrays created inside the the Data Structure

int a[10] = {2,5,1,6,4,9}; Arrays.sort(a); Arrays.find(array, ele); v. ArrayList Maintains the collection of elements in Array format. which can contains duplicate values

ArrayList al = new ArrayList(); ArrayList<Type> al = new ArrayList<Type>(); al.add(elements); vi. HashSet Maintains the elements in the order of KEY and VALUE pair

HashSet hs = new HashSet(); hs.put(key, value)

hs.get(key); vii. Date Performs the current system date operations.

Date d = new Date(); S.o.p(d); IST d.getTime(); 23-07-2011 01-01-1970 --------------22-06-0041 12:30 PM 00:00 AM --------------12:30 Hours Sat July 2011 23 12:20:24 PM

41 * 365 * 24 * 60 * 60 * 1000 + 06 * 30 * 24 * 60 *60 *1000 + 22 * 24 * 60 * 60 *1000 + 12 * 60 *60 *1000 + 30 * 60 *1000 viii. Calendar Is an abstract class which contains the Date and Timing of the Local Zones Calendar cal = null; cal.getInstance(); YEAR MONTH MONTH_OF_YEAR DAY_OF_YEAR DAY_OF_WEEK S.o.p(cal.YEAR); 1

6+1 204 7

ix. GregorianCalendar Maintains the world wide dates and timings India USA Miami 23-07-2011 23-07-2011 22-07-2011 12:25:25 PM 01:55:25 AM 02:00:00 PM

GregorianCalendar gcal = new GregorianCalendar(); gcal.get(cal.YEAR); gcal.isLeapYear(cal.YEAR); Interfaces : i. Set Maintains the data with out duplicates ii. List Maintains the data with duplicates The above 2 interfaces are part of Collection Framework Framework : Coll of Classes and interface which use among them 2011 false

Collection | List Set | | ArrayList BitSet LinkedList SortedSet TreeSet HashSet Legacy Classes and Interfaces : The classes which are introduced from jdk 1.4 version onwards, called as Legacy Classes Vector Class Growable array which was replacement for max of classes of java.util package

Vector v = new Vector(); Vector v = new Vector(size, increment); Vector v = new Vector(10, 10); Methods : v.addElement(Object ele); v.insertElementAt(int index, Object ele); v.replaceElementAt(int index, Object ele); v.removeElementAt(int index); v.removeAll(); Enumeration Interface Generates the series of information Enumeration en = v.elements(); while(en.hasMoreElements()) { S.o.p(en.nextElement()); } java.io packages : IO Input and Output

How the data can be saved into the memory and then how this can maintained and manipulated. In C, C++ In C : FILE *fp;

In C++ fstream ifstream and ofstream Max supporting formats are .dat or .txt In Java.io packages Data can : File Used to create the files and Directories

inside the java File File File File Methods : i. exists() Returns the avaialability of the file for the later operations ii. isReadOnly() iii. size() iv. length() Returns true or false basing on the permissions of the file Returns the size of the file within the memory Returns the length of the content within the file Returs the last access date and f f f f = = = = new new new new File(); File("String filename.ext"); File("path\filename.ext"); File(directoryObject);

v. lastAccessed() time

vi. lastModified() Returns the last modified content date and time vii. createdOn() viii. getParent() file ix. getPath() Returns the date of creation. Returns the parent folder to the

Returns the complete Path of the file Returns the complete data of the

x. String[] list() File RandomAccessFile

Is a class which allows the users to perform write operations into the Files RandomAccessFile raf = new RandomAccessFile(); RandomAccessFile raf = new RandomAccessFile("String filename.ext", "mode"); File f = new File("path\filename.ext"); RandomAccessFile raf = new RandomAccessFile(f, "mode"); Modes : C C++ Java ------------------------------------------------------------------read r ios::in r write w ios::out w append a ios:app rw read+write r+ write+read w+

append+read truncate create

a+ ios::trunc ios::ate

Methods : i. writeBytes(string) Which wirtes the string data to the file in Bytes format raf.writeBytes("abcd"); ii. int length() raf.length(); iii. void seek(int) Setting and Finding out the specified location with in the file raf.seek(raf.length()); iv. getFilePointer() Returns the current file pointer with in the File raf.getFilePointer(); int SNo 1 2 21 3 4 File Operations : i. Byte format Streams Stream Flow of data between Source to Destination Types : a. InputStream Read the data from Common Methods : int read() Check the file pointer is reached to EOF string SName A B E C D int 16 SMarks 56 89 74 78 59 Returns the length of the file

while(is.read() != -1) { length++; } read(byte b[]) Reads the data from the file and keeps it into the Byte format byte b[] = new byte(10000);

System.in.read(b); String s = new String(b); S.o.p(s); read(byte b[], int offset, int length) Reads the data in byte format, from the specified location with the given length is.read(b, 0, 16); int mark(int nbyte) Sets the cursor in the specified location for the next read void reset() Resets the marked pointer location. So that the cursor positions will be set to beginning of the file (0) Close the opened file.

void close()

InputStream Classes : a. FileInputStream Reads the data from Specified File Location FileInputStream fis = new FileInputStream("filename.ext"); b. BufferedInputStream Reads the data from the File or any other input device, can be stored the dat inside the Buffer BufferedInputStream bis = new BufferedInputStream(new FileInputStream("filename.ext")); BufferedInputStream bis = new BufferedInputStream(System.in); c. DataInputStream Reads the exact data type data from the Specified File Streams or any i/p devices DataInputStream dis = new DataInputStream(new FileInputStream(Filename.ext)); DataInputStream dis = new DataInputStream(System.in);

Methods : readInt() readDouble(); readFloat() readUTF() Reads int data Reads double Read Float Reads String

b. OutputStream Writes the data to Common Methods : i. write(byte b[]) Writes teh byte formatted content to the file ii. write(byte b[], int offset, int length) Write the byte data to the file with the specified length and position iii. flush() write iv. close() Clears the buffer b4 the new to close the opened file

Ouput Stream Class : FileOutputStream BufferedOutputStream DataOutputStream ii. Binary Format Binary : Types : a. Readers Common Methods : int read() Check the file pointer is reached to EOF Reads the data from Character 0 or 1. Low level programming

while(is.read() != -1) { length++; } read(char b[]) Reads the data from the file and keeps it into the binary format char b[] = new char(10000);

System.in.read(b); String s = new String(b); S.o.p(s); read(char b[], int offset, int length) Reads the data in char format, from the specified location with the given length is.read(b, 0, 16); int mark(int nchar) Sets the cursor in the specified location for the next read void reset() Resets the marked pointer location. So that the cursor positions will be set to beginning of the file (0) Close the opened file.

void close()

Readers classes : FileReader BufferedReader b. Writers Common Methods : i. write(char b[]) Writes teh binary formatted content to the file ii. write(char b[], int offset, int length) Write the binary data to the file with the specified length and position iii. flush() write iv. close() Writer classes : FileWriter BufferedWriter PrintWriter Servlets Clears the buffer b4 the new to close the opened file Writes the data to

Serialization

Process of converting from Byte to Object and vice versa This is only in the case of providing the security to the data while transferring over the internet To implement this we use an interface 'Serializable'.

class A implements Serializable { } java.net packages : Networking Benefits : Group of computers interconnected together Sort of sharing the information

Sort of communication Java programming language by defaulted with networking features to make the data to be travelled over the network. 1997, advanced networking features are added to make java internet programming language Communicational Architectures : 1. 1-Tier or Traditional Approach : 1 - System Presentation Input and Output Business Logic Main Code Database Data Drawbacks : i. No communication ii. No data share iii. If any change in 1, need other two tho change 2. 2-Tier or Client/Server Approach : 1-System Client Presentation Business Logic Business Logic + Presentation Business Logic + Database => FAT CLIENT => FAT SERVER 2-System Server Database

To creaet client and server applications using java, we use a package java.net package How the Client and Server applications can be created: 1. IP Address Internet Protocol Address. To identify the systems opver the network. 32-bit(IPv4) or 64-bit (IPv6) 2^8 256 0-255 Govt Private Public Public Future Class A 0-127 N Class B 128-191 N Class C 192-223 N Class D 224-247 N Class E 248-255 2^8 256 0-255 H N N N 2^8 256 0-255 H H N N 2^8 256 0-255 H H H H

2. Port Numbers Service point of an Application Port Numbers Range : 0 - 65535 Valid Port Numbers : 0 - 9999 80 8080 23 25 69 21 1433 1521 3306 3. Protocols HTTP Web Servers Telnet - LINUX SMTP Telnet - UNIX FTP Ms SQL Oracle My SQL Set of Rules and Regulations for making better communication

HTTP Dynamic to Static SMTP FTP TCP/IP SNTP POP PPP WTP UDP ITP

4. DNS Domain Naming Service In network computers can be represented either numerically or names wise. 202.48.125.106 google.com Classes of java.net Package : InetAddress Used to retrive the IP Addresses

InetAddress inet = null; Methods : getLocalHost() Return local system IP Address getByName(name) Returns the IP Address of the specified name system getAllByName(name) available IP Addresses of the specified name system ii. Sockets Connecivity point. Returns all the

a. Client Socket Establisgh a connectivity to the Client Socket s = new Socket("Ip Address of Server", int port-number); Socket s = new Socket("172.24.1.1", 8080); b. Server ServerSocket Server side connectivity

ServerSocket ss = new ServerSocket(int port-number); ServerSocket ss = new ServerSocket(8080); Socket s = ss.accept(); ObjectInputStream getInputStream() ObjectOutputStream

getOutputStream(); URL Makes a communication to the system which are loated in some other geographical areas URL u = new URL("site-name"); URL u = new URL("http://www.google.com"); Methods : getPort() getProtocol() URLConnection Makes the URL connection to open and gets some information

URL u = new URL("site-name"); URLConnection uc = u.openConnection(); Methods : getPort() getProtocol() getLastAccessed(); getModified() getLength() toExternalForm(); who.is whois.net ADVANCED JAVA : JDBC database programs Java JDBC Softwares : Win XP Win 7 ----------------------------------JDK 1.6 JDK 1.6 Netbeans 6.5 Netbeans 6.5 MS SQL 2000 SQL 2005 Oracle XE Oracle XE My SQL My SQL Class.forName("driver-class"); MS SQL sun.jdbc.odbc.JdbcOdbcDriver MS Access -> Data -> Database

Java Database Connectivity

Oracle oracle.jdbc.driver.OracleDriver classes12.jar and ojdbc6.jar/ojdbc14.jar My SQL com.mysql.jdbc.Driver mysql-connector-java-5.1.6-bin.jar set classpath=%classpath%;C:\mysql-connector-java-5.1.6\mysql-connector-java-5.1 .6-bin.jar;. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:CSEB"); -> Acces s or Connection con = DriverManager.getConnection("jdbc:odbc:CSEB1", "sa", "p ass"); -> MS SQL Server or Connection con = DriverManager.getConnection("jdbc:oracle:thin:@SYSNAME/ localhost/IPAddress:1521:XE", "cseb", "cseb"); -> Oracle or Connection con = DriverManager.getConnection("jdbc:mysql://SYSNAME or lo calhost:3306/database", "root", "root"); -> My SQL } catch(Exception e) { } DSN : Datasource Name MS Control Panel

Control Panel -> Administrative Tools -> Datasources (ODBC) -> Add Access : Microsoft Access Driver (*.mdb) Name Description Select Button Select the location of Ms Access Databse located. SQL Server SQL Server -> Finish Name Description Server CSEB1 Optional SERVER_NAME or CURR_SYS_NAME or CSEB Optional

. NExt Authentication Type O windows NT v SQL Server Login Id Password Next Select default database Master -> ComboBox Next -> Finish SQL statements : DDL Data Definition Language CREATE Create a Structure ALTER Modifies the Structure DROP Remove the Structure frm Memory TRUNCATE Clears the Structure DML Data Manipulation Language UPDATE Modifiying the Data of Table DELETE Removes the data from the Table INSERT Adds the data to the Table DCL Data Control Language GRANT Permits the Permissions of Access REVOKE Denying the Permissions DQL Data Query Language SELECT Retrieves the data from the Table TCL Transaction Controlling Language COMMIT Makes permanent settings ROLLBACK Takes the cursor to recent original positions JDBC - SQL Statements L SQL Statements Methods Return Type ---------------------------------------sa pass

DDL DML DQL

execute()

boolean

executeUpdate() int executeQuery() ResultSet

if table created successfully -> false if table created unsuccessfully -> true JDBC SQL Statements : i. Statement Executes Simple SQL statements Class.forName() Connection con Statement st = con.createStatement(); DDL create table Students(Sno int, SName varchar(20), SMarks int) DML DQL insert into Students values(101, 'A', 99); select * from Students;

boolean b = st.execute("DDL") or int n = st.executeUpdate("DML"); or ResultSet rs = st.executeQuery("DQL"); ii. PreparedStatement Execute Prepared SQL Statements (pre defined) with place holders (?) Methods : prepareStatement(query); ps.setXXXX(int ?, Object val) int ? Number Object Values Example : PreparedStatement ps = con.prepareStatement(""insert into Studen ts values(?,?,?)); ps.setInt(1, no); ps.setString(2, name); ps.setInt(3, marks); int n = ps.executeUpdate(); iii. CallableStatement Execute Stored Procedures

Stored Procedures : Are part of server which maintain and maipulate the data of a table thru T-SQL Statements. Types : i. Without Parameters create procedure Proc_Name As SQL stmts i. With Parameters create procedure Proc_Name @sno int, @sname varchar(20) output as @sname = select sname from Students where sno=@s no; Syntax : CallableStatement cs = con.prepareCall("{call proc_name(?,?)}"); Output Parameters : cs.registerOutParameters(2, java.Types.DOUBLE); cs.setXXXX(int index, Object val); cs.getXXXX(int index); 1. 2. 3. 4. "" "{}" "{call proc_name}" "{call proc_name(?,?)}"

o/p update Students set smarks = smarks + 10 where smarks < @smarks; i/p cond i/p iv. ResultSet Interface : Used Retrieves the data of the tables. Used when the suer is using "select" query. Syntax : ResultSet rs = st.executeQuery("select query"); Methods : rs.next() Finds the next record availability the details in

specified

rs.getXXXX(int) Returns column

specified format

XXXX data

type

rs.getMetaData() Returns the complete information related to the table v. ResultSetMetaData Retrieves the details about the Tables. Syntax : ResultSetMetaData rsmd = rs.getMetaData(); Methods : rsmd.getColumnCount() Returns the Count of columns from the Table rsmd.getColumnName(int) Returns the Column Names of the Table CLASSPATH c:\Program Files\Java\jdk1.6.0_12\lib;C:\mysql-connector-java-5.1.6\mysql-connec tor-java-5.1.6-bin.jar;C:\OracleJARs\classes12.jar;C:\OracleJARs\ojdbc6.jar;C:\O racleJARs\ojdbc14.jar;. RMI : Remote Method Invocation Remote Other than Current systems Method Methodology to access the applications Invocation Calling or Invoking 1-Tier : Presentation Business Logic Database 2-Tier : Client Pres B.L B.L + Pres B.L + D.B B.L + Pres FAT CLIENT FAT SERVER FAT SERVER Server D.B

3-Tier or Component Based Approach : Client Pres HTML JSP ASP PHP Client Students Fund Application Server B.L Common Server D.B Orac MS SQL My SQL DB2 server Chairman Funds

A.S Dean RMI Registry

Server Socket Programming : Client Socket(s) 9 fields 1000 RMI Components : 1. RMI Server 2. RMI Client RMI Architecture : 1. Stub / Skeleton Layer 2. R.R.L 3. T.L Packages : 1. java.rmi Remote Interface Naming class RMISecurityManager 2. java.rmi.registry Registry Interface RegistryHandler Interface 3. java.rmi.server RemoteObject class RemoteServer class RemoteStub class UnicastRemoteObject class RemoteCall interface Skeleton interface Unreferenced interface 4. java.rmi.dgc Lease dirty() clean() Server ServerSocket 9 fields 1

Marshalling : Converting from the Known to Unknown format Unmarshalling : Convertes from Unknown to Known format. OSI : Appl Pres Sess Trans Net DL Phy Client 72 85 Naming Class : bind() Registers the objects for single time usage SERVER rebind()Registers the objects for Multi time usage unbind()unRegisters the objects from the server list() Displays the registered Objects CLIENT lookup() Makes a communication between the registered objects of the server and client Applications 2 create RMI Applications : 1. Remote Interface Abstract Methods import java.rmi.*; public interface InterfaceName extends Remote { public return-type method-name(params) throws RemoteException; } 2. Implmentation for Interface : Implementation for Abstract methods import java.rmi.*; import java.rmi.server.*; public class ImplClassName extends UnicastRemoteObject implements Interf Low level (0, 1) Request Object1 Object2 High Level (A, B)

aceName { ImplClassName() throws RemoteException { super(); } public return-type method-name(params) throws RemoteException { Implement - code; } } 3. RMI Server Rergisters the objects by using bind(), rebind() import java.rmi.*; import java.rmi.server.*; public class RMIServer { p s v m(String args[]) { InterfaceName obj = new ImplClassName(); } } 4. RMI client : Makes the reference to the server by using lookup() or 1. Remote Interface Abstract Methods import java.rmi.*; public interface InterfaceName extends Remote { public return-type method-name(params) throws RemoteException; } 2. Implmentation and RMI Server : Implementation for Abstract methods Rergisters the objects by using bind(), rebind() import java.rmi.*; import java.rmi.server.*; public class ImplClassName extends UnicastRemoteObject implements Interf aceName { ImplClassName() throws RemoteException { super(); } public return-type method-name(params) throws RemoteException { Implement - code;

} p s v m(String args[]) { ImplClassName obj = new ImplClassName(); Naming.rebind("InstanceName", obj); System.setSecurityManager(new RMISecurityManager()); } 3. RMI client : Makes the reference to the server by using lookup() import java.rmi.*; import java.rmi.server.*; { p s v m(String args[]) { InterfaceName obj = (InterfaceName)Naming.lookup("rmi:// System_IP/InstanceName"); obj.methods(); } } 4. Policytool : Start -> Run -> cmd type policytool -> Press Enter Click on Add Policy Entry Click on Add Permission Select All Permission -> Click on Ok -> Click on Done To save : Win XP

C:\Documents and Settings\CurrentUser Fist -> Save As -> locate filename : To save : .java.policy

Win 7

C:\Users\CurrentUser Fist -> Save As -> locate filename : .java.policy

5. Generate Stub and Skeleton files : rmic ImplClassName v 1.4 ImplClassName_stub.class ImplClassName_skel.class

6. Start RMI Registry start rmiregistry port-no start rmiregistry 1099 (Default) start rmiregistry 1234 (Userdef) 7. Start and Run RMI Server : start java RMIServer 8. Start and Run RMI Client : start java RMIClient Programs needed for client and server systems : CLIENT SERVER --------------------------------JVM JVM RemoteInterface RemoteInterface Client Server Impl_stub Impl_stub SERVLETS : Chair man Dean HOD Students JRE | Application Server | Web Container | Servlets JSP HTML Web components Servlet Interface : 1. GenericServlet Supports other than HTTP Protocols like FTP javax.servlet 2. HttpServlet Supports only the HTTP Protocol javax.servlet.http ServletConfig interface : Contains the confirgurational information about the type of servlets. ServletConfig cfg = getServeltConfig(); ClassName extends HttpServlet HttpServlet extends GenericServlet Server side programs

ClassName extends GenericServlet or ClassName extends Servlet Web Application <- Web Browsers Web Life Cycle IDE GUI main()

Integrated Development Environment Designing Developing Testing Deploying Netbeans 6.5 Eclipse My Eclipse Web Shpere JBoss

Life Cycle : public void init() { code; } GenerticServlets : public void service(ServletRequest req, ServletResponse res) { code; } HttpServlet : public void doGet(HttpServletRequest req, HttpServletResponse res) { code; } public void doPost(HttpServletRequest req, HttpServletResponse res) { code; } Client server -----uid String u=req.getParameter("uid"); & pwd String p=req.getParameter("pwd"); if(u and p are in DB) { }

skills Select Tech Skills C, C++, Java, Oracle, DB2, MS SQL, My SQL String skil[] = req.getParameterValues("skills"); <select name="skills"> <option>C <option>C++ </select> <select name="skills" multiple> <option>C <option>C++ </select> Enumeration en = req.getParameterNames(); while(en.hasMoreElements()) { req.getParameter(en.nextElement()); } Sys Name IP Addr req.getRemoteHost()l; req.getRemoteAddr() PrintWriter out = res.getWriter(); out.println(); out.print(); res.setContentType("text/plain"); res.setContentType("text/html"); res.setContentType("image/jpeg"); Context : Security, Session Management and Instance Persistance ServletConfig cfg = getServletConfig(); ServletContext ctx = cfg.getServletContext(); ctx.setAttribute("name", value); ctx.getAttribute("name"); Cricinfo : req.getHeader("refresh"); res.setHeader("refresh", "5; url=./Page.ext"); res.addHeader("refresh", "1; url=./Adv.ext"); Validation : if(u and p are in DB) { res.sendRedirect("HomePage.ext"); } else

{ res.sendRedirect("Login.html"); } session.setAttribute("name", value); session.getAttribute("name"); Diff B/w Ctx and Session : 1 ctx.setAttribute("1", "ok"); 2 ctx.getAttribute("1"); ctx.setAttribute("1", "ok"); 3 ctx.getAttribute("1"); ctx.setAttribute("1", "ok"); 1 session.setAttribute("1", "ok"); 2 session.getAttribute("1"); 3 session.getAttribute("1"); 4 session.getAttribute("1"); MIME Multi Interchange Mail Extension

Vous aimerez peut-être aussi