You are on page 1of 102

Programming in Java

TABLE OF CONTENTS
1.PROGRAMMING LANGUAGES 2.HISTORY OF JAVA 3.OPERATORS 4.INPUT & OUTPUT 5.CONTROL STRUCTURES 6.ARRAYS 7.CLASSES & OBJECTS 8.INHERITANCE 9.EXCEPTION HANDLING 10.PACKAGES & INERFACES 11.MULTITHREADING 12.STRING HANDLING 13.IO STREAMS 14.APPLETS 15.ABSTRACT WINDOW TOOLKIT (AWT) 16.EVENT HANDLING 17.SOCKET PROGRAMMING / NETWORKING 18.COLLECTIONS 3 5 10 12 13

32 36 59 65 72

Programming in Java

PROGRAMMING LANGUAGES
Languages used for programming Languages. writing programs are called

Programming Languages can be classified into 1.Procedure Oriented Languages 2.Object Oriented Languages PROCEDURE ORIENTED LANGUAGES In Procedure Oriented Languages the mere Concentration is on the procedure or process, leaving the data behind. The Data, which is more important than the process is left global or public, open for all and thereby giving a chance for illegal manipulation. Data moves freely through out the program. OBJECT ORIENTED LANGUAGES In Object Oriented Languages the concentration is on the object i.e., Data. Data is kept under tight security and process is build around it. FEATURES OF OBJECT ORIENTED PROGRAMMING STRUCTURE 1.Class A Class is central to any Object Oriented Programming Structure. A Class is collection of Data and Methods. It is only through class the concept of data security gets implemented in Object Oriented Language. 2.Object A Variable of class type is called an Object. 3.Data Encapsulation Data in a class is completely hidden from external access and data is bind to methods in such a way that data cannot be accessed without the permission of methods. 4.Data Abstraction Class provides the data without any background information or details. Data, Methods, Implementation of class is said to be abstract from outside the class, as these details are not revealed.

Programming in Java 5.Inheritance This is one of the key features of OOPS through which properties of class are used by other class. The idea behind inheritance is reusability. 6.Polymorphism Polymorphism means many forms. object having the capability behavior at different instances.

Here it refers to an to exhibit different

7.Dynamic Binding In a traditional language like C binding takes place during compilation itself. But incase any OOL binding will take place during program execution i.e., runtime called as Dynamic binding.

Programming in Java HISTORY OF JAVA In the year 1990 Patric Naughton started a secret project called green at sunn micro systems. His intention was to develop an embedded programming language. In the year 1992 they released a language called oak. Patric Naughton teamed up with James Goosling (Father of Java). At the same time Internet Server / WWW was in gaining popularity (beginning phases). This required a platform independent language. These people contacted sunn micro systems and In the Year 1995 Java was released. That is why java is used as a forefront programming language for Internet. FEATURES OF JAVA 1.Simple & Powerful Java includes no surprising features other than classes and objects. Java defines every thing in terms of classes and objects. Thats why it is called simple. As java was derived from oak (embedded lang) Java too has the features of interacting with hardware. So we call it to be powerful. 2.Secure Java is said to be free from virus. Java programs are always under the control of JVM (Java virtual Machine) and it is only JVM that can understand and run a java application or program. Java doesnt have anything like .exe which has the maximum chance of getting attacked by a virus. 3.Portable Java believes in WRITE ONCE EXECUTE ANYTIME ANYWHERE. The .class is executable on all platforms. 4.Robust Programming languages prior to Java faced problems due to Memory Management and Exceptions. Java developers made Java a ROBUST one by making java overcome these two problems. Java handles Memory with a special process called Garbage Collection, which keeps running in the background cleaning up all the unused space. Java deals with Exceptions using a technique called Exception Handling 5.Object Oriented Being a Object Oriented Language Java supports all the features of Object Oriented Programming Structure.

Programming in Java a)CLASS b)OBJECT c)DATA ENCAPSULATION d)DATA ABSTRACTION e)INHERITANCE f)POLYMORPHISM g)DYNAMIC BINDING 6.MultiThreaded Java being a multithreaded language uses threads to create sub process or child process and thereby uses the CPU time to the best. Threads provide the facility of dividing a process into sub processes or a program into sub programs. 7.Distributed Java has an in-built support for networking and developing distributed applications in java is quite simpler. (Need not depend on any third party) 8.Dynamic Prior to java Internet was using HTML, which is said to be a static content. HTML was replaced with applets. Applets are java programs that can run on a browser. Applets changed the static content of Internet to dynamic.

Programming in Java BASIC STRUCTURE OF A JAVA PROGRAM import statements; class <class-name> { public static void main(String args[]) { variable declaration; program logic } } STEPS TO RUN A JAVA PROGRAM 1.Open any Text Editor 2.Key in the program 3.save it as <class-name>.java 4.Compile javac <class-name>.java 5.Run java <class-name> A Java program is compiled and executed at the command prompt EXAMPLE: class MyClass { public static void main(String args[]) { System.out.println(WELCOME TO JAVA PROGRAMMING.); } } save it as MyClass.java open command prompt c:\Documents and settings\..> browse to source location c:\Documents and settings\..>cd\ c:\>cd java c:\java> compile is as javac MyClass.java c:\java>javac MyClass.java

Programming in Java run it as java MyClass c:\java>java MyClass

JVM ARCHITECTURE DATA TYPES INTEGERS Name long int short byte DECIMALS Name Width in Bits double 64 float 32 Approximate Range 4.9e324 to 1.8e+308 1.4e045 to 3.4e+038 Width Range 64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 32 2,147,483,648 to 2,147,483,647 16 32,768 to 32,767 8 128 to 127

CHARACTERS The Data type used to store characters is char. char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. LOGICAL Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false VARIABLES The variable is the basic unit of storage in a program. A variable is defined by the combination of an identifier, a type, and an optional initial value. In addition, all variables have a scope, which defines their visibility, and a lifetime. All variables must be declared before they can be used. <data-type> <variable> [=value]; int n; or int n=25; To declare more than one variable of the specified type, use a comma-separated list.

Programming in Java INPUT and OUTPUT KEYWORDS OF JAVA abstract assert boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

Programming in Java

OPERATORS
There are 5 types of operators. 1.Arthemetic Operators 2.Logical Operators 3.Relational Operators 4.Assignment Operators 5.Conditional Operator ARTHEMETIC OPERATORS These are to perform general mathematical calculations. These are classified into 2 categories 1.Binary Operators 2.Unary Operators BINARY OPERATORS These operate on Minimum 2 operands. OPERATOR + * / % MEANING Addition Substraction Multplication Division Modulus (mod)

UNARY OPERATORS These operate on one operand. OPERATOR ++ -MEANING Increment Decrement

LOGICAL OPERATORS These are to perform Logical calculations or evaluate logical expressions. OPERATOR && || ! MEANING AND OR NOT

10

Programming in Java RELATIONAL OPERATORS These are to check the relation between two operands. OPERATOR > < >= <= == != MEANING Greater than Less than Greater than or equal to Less than or equal to Equal to Not Equal to

ASSIGNMENT OPERATORS These are to assign value to a variable. OPERATOR = += -= *= /= %= MEANING Assignment a=a+b OR a+=b a=a-b OR a-=b a=a*b OR a*=b a=a/b OR a/=b a=a%b OR a%=b

CONDITIONAL OPERATOR These checks a condition and returns a value. ?: together is called conditional operator. (<condition>)?exp1/val1:exp2/val2 if the condition is true then it is exp1/val1 if the condition is false then it is exp2/val2 a=25 b=77 writing c=(a>b)?a:b assigns 77 to c.

11

Programming in Java

INPUT & OUTPUT

12

Programming in Java

CONTROL STRUCTURES
A program till now doesnt have any user control on them. Flow of Execution is not under user control. Control Structures are used to control the flow of the program. Control structures of 3 types 1.BRANCHING 2.LOOPING 3.SELECTION

BRANCHING
Branching includes a condition and 2 sets of statements. When the condition evaluates true then one set is executed and false then the other set is executed. Branching is implemented using IF statement

IF Statement
IF statement can be of 3 types. 1.Single line IF Statement 2.Multi line IF Statement 3.Nested IF Statement SINGLE LINE IF STATEMENT If(<condition>) { statements; } statements in the IF block are executed if the condition is true. MULTI LINE IF STATEMENT If(<condition>) { statements; } else { statements; } statements in IF block will be executed if condition is true and those in ELSE block will be executed if condition is false.

13

Programming in Java NESTED IF STATEMENT If(<condition>) { statements; If(<condition>) { statements; } else { statements; } } else { If(<condition>) { statements; } else { statements; } } If(<condition>) { If(<condition>) { statements; } } If(<condition>) { If(<condition>) { statements; } else { statements; } } else If(<condition>) { statements; }

14

Programming in Java else { statements; }

LOOPING
Loop is something that has its starting and ending points the same. Here looping refers to repeatedly executing a set of statements. Looping is implemented in Java using 1.While Statement 2.do-while Statement 3.for Statement

WHILE STATEMENT
initialization While(<condition>) { statements; increment/decrement; } int n; n=1; while(n<=10) { System.out.println(n); n++; }

DO-WHILE STATEMENT
Initialization do { statements; increment/decrement; } while (<condition>);

FOR STATEMENT
for(inititalization; condition; increment/decrement) { Statements; }

15

Programming in Java

for(n=1;n<=10;n++) { System.out.println(n); }

SELECTION
Choosing one option from several available options is called selection. Selection is implemented using SWITCH statement. switch(<variable>) { case <value 1> : statements; break; case <value 2> : statements; break; . . case <value n> : statements; break; [default : statements;] }

16

Programming in Java

ARRAYS
An Array is Collection of similar type of data. ARRAY DECLARATION 1.Single Dimension <datatype>[] <variable>=new <datatype>[<size>]; int[] n = new int[10]; <datatype> <variable>[]=new <datatype>[<size>]; int n[] = new int[10]; <datatype>[] <variable> <datatype> <variable>[] ={ values separated by comma};

int n[]={25,12,10,27,86,77}; 2.Multi Demension <datatype>[][] <variable>=new <datatype>[<dim1>][<dim2>]; int[][] n = new int[3][3]; <datatype> <variable>[][]=new <datatype>[<dim1>][<dim2>]; int n[][] = new int[5][4]; <datatype>[][] <variable> <datatype> <variable>[][] ={ values separated by comma};

int n[][]={{25,12,10},{27,86,77}}; Array is accessed using subscript value. (0 to (size-1))

17

Programming in Java

CLASSES & OBJECTS


CLASS OBJECT TYPES OF VARIABLES STATIC MEMBERS OF A CLASS CONSTRUCTOR Constructor is a special member function of the class that constructs the object. A Constructor builds the object i.e., Allocates Memory. Java provides one constructor with all classes. This is called as default constructor. The default constructor can build object in default manner i.e., object is not initialized. Hence, class using default constructor should have a method to initialize the object. USER DEFINED CONSTRUCTOR Java provides the facility to write user defined constructors. Using a user-defined constructor, creation of object can be customized. RULES FOR DECLARING & DEFINING A CONSTRUCTOR 1.A Constructor has same name as the class. 2.A Constructor cannot have return type (not even void). 3.A Constructor should be in the public section of a class. Note : Java withdraws its default constructor, as soon as a user-defined constructor is defined. CONSTRUCTOR OVERLOADING Having more than one constructor is said be constructor overloading or overloaded constructor. METHOD OVERLOADING Having more than one method with the same name is said to method overloading or overloaded method. In general call to a method will be resolved based on the method name, but in case of an overloaded method, call to method cannot be resolved based on method name as more than one method has the same name. So in case of an overloaded method call to a method will be resolved based on the argument list. Here the name of the method is said to be overloaded.

18

Programming in Java INNER CLASS / NESTED CLASSES Having a class definition inside other class is called Inner class or Nested classes. Inner class can increase the level of security. Inner class is treated as member by its enclosing class. Being a member of its enclosing class an inner class can access all the members of its enclosing class, including private members. An Inner class can be accessible through its object defined in its enclosing class. Class Outter { //outer class members class Inner { //inner class members } }

19

Programming in Java

INHERITANCE
This is one of the key features of OOPS through which properties of class are used by other class. The idea behind inheritance is reusability. The class that shares its properties (Data & Methods) with other class is called BASE / PARENT / SUPER class. The class that shares properties from other class is called DERIVED / CHILD / SUB class. TYPES OF INHERITANCE 1.Single Level Inheritance Inheritance implemented upto one level i.e., having only one base and one derived class is Single Level Inheritance. 2.Multi Level Inheritance Inheritance implemented beyond single level is Multi Level Inheritance. This type of inheritance has atleast one class that behaves as both base and derived class. 3.Multiple Inheritance Inheriting the properties from more than one class or having more than one parent class is said as Multiple Inheritance. NOTE :- JAVA doesnt support Multiple Inheritance. 4.Hierarchial Inheritance Having more than one derived class or when inheritance follows some hierarchical structure like every parent has two children is said to be hierarchical Inheritance. 5.Hybrib Inheritance When the structure of inheritance implemented is combination of more than one type of inheritance then it is said as Hybrid Inheritance. INHERITING A CLASS Properties of a class are inherited using the keyword extends as follows. Class <class-name> { //class definition }

20

Programming in Java class <class-name> extends <class-name> { //class definition } Class A { //class definition } class B extends A { //class definition } ORDER OF INVOKING CONSTRUCTORS Invoking the constructor of the derived class (creating object) always invokes the base class constructor. As derived class uses the properties of the base class, base class instance should be available for derived class, invokes base class constructor first to create an instance of base class. METHOD OVERRIDDING Having the same method signature in both the parent and child classes is called as method overriding. The Parent class method is overridden by the child class method. Call to an overridden method always invokes the child class version. NOTE: A variable of base class can refer to derived class instance. The keyword SUPER The keyword super is used to refer to the base class from derived class. super can be used to invoke base class constructors, data & methods. super.<method-name> (calling member functions) super.<variable> (calling data members) super([arguments]) (calling constructors) NOTE : Initializing a derived class (creating object) always invokes the base class constructor, initializing the base class(implicit). Here it is always the default constructor of the base class that gets invoked. Super is used to invoke other than default constructor.

21

Programming in Java

The keyword FINAL The keyword final is to finalize the methods, variables and class. A final member function cannot be overridden, A final data member cannot be modified, a final class cannot be inherited. ABSTRACT CLASS A class having atleast one abstract method (declared & not defined) is called as abstract class. An Abstract class cannot be instantiated i.e., objects cannot be created for an abstract class. Abstract classes are used as common base classes. A class that inherits an abstract class must override all the abstract methods of that class, failing, the class has to be declared as abstract. The keyword abstract is used to declare abstract methods and classes.

22

Programming in Java PACKAGES AND INTERFACES A package is collection of classes and interfaces.

23

Programming in Java

EXCEPTION HANDLING
The two most common type of errors are syntax and logical errors. syntax errors arise due to poor understanding of the language. logical errors occur due poor understanding of the problem. Other than logical and syntax errors we come across some peculiar problems called Exceptions. Exceptions are runtime errors. Errors that arise when the program is executing. Accessing etc.., an array out of bounds, division by zero,

Java exception handling is managed using five keywords: try, catch, throw, throws and finally.

Try
the keyword try is to enclose a block of statements in which there is a chance of exception to raise or a try block indicates the java runtime system to try the statements within the try block for exception handling.

Catch
the keyword catch is catch the exception thrown from the try block. catch block encloses the exception handling statements. catch block takes an exception object as argument that specifies what type of exception will be handled by the catch block. catch block has to immediately follow a try block. one try block can have multiple catch blocks.

Throws
The keyword throws is to throw an exception out of a method or class. This is generally done when user is not interested in exception handling or doesnt know how to handle exceptions. This is the minimum thing that has to be done when an exception arise.

Throw
System-generated exceptions are automatically thrown by the Java run-time system. the keyword throw is to manually throw an exception.

24

Programming in Java

Finally
The keyword finally is to enclose statements that have to be executed or done for sure under any circumstances before the program terminates. This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch(ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch(ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed } Here, ExceptionType is the type of exception that has occurred. Exception can be of 2 types 1.System Defined 2.User Defined List of some System Defined Exceptions

Exception & Meaning


1.ArithmeticException Arithmetic error, such as divide-by-zero. 2.ArrayIndexOutOfBoundsException Array index is out-of-bounds. 3.ArrayStoreException Assignment to an array element of an incompatible type. 4.ClassCastException Invalid cast. 5.IllegalArgumentException Illegal argument used to invoke a method.

25

Programming in Java

6.IndexOutOfBoundsException Some type of index is out-of-bounds. 7.NegativeArraySizeException Array created with a negative size. 8.ClassNotFoundException Class not found. 9.CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. 10.IllegalAccessException Access to a class is denied. 11.InstantiationException Attempt to create an object of an abstract class or interface. 12.InterruptedException One thread has been interrupted by another thread. 13.NoSuchFieldException A requested field does not exist. 14.NoSuchMethodException A requested method does not exist. 15.NullPointerException Invalid use of a null reference. 16.NumberFormatException Invalid conversion of a string to a numeric format. 17.StringIndexOutOfBounds Attempt to index outside the bounds of a string. 18.UnsupportedOperationException An unsupported operation was encountered.

26

Programming in Java

CLASS HIERARCHY
Object Throwable Exception RuntimeException

Error

Methods
1.String getMessage() Returns a description of the exception. 2. void printStackTrace() Displays the stack trace.

NESTED TRY & CATCH USER DEFINED EXCEPTIONS

27

Programming in Java

MULTITHREADING
A Task is a work being done. Multitasking is having more than one task at a time. Multitasking can be of two ways 1.Process Based Multitasking 2.Thread based Multitasking PROCESS BASED MULTITASKING A process is, in essence, a program that is executing. process-based multitasking is the feature that allows your computer to run two or more programs concurrently. Process based Multitasking is said to heavy weight as each process requires it own separate memory address space and inter process communication is limited or expensive. The smallest unit of code that can be dispatched by the scheduler in a process based multitasking environment is a process. THREAD BASED MULTITASKING Thread based Multitasking is said to be a lightweight as threads dont require separate memory address space and inter thread communication is inexpensive. The smallest unit of code that can be dispatched by a scheduler in a thread based multitasking environment is a thread. A Thread is a line of Execution. A Thread is a part of a program or a process. Using threads a process or a program can be divided into sub-program or sub-process. Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. Multithreading lets you gain access to this idle time and put it to good use.

THREAD STATES / THREAD LIFE CYCLE


1.Ready 2.Running 3.Suspended 4.Dead

28

Programming in Java

READY

start()

suspend()/wait()/sleep()

RUNNING
run()

resume()/ D notify()/notifyAll() stop()

SUSPENDE

stop()

DEAD

1.Ready

: A Thread is said to be in ready state when it is just created and not yet started executing. Thread is created and ready for execution.

2.Running : A Thread is said to be in running state when it is executing. A Thread in ready state is sent to running state by invoking start() on the thread. 3.Suspended : A Thread is said to be in suspended state when its execution has been temporarily halted. A Thread in running state can be suspended by invoking sleep(), wait() or suspend() on the thread. A Thread that has been suspended can be resumed by invoking notify(),notifyAll() or resume() on the thread.

4.Dead

: A Thread thats done is killed or terminated. A Thread invokes run() to be done. When A Thread in suspended state cannot be resumed it can be killed by invoking stop(). A Thread ready state can also be killed by invoking stop() on the thread.

IMPLEMENTING THREADS Threads are implemented in java in 2 ways. 1.using the Runnable interface 2.using the Thread class The Runnable Interface Implementing threads using the Runnable interface is a simple task. The Runnable interface has only one abstract method run(), and overriding this is sufficient. public void run();

29

Programming in Java The Thread Class The Thread class is used properties of thread. All thread are methods of the life-cycle methods, Thread get & set the properties of

to create and manipulate the the life-cycle methods of a Thread class. Along with the class also defines methods to a thread.

CONSTRUCTORS 1.Thread(): creates a Thread with default values. 2.Thread(String name) : creates a Thread with the specified name. 3.Thread(Runnable object, String name) : creates a thread for the specified Runnable instance. 4.Thread(ThreadGroup TG, String name) : creates a thread with the specified group & name. METHODS 1.start() 2.run() 3.stop() 4.suspend() thread. 5.resume() 6.wait(long millisec) 7.sleep(long millisec) 8.notify() 9.notifyAll() 10.join() 11.getName() 12.setName(String name) 13.getPriority() : invokes the run() : defines the thread. : kills a thread. : suspends the execution of a : resume a suspended thread. : makes a thread to wait for the specified number of milliseconds : makes a thread to sleep for the specified number of milliseconds

: notifies a thread that is waiting/sleeping : notifies all threads that are waiting or sleeping. : makes a thread to wait until all other have finished. : returns the name of the thread. : specifies the name for a thread.

: returns the current priority of thread.

30

Programming in Java 14.setPriority(int priority) 15.currentThread() : specifies the priority for a thread. : returns a thread, reference of the current thread. an asynchronous behavior in dead locks. A dead lock is a keeps waiting continuously on one of the thread responsible A B C

DEAD LOCKS Multithreading introduces programs. This results in situation where a thread other thread. Killing any for it can solve dead Lock.
A waits for B & B waits for C C waits for A.

SYNCHRONIZATION Synchronization is a technique to ovoid deadlocks. Synchronization specifies only one thread at a time. When a thread is accessing a resource, carrying out a task, any other thread will not be given control or access of the same. Synchronization is implemented using the keyword synchronized. Synchronization can be implemented in two ways. Using synchronized methods Using synchronized statements

1.USING synchronized METHODS class Callme { synchronized void call(String msg) { ... } 2.USING synchronized STATEMENTS synchronized(object) { // statements to be synchronized }

31

Programming in Java

STRING HANDLING
Java performs most of the read and write operations using strings. A String is a collection of characters (character array). Strings are represented in java as objects of String class. String Handling is done in Java using 1.The STRING class 2.The STRINGBUFFER class The String Class String class objects are fixed length character sequences. String objects are implicit. Changing the content of a String object always creates a new instance. CONSTRUCTORS String class provides 5 constructors. 1.String(String S) String S = new String(NaveenChandraPagadala); 2.String(char[] c) char name[] = {N,A,V,E,E,N}; String S = new String(name); 3.String(char[] c, int start, int end) char name[] = {N,A,V,E,E,N}; String S = new String(name,1,3); 4.String(byte[] b) byte b[] = {25,12,77,27,10,86}; String S = new String(b); 5.String(byte[] b, int start, int end) byte b[] = {25,12,77,27,10,86}; String S = new String(b,2,5); METHODS

1) int length() : returns length of the String. 2) char charAt(int index) : returns char at the index. 3) void getChars(int start, int end, char[] target, int
index) : returns chars from the String, placed into target.

32

Programming in Java

4) void getBytes(int start, int end, byte[] target, int


index) : returns bytes from the String, placed into target.

5) char[] toCharArray() : returns a char[] from the


String.

6) boolean equals(String) : checks whether the Strings


are equal are not.

7) boolean equalsIgnoreCase(String) : checks ignoring


case.

8)

boolean regionMatches(int start,String S,int start,int n) matches a region of a String with other.

9) boolean

regionMatches(boolean ignorecase, int start,String S,int start,int n) : matches a region of a String with other, ignoring the case. boolean startsWith(String str,[int pos]) checks whether the String starts with str or not. :

10)

11) 12) 13) 14) 15)

boolean endsWith(String str) : checks whether the String ends with str or not int CompareTo(String S2) : Compares String with S2 and returns 0 if equal and non-zero if not equal. int indexOf(char C/String S,[int start]) returns the index of the char in this String. :

int lastIndexOf(char C/String S,[int start]) : returns the last index of char in this String. String substring(int start extracts a portion of a String. [,int end]) :

16) 17)

String replace(char from, char to) : replaces a char from this String (from) with char (to). String String. concat(String S) : joins S to this

33

Programming in Java

18)

String trim() : removes white spaces before and after String. String toLowerCase() : converts the String to lower case. String toUpperCase() : converts the String to upper case.

19) 20)

The StringBuffer Class This is a peer class of String class that provides much of the functionalities of String class. String class represents fixed length character sequences & StringBuffer class represents varied length character sequences. Hence sub strings, characters can be added to a StringBuffer object at the end or can be inserted in between. CONSTRUCTORS 1.StringBuffer() : creates a StringBuffer Object with a length of 16 characters. StringBuffer S=new StringBuffer(); 2.StringBuffer(int size): creates a StringBuffer object with specified size. StringBuffer S=new StringBuffer(25); 3.StringBuffer(String S) : creates a StringBuffer object with the given string and the length of the object will be (size of S + 16 ) StringBuffer S=new StringBuffer("Naveen"); METHODS 1.length() : returns length of the Object. int l = S.length(); 2.setLength() : sets length of the object. Length is either increased or decreased. S.setLength(25); 3.capacity() : returns capacity of the object. StringBuffer S = new StringBuffer("Naveen"); S.length() returns 6 S.capacity() returns 22 (6+16)

34

Programming in Java 4.ensureCapacity(int capacity) : guarantees that object contains capacity number of characters atleast. 5.append(String S/Char C) : appends the string or char to this String. Not only string & char almost all data types can be appended or inserted. 6.insert(int index, String S/Char C) : inserts string or char at the specified index. 7.charAt(int index) : returns char at index 8.delete(int start, int end) : delete substring specified by start and end positions from object. 9.deleteCharAt(int index) : deletes char at index. 10.getChars(int srcBegin, int srcEnd, char[] dest, int dest-index) returns chars from srcBegin to srcEnd, stored into dest[] from dest_index. 11.indexOf(String) returns index of object. 1st occurrence of string in the

12.indexOf(String S, int start) returns index of 1st occurrence of S in this String from the given start position. 13.lastIndex(String S) returns last index of S in this String. 14.reverse() reverse contents of this String. 15.substring(int start, int end) returns sub-string specified positions. 16.setCharAt(int index, char c) replaces char at index with c. by start and end

35

Programming in Java

INPUT & OUTPUT STREAMS


Stream : Stream is a sequence of bytes. Streams can be used with almost all types of Input and Output devices. A stream is a flow into which any input device can write data and from which any output device can read data. Streams are flexible. Java uses Streams to handle Input and Output. Java further classifies STREAMS into 1.Byte Streams 2.Character Streams

FILE
Although most of the classes defined in java.io operate on Streams, File class does not. It deals directly with files and file-system. File class does not specify how information is retrieved from or stored to files. It describes properties of file itself. A File object is used to obtain or manipulate information associated with a disk file (permissions, time, date, directory path)

CONSTRUCTORS
1.File(String directory-path) File f=new File("E:\pagadala\Myclass.java"); 2.File(String directory-path, String filename) File f=new File("E:\pagadala","Myclass.java"); 3.File(File dirObj, String filename) File f=new File("E:\pagadala"); File file=new File(f,"Myclass.java");

Methods
1.boolean canRead() Tests whether the application denoted by this File. can read the file

2.boolean canWrite() Tests whether the application can modify the file denoted by this File. 3.boolean delete() Deletes the file or directory denoted by this File. returns true on success.

36

Programming in Java

4.boolean exists() Tests whether the file denoted by this File exists. 5.String getAbsolutePath() Returns the absolute string. pathname of this File as

6.String getName() Returns the name of the file or directory denoted by this File. 7.boolean isDirectory() Tests whether the file denoted by this File is a directory. 8.boolean isFile() Tests whether the file denoted by this File is a normal file. 9.boolean isHidden() Tests whether the hidden file. file named by this File is a

10.long lastModified() Returns the time the file denoted by this File was last modified. 11.long length() Returns the length of the file denoted by this File. 12.String[] list() Returns an array of strings, names of the files and directories in the directory denoted by this File. 13.boolean mkdir() Creates the directory named by this File. returns true on success. 14.boolean renameTo(File dest) Renames the file denoted by this File to a file denoted by dest File.

37

Programming in Java

THE BYTE STREAM


The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte stream can be used with any type of object, including binary data. This versatility makes byte streams important to many types of programs. All the Byte Stream Classes InputStream and OutputStream. are sub classes of

InputStream InputStream is an abstract class that defines Javas model of streaming byte input. All of the methods in this class will throw an IOException on error conditions.

Methods
1.int available() Returns the number of available for reading. bytes of input currently

2.void close() Closes the input source. Further read attempts will generate an IOException. 3.void mark(int numBytes) Places a mark at the current point in the input stream that will remain valid until numBytes bytes are read. 4.boolean markSupported() Returns true if mark()/reset() are supported by the invoking stream. 5.int read() Returns an integer representation of the next available byte of input. 1 is returned when the end of the file is encountered. 6.int read(byte b[]) Attempts to read up to b.length bytes into buffer and returns the actual number of bytes that were successfully read. 1 is returned when the end of the file is encountered. 7.int read(byte b[],int start, int numBytes) Attempts to read up to numBytes bytes into buffer starting at b[start], returning the number of bytes

38

Programming in Java successfully read. 1 is returned when the end of the file is encountered. OutputStream OutputStream is an abstract class that defines streaming byte output. All of the methods in this class throw an IOException in the case of errors.

Methods
1.void reset() Resets the input pointer to the previously set mark. 2.long skip(long numBytes) Ignores i.e., skips numBytes bytes of input, returning the number of bytes actually ignored. 3.void close() Closes the output stream. Further will generate an IOException. write attempts

4.void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. 5.void write(int b) Writes a single byte to an output stream. 6.void write(byte buffer[]) Writes a complete array of stream. bytes to an output

7.void write(byte b[],int start, int numBytes) Writes a subrange of numBytes bytes from the array b, beginning at b[start].

List of Byte Stream classes


1.FileInputStream 2.FileOutputStream 3.ByteArrayInputStream 4.ByteArrayOutputStream 5.BufferedInputStream 6.BufferedOutputStream 7.PushbackInputStream 8.SequenceInputStream 9.PrintWriter 10.RandomAccessFile

39

Programming in Java FileInputStream The FileInputStream class creates an InputStream that you can use to read bytes from a file. Constructors 1.FileInputStream(String filepath) 2.FileInputStream(File fileObj) Either throws FileNotFoundException. FileInputStream fis=new FileInputStream("G:\\pagadala\\Myclass.java"); File F=new File("G:\\pagadala\\Myclass.java"); FileInputStream fis=new FileInputStream(F); FileOutputStream FileOutputStream creates an OutputStream can use to write bytes to a file. that you

Constructors 1.FileOutputStream(String filePath) 2.FileOutputStream(File fileObj) 3.FileOutputStream(String filePath, boolean append) 4.FileOutputStream(File fileObj, boolean append) throws a FileNotFoundException or a SecurityException FileOutputStream fos = new FileOutputStream("G:\\pagadala\\naveen.txt"); File F=new File("G:\\pagadala\\naveen.txt"); FileOutputStream fos=new FileOutputStream(F); FileOutputStream fos=new FileOutputStream("G:\\pagadala\\naveen.txt",true); File F=new File("G:\\pagadala\\naveen.txt"); FileOutputStream fos=new FileOutputStream(F,true);

40

Programming in Java PROGRAM TO DEMOSTRATE FILEOUTPUTSTREAM import java.io.*; class FOutStream { public static void main(String args[]) { try { String msg="Naveen Chandra Pagadala"; byte[] b=msg.getBytes(); File F=new File("E:\\naveen.txt"); FileOutputStream fos=new FileOutputStream(F); fos.write(b); fos.close(); } catch(FileNotFoundException FNFE) { System.out.println(FNFE.getMessage()); } catch(IOException IOE) { System.out.println(IOE.getMessage()); } } } PROGRAM TO DEMOSTRATE FILEINPUTSTREAM import java.io.*; class FInStream { public static void main(String args[]) { try { //File F=new File("E:\\naveen.txt"); File F=new File("FInStream.java"); FileInputStream fis=new FileInputStream(F); int len=fis.available(); byte[] b=new byte[len]; fis.read(b); for(int i=0;i<b.length;i++) System.out.print((char)b[i]); fis.close();

41

Programming in Java } catch(FileNotFoundException FNFE) { System.out.println(FNFE.getMessage()); } catch(IOException IOE) { System.out.println(IOE.getMessage()); } } } SequenceInputStream The SequenceInputStream class allows you to concatenate multiple InputStreams. The construction of a SequenceInputStream is different from any other InputStream. A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of InputStreams as its argument. Constructors 1.SequenceInputStream (InputStream first, InputStream second) 2.SequenceInputStream (Enumeration streamEnum) PROGRAM TO DEMONSTRATE SEQUENCEINPUTSTREAM import java.io.*; class SequenceInputStreamDemo { public static void main(String Exception { int c; FileInputStream fis1=new FileInputStream("autoexec.bat"); FileInputStream fis2=new FileInputStream("config.sys"); SequenceInputStream input = new SequenceInputStream(fis1,fis2); while((c=input.read())!=-1) {

args[])

throws

42

Programming in Java System.out.print((char)c); } input.close(); } } autoexec.bat prompt $p$g config.sys set winbootdir=c:\windows OUTPUT prompt $p$g set winbootdir=c:\windows RANDOM ACCESS FILE RandomAccessFile encapsulates a random-access file. It is not derived from InputStream or OutputStream. Instead, it implements the interfaces DataInput and DataOutput, which define the basic I/O methods. It also supports positioning requeststhat is, you can position the file pointer within the file. Constructors 1.RandomAccessFile(File fileObj, String access) throws FileNotFoundException 2.RandomAccessFile(String filename, String access) throws FileNotFoundException In both cases, access determines what type of file access is permitted. If it is r, then the file can be read, but not written. If it is rw, then the file is opened in read-write mode. If it is rws, the file is opened for read-write operations and every change to the files data or metadata will be immediately written to the physical device. If it is rwd, the file is opened for read-write operations and every change to the files data will not be immediately written to the physical device. The method seek() is used to set the current position of the file pointer within the file.

43

Programming in Java void seek(long newPos) throws IOException Here, newPos specifies the new position, in bytes, of the file pointer from the beginning of the file. After a call to seek(), the next read or write operation will occur at the new file position. The Method getFilePointer() returns an int indicating the current position of the File Pointer int getFilePointer() long length() Returns the length of this file. void writeInt(int v) Writes an int to the file as four bytes, high byte first. int readInt() Reads a signed 32-bit integer from this file. String readLine() Reads the next line of text from this file. PROGRAM TO DEMONSTRATE RANDOMACCESSFILE import java.io.*; class RandomAccessFileDemo { public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); RandomAccessFile rf=new RandomAccessFile("raccess.dat","rw"); int val; System.out.println("Enter 10 Integer."); for(int i=0;i<10;i++) { val=Integer.parseInt(br.readLine()); rf.writeByte(val); } int pos,s;

44

Programming in Java boolean ans=true; try { while(ans) { rf.seek(0); System.out.print("Position : "); pos=Integer.parseInt(br.readLine()); s=pos-1; rf.seek(s); System.out.println("Value : " + rf.readByte()); System.out.print("\n1.Continue\n2.Exit\nSelect Choice : "); if(Integer.parseInt(br.readLine())==2) ans=false; } } catch(EOFException eof) { System.out.println("EOF Reached."); } finally { rf.close(); } } }

45

Programming in Java

THE CHARACTER STREAM


The Character stream classes provide a rich environment for handling char-oriented I/O. All the Character stream classes are sub classes of Reader and Writer classes. Reader Reader is an abstract class that defines Javas model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Writer Writer is an abstract class that defines streaming character output. All of the methods in this class return a void value and throw an IOException in the case of errors. METHODS DEFINED IN READER CLASS 1.abstract void close() Closes the input source. generate an IOException. Further read attempts will

2.void mark(int numChars) Places a mark at the current point in the input stream that will remain valid until numChars characters are read. 3.boolean markSupported() Returns true if mark()/reset() stream. are supported on this

4.int read() Returns an integer representation of the next available character from the invoking input stream. 1 is returned when the end of the file is encountered. 5.int read(char buffer[]) Attempts to read up to buffers length number of characters into buffer[] and returns the actual number of characters that were successfully read. 1 is returned when the end of the file is encountered. 6.abstract int read(char buffer[],int start, int numChars) Attempts to read up to numChars characters into buffer starting at buffer[start], returning the number of characters successfully read. 1 is returned when the end of the file is encountered.

46

Programming in Java 7.boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false. 8.void reset() Resets the input pointer to the previously set mark. 9.long skip(long numChars) Skips over numChars characters of input, returning the number of characters actually skipped. METHODS DEFINED IN WRITER CLASS 1.abstract void close() Closes the output stream. Further write attempts will generate an IOException. 2.abstract void flush() Finalizes the output state so that any buffers cleared. That is, it flushes the output buffers. are

3.void write(int ch) Writes a single character to the invoking output stream. 4.void write(char buffer[]) Writes a complete array of characters to the invoking output stream. 5.abstract void write(char buffer[],int start, int numChars) Writes a subrange of numChars characters from the array buffer, beginning at buffer[start] to the invoking output stream. 6.void write(String str) Writes str to the invoking output stream. 7.void write(String str, int start, int numChars) Writes a subrange of numChars characters from the array str, beginning at the specified start position.

LIST OF CHARACTER STREAM CLASSES


1.FileReader 2.FileWriter 3.CharArrayReader 4.CharArrayWriter 5.BufferedReader 6.BufferedWriter

47

Programming in Java Some of the classes in java.io are bridge classes. A bridge class converts BYTE stream to CHAR stream. InputStreamReader converts an InputStream to a Reader and OutputStreamWriter converts an OutputStream to a Writer. An InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. Constructor 1)InputStreamReader(InputStream in) Create an InputStreamReader that uses the default charset. Methods 1)void close() Close the stream. 2)String getEncoding() Return the name of the character being used by this stream. 3)int read() Read a single character. PROGRAM TO DEMONSTRATE INPUTSTREAMREADER import java.io.*; class InputReader { public static void main(String[] args)throws Exception { InputStreamReader isr=new InputStreamReader(System.in); System.out.println("Enter first char"); char c=(char)isr.read(); System.out.println("the entered value is :"+c); isr.close(); } } FILEWRITER FileWriter creates a Writer that you can use to write to a file. Contructor 1.FileWriter(String filePath) 2.FileWriter(String filePath, boolean append) 3.FileWriter(File fileObj) 4.FileWriter(File fileObj, boolean append)

encoding

48

Programming in Java PROGRAM TO DEMONSTRATE FILEWRITER import java.io.*; class FileWriterDemo { public static void main(String args[]) throws Exception { String source = "Now is the time for all good men\n to come to the aid of their country\n and pay their due taxes."; char buffer[] = new char[source.length()]; source.getChars(0,source.length(),buffer,0); FileWriter f0 = new FileWriter("file1.txt"); for(int i=0;i<buffer.length;i+=2) { f0.write(buffer[i]); } f0.close(); FileWriter f1 = new FileWriter("file2.txt"); f1.write(buffer); f1.close(); FileWriter f2 = new FileWriter("file3.txt"); f2.write(buffer,buffer.lengthbuffer.length/4,buffer.length/4); f2.close(); } } FILEREADER The FileReader class creates a Reader that you can use to read the contents of a file. Constructors 1.FileReader(String filePath) 2.FileReader(File fileObj) PROGRAM TO DEMONSTRATE FILEREADER import java.io.*; class FileReaderDemo { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr);

49

Programming in Java String s; while((s=br.readLine())!=null) System.out.println(s); fr.close(); } } CHARARRAYWRITER CharArrayWriter CharArrayWriter is an implementation of an output stream that uses an array as the destination. Constructors CharArrayWriter() CharArrayWriter(int numChars) PROGRAM TO DEMONSTRATE CHARARRAYWRITER import java.io.*; import java.io.FileWriter; class CharArrayWriterDemo { public static void main(String args[]) throws IOException { CharArrayWriter f=new CharArrayWriter(); String s="This should end up in the array"; char buf[]=new char[s.length()]; s.getChars(0,s.length(),buf,0); f.write(buf); System.out.println("Buffer as a string"); System.out.println(f.toString()); System.out.println("Into array"); char c[]=f.toCharArray(); for(int i=0;i<c.length;i++) System.out.print(c[i]); System.out.println("\nTo a FileWriter()"); FileWriter f2=new FileWriter("test.txt"); f.writeTo(f2); f2.close(); System.out.println("Doing a reset"); f.reset(); for(int i=0;i<3;i++) f.write('*'); System.out.println(f.toString()); } }

50

Programming in Java CHARARRAYREADER CharArrayReader is an implementation of an input stream that uses a character array as the source. Constructor CharArrayReader(char array[]) CharArrayReader(char array[],int start,int len) PROGRAM TO DEMONSTRATE CHARARRAYREADER import java.io.*; public class CharArrayReaderDemo { public static void main(String args[]) throws IOException { String tmp="abcdefghijklmnopqrstuvwxyz"; int length=tmp.length(); char c[]=new char[length]; tmp.getChars(0,length,c,0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c,0,5); int i; System.out.println("input1 is:"); while((i=input1.read())!=-1) System.out.print((char)i); System.out.println(); System.out.println("input2 is:"); while((i=input2.read())!=-1) System.out.print((char)i); System.out.println(); } }

51

Programming in Java BUFFEREDWRITER A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data buffers are physically written to the actual output stream. Using a BufferedWriter can increase performance by reducing the number of times data is actually physically written to the output stream. Constructors BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream,int bufSize) PROGRAM TO DEMONSTRATE BUFFEREDWRITER BUFFEREDREADER BufferedReader improves performance by buffering input. Constructors BufferedReader(Reader inputStream) BufferedReader(Reader inputStream,int bufSize) PROGRAM TO DEMONSTRATE BUFFEREDREADER import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws IOException { String s="This is a &copy;copyright symbol but this is &copy not.\n"; char buf[] = new char[s.length()]; s.getChars(0,s.length(),buf,0); CharArrayReader in=new CharArrayReader(buf); BufferedReader f=new BufferedReader(in); int c; boolean marked=false; while((c = f.read())!=-1) { switch(c) { case '&':if(!marked) { f.mark(32); marked=true; } else {

52

Programming in Java marked=false; } break; case ';':if(marked) { marked=false; System.out.print("(c)"); } else System.out.print((char)c); break; case ' ':if(marked) { marked=false; f.reset(); System.out.print("&"); } else System.out.print((char) c); break; default:if(!marked) System.out.print((char) c); break; } } } }

SERIALIZATION Serialization is the process of writing the state of an object to a byte stream. This is useful when you want to save the state of your program to a persistent storage area, such as a file. At a later time, you may restore these objects by using the process of deserialization. Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. An object may be supplied as an argument to that remote method. The sending machine serializes the object and transmits it. The receiving machine deserializes it. Assume that an object to be serialized has references to other objects, which, in turn, have references to still more objects. This set of objects and the relationships among them form a directed graph. There may also be

53

Programming in Java circular references within this object graph. That is, object X may contain a reference to object Y, and object Y may contain a reference back to object X.Objects may also contain references to themselves. The object serialization and deserialization facilities have been designed to work correctly in these scenarios. If you attempt to serialize an object at the top of an object graph, all of the other referenced objects are recursively located and serialized. Similarly, during the process of deserialization, all of these objects and their references are correctly restored. Serializable Interface Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable. Variables that are declared as transient are not saved by the serialization facilities. Also, static variables are not saved. ObjectOutput The ObjectOutput interface extends the DataOutput interface and supports object serialization. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared.That is,it flushes the output buffers. void write(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[],int offset,int numBytes) Writes a subrange of numBytes bytes from the array buffer,beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream.

54

Programming in Java void writeObject(Object obj) Writes object obj to the invoking stream. ObjectOutputStream The ObjectOutputStream class extends the OutputStream class and implements the ObjectOutput interface. It is responsible for writing objects to a stream. ObjectOutputStream(OutputStream outStream) throws IOException The argument outStream is the output stream to which serialized objects will be written. METHODS void writeBoolean(boolean b) Writes a boolean to the invoking stream. void writeByte(int b) Writes a byte to the invoking stream. void writeBytes(String str) Writes the bytes representing str to the invoking stream. void writeChar(int c) Writes a char to the invoking stream. void writeChars(String str) Writes the characters in str to the invoking stream. void writeDouble(double d) Writes a double to the invoking stream. void writeFloat(float f) Writes a float to the invoking stream. void writeInt(int i) Writes an int to the invoking stream. void writeLong(long l) Writes a long to the invoking stream. void writeShort(int i) Writes a short to the invoking stream. ObjectInput

55

Programming in Java The ObjectInput interface extends the DataInput interface. It supports object serialization. This is called to deserialize an object. int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException. int read() Returns an integer representation of the next available byte of input. 1 is returned when the end of the file is encountered. int read(byte buffer[]) Attempts to read up to buffer.length bytes into buffer, returning the number of bytes that were successfully read. 1 is returned when the end of the file is encountered. int read(byte buffer[],int offset,int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes that were successfully read. 1 is returned when the end of the file is encountered. Object readObject( ) Reads an object from the invoking stream. long skip(long numBytes) Ignores (that is, skips) numBytes bytes in the invoking stream, returning the number of bytes actually ignored. ObjectInputStream The ObjectInputStream class extends the InputStream class and implements the ObjectInput interface. ObjectInputStream is responsible for reading objects from a stream. ObjectInputStream(InputStream inStream) throws IOException, StreamCorruptedException

56

Programming in Java int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException. int read() Returns an integer representation of the next available byte of input. 1 is returned when the end of the file is encountered. int read(byte buffer[],int offset,int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset],returning the number of bytes successfully read.1 is returned when the end of the file is encountered. boolean readBoolean() Reads and returns a boolean from the invoking stream. byte readByte() Reads and returns a byte from the invoking stream. char readChar() Reads and returns a char from the invoking stream. double readDouble() Reads and returns a double from the invoking stream. float readFloat() Reads and returns a float from the invoking stream. void readFully(byte buffer[]) Reads buffer.length bytes into buffer. Returns only when all bytes have been read. void readFully(byte buffer[],int offset, int numBytes) Reads numBytes bytes into buffer starting at buffer[offset].Returns only when numBytes have been read. int readInt() Reads and returns an int from the invoking stream. long readLong() Reads and returns a long from the invoking stream.

57

Programming in Java

final Object readObject() Reads and returns an object from the invoking stream. short readShort() Reads and returns a short from the invoking stream. int readUnsignedByte() Reads and returns an unsigned byte from the invoking stream. int readUnsignedShort() Reads an unsigned short from the invoking stream.

58

Programming in Java

APPLETS
Applet is a Java program that can run in a browser. Applet is a small java program that is primarily used in Internet Computing. Applet is a Window based program. Applet provides Graphical user Interface. Applet is Event Driven. Applet is intended for client. It works for client or a browser. Applet can be transported over the Internet from one computer to other and can be run using 'appletviewer' or any browser. With the invent of Applet, Java has revolutionized the way users retrieve and use documents on Internet (WWW). Java's Applet has significant impact on WWW. CREATING AN Applet All Applet classes (user) must java.applet & java.awt All Applet classes (user) must class Applet from java.applet All Applet classes (user) must Cycle Methods of Applet. All Applet classes (user) must (as comment) import java.applet.*; import java.awt.*; public class MyApplet extends Applet { //life cycle methods } /*<applet code="<applet class>" height=" " width=" "> </applet>*/ Note : Applet class will not have main() save it as MyApplet.java compile : javac MyApplet.java execute : appletviewer MyApplet.java

import the package extend the super implement the Life include an Applet Tag

59

Programming in Java TO EXECUTE AN APPLET IN A BROWSER 1.create an html file as <HTML> <applet code=MyApplet height=300 width=300></applet> </HTML> 2.save it as *****.html 3.open *****.html in a browser (dblclick) APPLET LIFE CYCLE 1.init() 2.start() 3.stop() 4.destroy() 5.paint() The Applet class Applet class provides standard interface between applets and their environment. Applet class provides several methods that give a detailed control over execution of a applet. Method Description 1.void init() The init() method is the first method to be called. This is where you should initialize variables. This method is called only once in the Life Cycle of applet. 2.void start() Called by the browser when an applet should start (or resume) execution. It is automatically called after init() when an applet first begins. It is called to restart an applet after it has been stopped. if a user leaves a web page and comes back, the applet resumes execution at start(). 3.void stop() Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start(). The stop() method is called when a web browser leaves the HTML document containing the applet when it goes to another page. When stop() is called, the applet is probably running. 4.void destroy()

60

Programming in Java Called by the browser just before an applet is terminated. The destroy() method is called when the environment determines that your applet needs to be removed completely from memory. 5.String getAppletInfo() Returns a string that describes the applet. 6.URL getCodeBase() Returns the URL associated with the invoking applet. 7.URL getDocumentBase() Returns the URL of the HTML document that invokes the applet. 8.String getParameter(String paramName) Returns the parameter associated with paramName. null is returned if the specified parameter is not found. 9.boolean isActive() Returns true if the applet has been started. It returns false if the applet has been stopped. 10.void showStatus(String str) Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place. SEQUENCE OF CALLING LIFE CYCLE METHODS OF APPLET It is important to understand the order in which the various methods are called. When an applet begins, the AWT calls the following methods, in this sequence: 1. init() 2. start() 3. paint() When an applet is terminated, the following sequence of method calls takes place: 1. stop() 2. destroy()

61

Programming in Java void paint(Graphics object) The paint() method is called each time your applets output must be redrawn. This situation can occur for several reasons. The paint() method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. METHODS FROM GRAPHICS CLASS (JAVA.AWT) 1. void drawString(String S, int x, int y) 2. void setBackground(Color newcolor) 3. void setForeground(Color newcolor) Color class defines color constants Color.red Color.gray Color.blue Color.lightgray Color.green Color.pink Color.orange Color.magenta Color.white Color.cyan Color.black Color.darkgray Color.yellow Color(int red, int green, int blue) //constructor Color C=new Color(255,0,0) //red color range : 0 - 255 Color C=new Color(0,0,0) //black Color C=new Color(255,255,255) //white 4. Color getBackground() 5. Color getForeground() 6. void repaint() repaints the applet by invoking the paint(). 7. void repaint(int x, int y, int height, int width) repaints only the rectangular portion specified by the arguments. 8. void repaint(long maxdelay) repaint the applet after the specified time interval. 9. void repaint(long maxdelay, int x, int y, int height, int width) repaints only the rectangular portion specified by the arguments after the specified time interval.

62

Programming in Java 10. void drawLine(int x1,int y1,int x2,int y2) draws a line from (x1,y1) to (x2,y2). 11. void drawRect(int x,int y,int height,int width) draws a rectangle in current color. 12. void drawRoundRect(int x,int y,int height,int width,int arc width,int arc height) Draws a rectangle with rounded corners in the current color with given width and height 13. void drawOval(int x,int y,int height,int width) Draws an oval in the current color with specified width and height. 14. void drawPolygon(int[] xpoints,int[] ypoints,int npoints) draws a polygon with the given (x[],y[]) coordinates. 15. void drawPolyline(int[] xpoints, int[] ypoints, int npoints) draws a polyline with the given (x[],y[]) coordinates. 16. void drawArc(int x, int y, int arc width, int arc height, int arc start angle, int arc angle) Draws an arc in the current color relative to the bounding rectangle top left coordinates x and y. The arc segment is drawn from the starting angle to the arc angle. 17. void fillRect(int x, int y, int height, int width) draws a solid rectangle filled with the current forecolor. 18. void fillRoundRect(int x, int y, int height, int width, int arc width, int arc height) Draws a solid rectangle with rounded corners in the current color with the specified width and height. 19. void fillOval(int x, int y, int height, int width) Draws and Filled Oval in the current color with specified width and height. 20. void fillPolygon(int[] xpoints, int[] ypoints, int npoints)

63

Programming in Java 21. void fillArc(int x,int y, int arc width, int arc height,int arc start angle, int arc angle) 22. void setFont(Font F) 23. void setColor(Color C) 24. void clearRect(int x, int y, int width, int height) Draws a rectangle using the current Background color, thereby clearing it. 25. void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3D rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinate (x,y). The rectangle is raised from surface when boolean value is true. 26. void fill3DRect(int x, int y, int width, int height, boolean raised) Draws a filled 3D rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinate(x,y). The rectangle is raised from surface when boolean value is true.

64

Programming in Java

AWT (ABSTRACT WINDOW TOOLKIT)


AWT contains classes for creating Graphical User Interfaces (GUI). AWT contains numerous classes and methods to create and manage windows, buttons, text-fields, labels etc.. Although the main purpose of AWT is to support the Applet Window, it can also be used to design stand-alone window that run on a graphical environment like Windows. The package Interfaces. java.awt provides all the classes and

LIST OF CLASSES IN java.awt AWTEvent BorderLayout Button Canvas CardLayout Checkbox CheckboxGroup CheckboxMenuItem Frame GridLayout FlowLayout Label List Panel Component Container Menu MenuBar MenuItem Window Encapsulates AWT Events. The BorderLayout Manager Creates a Push Button Control. Represents a blank rectangle area of the screen. The CardLayout Manager Creates a Checkbox control. Creates a Group of Checkbox controls. Creates a on/off MenuItem. Creates a stand-alone window with a Menubar# Title#Resize corners. The GridLayout Manager. The FlowLayout Manager. Creates a Label to display a single line of text. Creates a List Box control#having a list of choices#user can choose one from them. A Simple concrete sub class for Container. A Abstract super class for all classes in java.awt A sub class of Component# that encapsulates a container to hold other components. Encapsulates a Menu. Encapsulates a Menubar. All the elements of Menu are subclasses of MenuItem. Creates a stand-alone window without

65

Programming in Java Menubar#Title#Resize corners. The FlowLayout Manager. Creates a pop-up list. Manages Color in a portable manner. Creates a Dialog Window. Specifies dimensions of a object. Encapsulates Events. Creates a File Dialog#from which file can be selected. Encapsulates Font Type. Creates a scroll bar control. Creates a Multi-line text edit control. Creates a single-line text edit control.

FlowLayout Choice Color Dialog Dimension Event FileDialog Font Scrollbar TextArea TextField

Panel, Window & Frame are container classes. BorderLayout, CardLayout, FlowLayout, GridLayout Layout Managers.

are

FRAME
A Frame class object creates a concrete window with a title bar, menu bar and resizable corners. CONSTRUCTORS 1.Frame() Creates a new Frame with no title. (invisible) Frame F = new Frame(); 2.Frame(String Title) Creates a new Frame with the given title. (invisible) Frame F = new Frame("My Frame"); METHODS 1.void setTitle(String Title) sets the specified string as title for this Frame. 2.String getTitle() returns a string containing the title of this Frame. 3.void setBackground(Color C) 4.void setForeground(Color C) sets background and foreground colors for this Frame.

66

Programming in Java

5.void setResizable(boolean resize) specifies whether this Frame to be resizable or not. 6.boolean isResizable() checks whether this Frame is resizable or not. 7.void setSize(int width, int height) sets the size of this Frame. 8.void setVisible(boolean visible) specifies whether this Frame is to be visible or not. 9.MenuBar setMenubar(MenuBar M) adds the MenuBar M on to this Frame. 10.void add(Component C) adds the component C to this Frame. FRAME EXAMPLE import java.awt.*; class MyFrame extends Frame { public static void main(String args[]) { MyFrame F=new MyFrame(); F.setSize(800,600); F.setTitle("My Frame."); F.setBackground(Color.magenta); F.setResizable(false); F.setVisible(true); //default:false } }

BUTTON
Creates a Push button Control. CONSTRUCTOR 1.Button() Button Add=new Button(); 2.Button(String title) Button Add=new Button("ADD"); METHODS 1.void addActionListener(ActionListener al) Adds/registers a ActionListener with this Button.

67

Programming in Java

2.String getActionCommand() returns the action command of this Button. if action command is not set then returns the label of this Button. 3.String getLabel() returns the label of this Button. 4.void setLabel(String label) Specifies the label for this Button. 5.void setActionCommand(String ActionCommand) specifies the action command for this Button. 6.void removeActionListener(ActionListener al) removes Action Listener registered with this Button. BUTTON EXAMPLE import java.awt.*; class MyButton extends Frame { public static void main(String args[]) { Frame F=new Frame(); //super(); new Frame(); Button Button Button Button B1=new B2=new B3=new B4=new Button("OPEN"); Button("NEW"); Button("SAVE"); Button("SAVE AS");

F.setSize(800,600); F.setTitle("My Frame."); F.setBackground(Color.gray); F.setLayout(new FlowLayout()); B1.setBackground(Color.RED); B2.setBackground(Color.ORANGE); B3.setBackground(Color.RED); B4.setBackground(Color.ORANGE); F.add(B1); F.add(B2); F.add(B3); F.add(B4); //F.add(new Button("OPEN")); //add(new Button("NEW"));

68

Programming in Java

//F.add(B4);

has no effect as a component is added only once.

F.setResizable(false); F.setVisible(true); } }

TEXT FIELD
A TextField object provides a single line text editable control. CONTRUCTOR 1.TextField() 2.TextField(int cols) 3.TextField(String text) 4.TextField(String text, int cols) METHODS 1.void addActionListener(ActionListener AL) registers a ActionListener with this TextField. 2.int getColumns() returns width of this TextField. 3.void removeActionListener(ActionListener AL) removes ActionListener registered with this TextField. 4.void setColumns(int Cols) specifies width of this TextField. 5.void setText(String text) specifies text to be shown in this TextField.

TEXTAREA
A TextArea object provides a Multi line text editable control. CONSTRUCTOR 1.TextArea() 2.TextArea(int rows, int cols) 3.TextArea(String text) 4.TextArea(String text,int rows,int cols) 5.TextArea(String text,int rows,int cols, int scrollbar)

69

Programming in Java TextArea addr=new TextArea("Hyderabad",10,25,Scrollbar.VERTICAL/ Scrollbar.HORIZANTAL) METHODS 1.void append(String text) appends the text to this TextArea. 2.int getCols() 3.int getRows() returns height and width of this TextArea. 4.void insert(String text, int pos) inserts the text at given pos in this TextArea. 5.void replaceRange(String text, int start, int end) replaces a specific range (start to end) with the given text in this TextArea. 6.void setRows(int rows) 7.void setCols(int cols) specifies height and width for this TextArea. TEXT FIELD & TEXT AREA EXAMPLE import java.awt.*; class MyTextField extends Frame { public static void main(String args[]) { MyTextField F=new MyTextField(); F.setSize(500,400); F.setTitle("My Frame"); Label Label Label Label Label L1=new L2=new L3=new L4=new L5=new Label("Name"); Label("Father Name"); Label("Course"); Label("Address"); Label("Qualification"); TextField("Key TextField("Key TextField("Key TextField("Key TextField("Key in in in in in details"); details"); details"); details"); details");

TextField TextField TextField TextField TextField

T1=new T2=new T3=new T4=new T5=new

Panel P=new Panel();

70

Programming in Java

Button B1=new Button("Click Here"); Button B2=new Button("Click Here"); TextArea TA1=new TextArea(10,5); TextArea TA2=new TextArea(10,5); P.setLayout(new GridLayout(5,2,25,25)); P.add(L1);P.add(T1); P.add(L2);P.add(T2); P.add(L3);P.add(T3); P.add(L4);P.add(T4); P.add(L5);P.add(T5); F.setLayout(new BorderLayout(50,50)); F.add(P,BorderLayout.CENTER); F.add(B1,BorderLayout.NORTH); F.add(B2,BorderLayout.SOUTH); F.add(TA1,BorderLayout.EAST); F.add(TA2,BorderLayout.WEST); F.setBackground(Color.RED); F.setForeground(Color.BLUE); F.setResizable(false); F.setVisible(true); } }

71

Programming in Java

EVENT HANDLING
EVENT An Event is a action performed. An Event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character from the keyboard, selecting an item in a list, and clicking the mouse. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, software or hardware failure occurs, or an operation is completed. User is free to define events that are appropriate for the application. EVENT SOURCES A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. The general form is public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener() The method that registers a mouse motion listener is called addMouseMotionListener() When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them. Some sources may allow only one listener to register. When such an event occurs, the registered listener is notified. This is known as unicasting the event.

72

Programming in Java A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form is public void removeTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener we use removeKeyListener() The methods that add or remove listeners are provided by the source that generates events. EVENT LISTENERS A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. THE DELEGATION EVENT MODEL This defines standard and consistent mechanisms to generate and process events. Its concept is quite simple A source generates an event and sends it to one or more listeners. The listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to delegate the processing of an event to a separate piece of code. In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit i.e., notifications are sent only to listeners that want to receive them. EVENT CLASSES The classes that represent events are at the core of Javas event handling mechanism. They provide a consistent, easy-to-use means of encapsulating events. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events.

73

Programming in Java CONSTRUCTOR EventObject(Object src) Here, src is the object that generates this event. METHODS 1.Object getSource() returns the source of the event. 2.String toString( ) returns the string equivalent of the event. The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its getID() method can be used to determine the type of the event int getID() EVENT ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent ACTION PERFORMED Button press, item dblclick, menu item selected. scrollbar manipulated. component hidden, moved, resized, becomes visible. components added or removed from a container. component gains or looses focus. checkbox item is clicked, choice selection is made, checkable menu item is selected or deselected. input from keyboard. mouse clicked, moved, dragged, pressed, released, entered, exited change in content of text component. window activated, opened, closed, deactivated.

74

Programming in Java EVENT SOURCES Button Checkbox Choice List MenuItem Scrollbar TextArea TextField Window ActionEvent ItemEvent ItemEvent ActionEvent, ItemEvent ActionEvent, ItemEvent AdjustmentEvent TextEvent TextEvent WindowEvent

EVENT LISTENERS All Event Listeners are Interfaces ActionListener AdjustmentListener ComponentListener ContainerListener FocusListener ItemListener KeyListener MouseListener MouseMotionListener TextListener WindowListener ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent MouseEvent TextEvent WindowEvent

METHODS DEFINED BY LISTENER INTERFACES 1.ActionListener void actionPerformed(ActionEvent AE) 2.AdjustmentListener void adjustmentValueChanged(AdjustmentEvent AE) 3.ComponentListener void componentResized(ComponentEvent CE) void componentMoved(ComponentEvent CE) void componentShown(ComponentEvent CE) void componentHidden(ComponentEvent CE) 4.ContainerListener void componentAdded(ContainerEvent CE)

75

Programming in Java void componentRemoved(ContainerEvent CE) 5.FocusListener void focusGained(FocusEvent FE) void focusLost(FocusEvent FE) 6.ItemListener void itemStateChanged(ItemEvent IE) 7.KeyListener void keyPressed(KeyEvent KE) void keyTyped(KeyEvent KE) void keyReleased(KeyEvent KE) 8.MouseListener void mouseClicked(MouseEvent ME) void mouseEntered(MouseEvent ME) void mouseExited(MouseEvent ME) void mousePressed(MouseEvent ME) void mouseReleased(MouseEvent ME) 9.MouseMotionListener void mouseDragged(MouseEvent ME) void mouseMoved(MouseEvent ME) 10.TextListener void textChanged(TextEvent TE) 11.WindowListener void windowActivated(WindowEvent WE) void windowDeactivated(WindowEvent WE) void windowOpened(WindowEvent WE) void windowClosed(WindowEvent WE) METHODS FROM EVENT CLASSES The top most super class of all Event classes is EventObject class (java.util). Object getSource() returns the object that generated the Event. ActionEvent 1) String getActionCommand() Returns the command string associated with this action. For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button.

76

Programming in Java

AdjustmentEvent 1) Adjustable getAdjustable() returns the object that generated the event. 2) int getValue() returns the amount of the adjustment. ComponentEvent 1) Component getComponent() returns the component that generated the event. ContainerEvent 1) Container getContainer() return a reference to the container that generated this event. 2) Component getChild() returns a reference to the component that was added to or removed from the container. ItemEvent 1) Object getItem() used to obtain a generated an event.

reference

to

the

item

that

2) ItemSelectable getItemSelectable() used to obtain a reference to the ItemSelectable object that generated an event. Lists and choices are examples of user interface elements that implement the ItemSelectable interface. 3) int getStateChange() returns the state change(i.e.,SELECTED or DESELECTED) for the event. KeyEvent 1) char getKeyChar() returns the character that was entered. 2) int getKeyCode() returns the key code. MouseEvent 1) int getX() 2) int getY()

77

Programming in Java return the X and Y coordinates of the mouse when the event occurred. 3) Point getPoint() returns a Point coordinates. object that contains the X, Y

4) void translatePoint(int x, int y) This method changes the location of the event. Here, the arguments x and y are added to coordinates of the event.

the

5) int getClickCount() obtains the number of mouse clicks for this event. 6) int getButton() returns a value that caused the event. represents the button that

WindowEvent 1) Window getWindow() returns the Window object that generated the event. 2) Window getOppositeWindow() returns the opposite window (when a focus event has occurred). 3) int getOldState() returns the previous window state. 4) int getNewState() returns the current window state.

78

Programming in Java

NETWORKING / SOCKET PROGRAMMING


NETWORK Two or more machines connected with each other is a Network. This connection can be through a physical medium like cable, can be a wireless connection through satellite. Network is used for Resource Sharing. COMMON TERMS USED IN NETWORKING. SERVER A server is anything that has some resource that can be shared. Compute Servers: Print Servers : Disk Servers : Web Servers : Mail Servers : Database Servers which provide computing power; which manage a collection of printers; which provide networked disk space; which store web pages. which provide mail service. : which provide database services.

CLIENT A client is simply a machine that requests for service from a Server. Internet Address Every computer on the Internet has an address. An Internet address is a number that uniquely identifies each computer on the Network. PROTOCOL PROTOCOL is set of rules for Networking. PROTOCOL specifies how data is to be transferred over the network. It specifies how machines over the network will communicate with each other. A List 1.HTTP 2.SMTP 3.FTP 4.IP 5.TCP 6.UDP of PROTOCOLS : Hyper Text Transfer Protocol. : Simple Mail Transfer Protocol. : File Transfer Protocol. : Internet Protocol. : Transmission Control Protocol. : User Datagram Protocol.

Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination.

79

Programming in Java Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit your data. User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets. PROXY SERVER A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. Thus, a client would connect to a proxy server, which did not have such restrictions, and the proxy server would in turn communicate for the client. As this isn't a server but behaves like a server, it is called as proxy server. Domain Naming Service (DNS) DNS maps names with Internet Addresses. When a client has to connect to a server, client has to remember the Address of the server, which is a number. This would look like xxx.xxx.xxx.xxx (252.712.107.786) As remembering Internet Addresses isn't easier, these are mapped to names. SOCKET A Socket is a place where a client can plug in. A Socket delivers some pay load. A Socket is associated with a protocol and a port number. Server creates socket and waits for client. A Client that understands the protocol can connect by specifying the port number. The package java.net provides all classes and interfaces required for networking. INETADDRESS CLASS The InetAddress class is used to encapsulate the Address of a Computer. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. (Factory methods are static methods that return an instance of that class). INETADDRESS FACTORY METHODS static InetAddress getLocalHost()

80

Programming in Java throws UnknownHostException This method simply returns the InetAddress object that represents the local host. static InetAddress getByName(String hostName) throws UnknownHostException This method returns an InetAddress for a host name passed to it. static InetAddress[] getAllByName(String hostName) throws UnknownHostException Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system. METHODS 1.boolean equals(Object obj) Compares this object against the specified object. 2.byte[] getAddress() Returns the IP address of this InetAddress object. 3.String getHostAddress() Returns the IP address string in textual presentation. 4.String getHostName() Gets the host name for this IP address. 5.static InetAddress getHost() Returns the remote host. SOCKET & SERVER SOCKET CLASSES TCP/IP Sockets TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to- point, stream-based connections between hosts on the Internet. A socket can be used to connect Javas I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. There are two kinds of TCP sockets in Java. Socket for Clients ServerSocket for Servers The ServerSocket class is designed to be a listener which waits for clients to connect before doing anything.

81

Programming in Java The Socket class is designed to connect to server socket and initiate protocol exchanges. Socket Class The creation of a Socket object implicitly establishes a connection between the client and server. CONSTRUCTORS Socket(String hostName, int port) Creates a socket connecting the local host to the named host and port. (throws an UnknownHostException or an IOException) Socket(InetAddress ipAddress, int port) Creates a socket using a pre existing InetAddress object and a port. (throws an IOException) METHODS InetAddress getInetAddress() Returns the InetAddress associated object.

with

the

Socket

int getPort() Returns the remote port to which this Socket object is connected. int getLocalPort() Returns the local port to which this Socket object is connected. InputStream getInputStream() Returns the InputStream associated socket. OutputStream getOutputStream() Returns the OutputStream associated socket. with the invoking

with

the

invoking

ServerSocket Class The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on published ports. ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will register itself with the system as having an interest in client connections.

82

Programming in Java The constructors for ServerSocket number to accept connections. specifies a port

CONSTRUCTORS ServerSocket(int port) Creates server socket on the specified port with a queue length of 50. ServerSocket(int port, int maxQueue) Creates a server socket on the specified port with a maximum queue length of maxQueue. ServerSocket(int port, int maxQueue, InetAddress localAddress) Creates a server socket on the specified port with a maximum queue length of maxQueue. The queue length connections it can refuse connections. These constructors conditions. tells the system how many client leave pending before it should simply The default is 50. throw an IOException under adverse

METHODS Socket accept() makes the server to wait for client to initiate communications, return with a Socket that is then used for communication with the client. Being a Subclass of Socket uses all the methods from Socket Class.

83

Programming in Java

COLLECTIONS
A Collection is a group of objects. The Collection framework standardizes the way in which groups of objects are manipulated. The entire collections framework is designed around a set of standard interfaces. The framework allows different types of collections to work in a similar manner and with a high degree of interoperability and Extending and/or adapting a collection is easier. The collection interfaces are necessary because they determine the fundamental nature of the collection classes. The concrete classes simply provide different implementations of the standard interfaces. LIST OF INTERFACES FROM COLLECTION FRAMEWORK INTERFACE Collection DESCRIPTION Enables you to work with groups of objects. It is at the top of the collections hierarchy. it is at the top of the collections hierarchy. Extends Collection to handle sequences (lists of objects) Extends Collection to handle sets, which must contain unique elements. Extends Set to handle sorted sets

List Set SortedSet

The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections contain. All these methods throw an UnsupportedOperationException if an unsupported operation is invoked. A ClassCastException is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. METHODS 1.boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates.

84

Programming in Java

2.boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false. 3.void clear() Removes all elements from the invoking collection. 4.boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false. 5.boolean containsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. 6.boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. 7.boolean isEmpty() Returns true if the invoking collection is empty. Otherwise, returns false. 8.Iterator iterator() Returns an iterator for the invoking collection. An Iterator is used to browse a collection. 9.boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. 10.boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed).Otherwise, returns false. 11.boolean retainAll(Collection c) Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. 12.int size() Returns the number of elements held in the invoking collection.

85

Programming in Java

13.Object[] toArray() Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. THE LIST INTERFACE The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. In addition to the methods defined by Collection, List defines some of its own. METHODS 1.void add(int index, Object obj) Inserts obj into the invoking list at the specified index, shifting pre-existing element up in the List. 2.boolean addAll(int index, Collection c) Inserts all elements of c into the invoking list at the Specified index, shifting pre-existing element up in the List. Returns true if the invoking list changes and returns false otherwise. 3.Object get(int index) Returns the object stored at the specified index within the invoking collection. 4.int indexOf(Object obj) Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, 1 is returned. 5.int lastIndexOf(Object obj) Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, 1 is returned. 6.ListIterator listIterator() Returns an iterator to the start of the invoking list. 7.ListIterator listIterator(int index) Returns an iterator to the invoking list that begins at the specified index.

86

Programming in Java

8.Object remove(int index) Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted (indexes of subsequent elements are decremented by one). 9.Object set(int index, Object obj) Assigns obj to the location specified by index within the invoking list. 10.List subList(int start, int end) Returns a list that includes elements from start to end1 in the invoking list.Elements in the returned list are also referenced by the invoking object. THE SET INTERFACE The Set interface defines a set. It extends Collection and declares the behavior of a collection that does not allow duplicate elements. Therefore, the add() method returns false if an attempt is made to add duplicate elements to a set. THE SORTEDSET INTERFACE The SortedSet interface extends Set and declares behavior of a set sorted in ascending order. the

METHODS 1.Object first() Returns the first element in the invoking sorted set. 2.Object last() Returns the last element in the invoking sorted set. 3.SortedSet subSet(Object start, Object end) Returns a SortedSet that includes those elements between start and end1. 4.SortedSet tailSet(Object start) Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set.

87

Programming in Java THE STANDARD COLLECTION CLASSES CLASS DESCRIPTION AbstractCollection Implements most of the Collection interface. AbstractList Extends AbstractCollection and implements most of the List interface. AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. LinkedList Implements a linked list by extending AbstractSequentialList. ArrayList AbstractSet HashSet LinkedHashSet TreeSet Implements a dynamic array by extending AbstractList. Extends AbstractCollection and implements most of the Set interface. Extends AbstractSet for use with a hash table. Extends HashSet to allow insertion-order iterations. Implements a set stored in a tree. Extends AbstractSet

The ArrayList Class The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. An ArrayList is a variablelength array of object references. i.e.., an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. CONSTRUCTORS 1.ArrayList() : builds an empty array list. list

2.ArrayList(Collection c) : builds an array initialised with elements from collection c.

3.ArrayList(int capacity) : builds an array list that has the specified initial capacity. The capacity grows automatically as elements are added to an array list.

88

Programming in Java

METHODS 1.void ensureCapacity(int capacity) Increases the size of this Collection. capacity will be the new size of this Collection. 2.void trimToSize() reduce the size of this ArrayList object so that it is precisely as large as the number of items that it is currently holding. The LinkedList Class The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure. CONSTRUCTORS 1.LinkedList() : builds an empty linked list.

2.LinkedList(Collection c) : builds a linked list that is initialized with the elements of the collection c. METHODS 1.void addFirst(Object obj) adds elements to the start of the list. 2.void addLast(Object obj) adds elements to the end of the list. 3.Object getFirst() returns the first object from the list. 4.Object getLast() returns the last object from the list. 5.Object removeFirst() removes the first element from the list and returns it 6.Object removeLast() removes the last element from the list and returns it. The HashSet Class HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value,

89

Programming in Java called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically. The advantage of hashing is that it allows the execution time of basic operations, such as add(),contains(),remove()and size() to remain constant even for large sets. CONSTRUCTORS HashSet() : HashSet(Collection c) HashSet(int capacity) constructs a default HashSet. : initializes the HashSet by using the elements of c. : initializes the capacity of the HashSet to capacity.

Note : A hash set does not guarantee the order of its elements. The TreeSet Class TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. CONSTRUCTORS 1.TreeSet() constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements. TreeSet(Collection c) : builds a tree set that contains the elements of c. TreeSet(Comparator comp) : constructs an empty tree set that will be sorted according to the comparator specified by comp. builds a tree set that contains the elements of ss. :

TreeSet(SortedSet ss)

The Iterator Interface. An Iterator gives you a general-purpose, standardized way of accessing the elements within a collection, one at a time. Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends

90

Programming in Java Iterator to allow bidirectional traversal of a list, and the modification of elements. METHODS (Iterator) 1.boolean hasNext() Returns true if there are more elements. Otherwise, returns false. 2.Object next() Returns the next element. Throws NoSuchElementException if there is no next element. 3.void remove() Removes the current element. Throws IllegalStateException if an attempt is made to call remove() that is not preceded by a call to next(). METHODS (ListIterator) 1.void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next(). 2.boolean hasNext() Returns true if there is a next element. Otherwise, returns false. 3.boolean hasPrevious() Returns true if there Otherwise, returns false. is a previous element.

4.Object next() Returns the next element. A NoSuchElementException is thrown if there is not a next element. 5.int nextIndex() Returns the index of the next element. If there is no next element, returns the size of the list. 6.Object previous() Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. 7.int previousIndex() Returns the index of the previous element. If there is no previous element, returns -1. 8.void remove()

91

Programming in Java Removes the current element from the list. IllegalStateException is thrown if remove( ) called before next( ) or previous( ) is invoked. An is

9.void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next() or previous(). Steps for using an Iterator or ListIterator 1.Obtain an iterator to the start of the collection by calling the collections iterator() method. 2.Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. 3.Within the loop, obtain each element by calling next(). MAP A map is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. The Map Interface The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. After the value is stored, you can retrieve it by using its key. METHODS 1.void clear() Removes all key/value pairs from the invoking map. 2.boolean containsKey(Object k) Returns true if the invoking map contains k as a key. Otherwise, returns false. 3.boolean containsValue(Object v) Returns true if the map contains v as a value. Otherwise, returns false. 4.Object remove(Object k) Removes the entry whose key equals k. 5.int size() Returns the number of key/value pairs in the map.

92

Programming in Java

The SortedMap Interface The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order. METHODS 1.Comparator comparator() Returns the invoking sorted maps comparator. If the natural ordering is used for the invoking map, null is returned. 2.Object firstKey() Returns the first key in the invoking map. 3.SortedMap headMap(Object end) Returns a sorted map for those map entries with keys that are less than end. 4.Object lastKey() Returns the last key in the invoking map. 5.SortedMap subMap(Object start, Object end) Returns a map containing those entries with keys that are greater than or equal to start and less than end. 6.SortedMap tailMap(Object start) Returns a map containing those entries with keys that are greater than or equal to start. Comparators Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means. By default, these classes store their elements by using what Java refers to as natural ordering, which is usually the ordering that you would expect. (A before B, 1 before 2, and so forth.) If you want to order elements a different way, then specify a Comparator object when you construct the set or map. Doing so gives you the ability to govern precisely how elements are stored within sorted collections and maps. The Comparator interface defines two methods 1.int compare(Object obj1, Object obj2) The compare() method, compares two elements for order obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal.

93

Programming in Java It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. The method can throw a ClassCastException if the types of the objects are not compatible for comparison. By overriding compare(), you can alter the way that objects are ordered. 2. boolean equals(Object obj) The equals() method, tests whether an object equals the invoking comparator. obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.

The Enumeration Interface The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. Enumeration specifies the following two methods: 1.boolean hasMoreElements() return true while there are still more elements to extract, and false when all the elements have been enumerated. 2.Object nextElement() returns the next object in the enumeration as a generic Object reference. Each call to nextElement() obtains the next object in the enumeration. The calling routine must cast that object into the object type held in the enumeration. Vector Vector implements a dynamic array. It is similar to ArrayList, but with two differences. Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections.

94

Programming in Java Constructors 1.Vector() creates a default vector, which has an initial size of 10. 2.Vector(int size) creates a vector whose initial capacity is specified by size. 3.Vector(int size,int incr) creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward. 4.Vector(Collection c) creates a vector that contains the elements of collection c.
All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. If you dont specify an increment, the vectors size is doubled by each allocation cycle.

Vector defines these protected data members: int capacityIncrement; int elementCount; Object elementData[]; The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. The array that holds the vector is stored in elementData. Methods Method void addElement(Object element) int capacity() Object clone() boolean contains(Object element) Description The object specified by element is added to the vector. Returns the capacity of the vector. Returns a duplicate of the invoking vector. Returns true if element is contained by the vector#and returns false if it is not.

95

Programming in Java void copyInto(Object array[]) Object elementAt(int index) Enumeration elements() void ensureCapacity(int size) Object firstElement() int indexOf(Object element) The elements contained in the invoking vector are copied into the array specified by array. Returns the element at the location specified by index. Returns an enumeration of the elements in the vector. Sets the minimum capacity of the vector to size. Returns the first element in the vector. Returns the index of the first occurrence of element. If the object is not in the vector# 1 is returned. Returns the index of the first occurrence of element at or after start. If the object is not in that portion of the vector# 1 is returned. Adds element to the vector at the location specified by index. Returns true if the vector is empty and returns false if it contains one or more elements. Returns the last element in the vector. Returns the index of the last occurrence of element. If the object is not in the vector# 1 is returned. Returns the index of the last occurrence of element before start.If the object is not in that portion of the vector# 1 is returned. Empties the vector. After this method executes# the size of the vector is zero. Removes element from the vector.If more than one instance of the specified

int indexOf(Object element# int start)

void insertElementAt(Object element#int index) boolean isEmpty()

Object lastElement() int lastIndexOf(Object element) int lastIndexOf(Object element#int start)

void removeAllElements() boolean removeElement(Object element)

96

Programming in Java object exists in the vector then it is the first one that is removed. Returns true if successful and false if the object is not found. Removes the element at the location specified by index. The location specified by index is assigned element. Sets the number of elements in the vector to size. If the new size is less than the old size# elements are lost. If the new size is larger than the old size null elements are added. Returns the number of elements currently in the vector. Returns the string equivalent of the vector. Sets the vectors capacity equal to the number of elements that it currently holds.

void removeElementAt(int index) void setElementAt(Object element#int index) void setSize(int size)

int size() String toString() void trimToSize()

Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. CONSTRUCTOR Stack() : creates an Empty Stack. Stack S = new Stack(); METHODS Method boolean empty() Description Returns true if the stack is empty# and returns false if

97

Programming in Java the stack contains elements. Returns the element on the top of the stack# but does not remove it. Returns the element on the top of the stack#removing it in the process. Pushes element onto the stack. element is also returned. Searches for element in the stack. If found# its offset from the top of the stack is returned. Otherwise# 1 is returned.

Object peek() Object pop() Object push(Object element) int search(Object element)

98

Programming in Java

javadoc usage: javadoc [options][packagenames][sourcefiles][@files] -overview <file> Read overview documentation from HTML file -public Show only public classes and members -protected Show protected/public classes and members (default) -package Show package/protected/public classes and members -private Show all classes and members -help Display command line options and exit -doclet <class> Generate output via alternate doclet -docletpath <path> Specify where to find doclet class files -sourcepath <pathlist> Specify where to find source files -classpath <pathlist> Specify where to find user class files -exclude <pkglist> Specify a list of packages to exclude -subpackages <subpkglist> Specify subpackages to recursively load -breakiterator Compute 1st sentence with BreakIterator -bootclasspath <pathlist> Override location of class files loaded by the bootstrap class loader -source <release> Provide source compatibility with specified release -extdirs <dirlist> Override location of installed extensions -verbose Output messages about what Javadoc is doing -locale <name> Locale to be used, e.g. en_US or en_US_WIN -encoding <name> Source file encoding name -quiet Do not display status messages -J<flag> Pass <flag> directly to the runtime system

99

Programming in Java Provided by Standard doclet: -d <directory> Destination directory for output files -use Create class and package usage pages -version Include @version paragraphs -author Include @author paragraphs -docfilessubdirs Recursively copy doc-file subdirectories -splitindex Split index into one file per letter -windowtitle <text> Browser window title for the documenation -doctitle <html-code> Include title for the overview page -header <html-code> Include header text for each page -footer <html-code> Include footer text for each page -top <html-code> Include top text for each page -bottom <html-code> Include bottom text for each page -link <url> Create links to javadoc output at <url> -linkoffline <url> <url2> Link to docs at <url> using package list at <url2> -excludedocfilessubdir <name1>:.. Exclude any doc-files subdirectories with given name. -group <name> <p1>:<p2>.. Group specified packages toget her in overview page -nocomment Supress description and tags,generate only declarations. -nodeprecated Do not include @deprecated information -noqualifier <name1>:<name2>:... Exclude the list of qualifiers from the output. -nosince Do not include @since information -notimestamp Do not include hidden time stamp -nodeprecatedlist Do not generate deprecated list -notree

100

Programming in Java Do not generate class hierarchy -noindex Do not generate index -nohelp Do not generate help link -nonavbar Do not generate navigation bar -serialwarn Generate warning about @serial tag -tag <name>:<locations>:<header> Specify single argument custom tags -taglet The fully qualified name of Taglet to register -tagletpath The path to Taglets -charset <charset> Charset for cross-platform viewing of generated documentation. -helpfile <file> Include file that help link links to -linksource Generate source in HTML -sourcetab <tab length> Specify the number of spaces each tab takes up in the source -keywords Include HTML meta tags with package, class and member info -stylesheetfile <path> File to change style of the generated documentation -docencoding <name> Output encoding name

101

Programming in Java

COURSE SCHEDULE TOPIC Introduction, OOPS & Java Introduction Programming Basics (Data Types, Variables, Input & Output, Control Structure, Arrays) Classes & Objects Inheritance Packages & Interfaces Exception Handling Multithreading String Handling Input & Output Streams Applets AWT Event Handling Socket Programming Collections DAYS 1 4 3 2 3 2 3 2 4 2 3 2 2 2 35

102

You might also like