Java
Java
UNIT –I:
Introduction: Introduction to Java-Java & Internet- Byte codes -Features of Java–
Java Development Environment – Java Character set-Operators- Control Statements-Simple
Programs-Java History & features- Java Development Kit(JDK)-Java Tokens-Java
Statements-Arrays& Vectors-Strings & String buffers.
UNIT-II:
Classes , Interfaces and packages: Classes -Objects- Wrapper Classes- Packages
and Interfaces.
UNIT-III:
Inheritance: Inheriting Extending classes-abstract and Final classes- Interfaces and
Inheritance.
UNIT -IV:
Exception Handling: Error Handling- Exception Types and Hierarchy-Try Catch
blocks-use of Throw, Throws and finally-programmer Defined Exceptions.
UNIT-V:
Applet and Graphics: Fundamentals of Applets-Graphics. AWT and Event
Handling: AWT Components and Event Handlers – AWT Controls and Event Handling –
Types and Examples-Swing introduction. Input and output: files –streams. Multithreading
and networking: multiple threads- networking basics.
TEXT BOOK:
1) Patrick Naughton, Herbert Schildt, “JAVA2- The Complete Reference”, Tata
McGraw Hill, fifth Edition, New Delhi, 2002.
2) Hubbard John R, “ Schaum’s Outline of theory and problems of programming
with Java”,Tata McGraw Hill , Second Edition, New Delhi,2004.
-1-
UNIT I
The Java programming language enables the Web documents authors to deliver small
application programs to anyone browsing the pages of the html documents.
The page becomes alive because it can create game score boards, execute animated
cartoons, audio files and video clippings.
-2-
BYTE CODES:
Byte code is the intermediate representation of Java programs just as assembler is the
intermediate representation of C or C++ programs.
The most knowledgeable C and C++ programmers know the assembler instruction
set of the processor for which they are compiling.
This knowledge is crucial when debugging and doing performance and memory
usage tuning.
Knowing the assembler instructions that are generated by the compiler for the source
code you write, helps you know how you might code differently to achieve memory
or performance goals.
In addition when tracking down a problem, it is often useful to use a debugger to
disassemble the source code and step through the assembler code that is executing.
Java is the bytecode that is generated by the javac compiler.
Understanding bytecode and what bytecode is likely to be generated by a java
compiler helps the java programmer in the same way that knowledge of assembler
helps the C or C++ programmer.
The bytecode is your program.
Consider that the more bytecode you have, the bigger the .class file is and the more
code that has to be compiled by a JIT or Hotspot runtime.
FEATURES OF JAVA:
Sun Microsystems officially describes java with the following attributes:
Compiled and Interpreted
Platform-Independent and Portable
Object-Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High performance
Dynamic and Extensible
-3-
Compiled and Interpreted
- A computer language is either complied or interpreted.
- Java combines both theses approaches thus making Java a two-stage system.
- First, Java compiler translates source code into byte code instructions.
- Second, Java interpreter generate machine code that can be directly executed
in the machine that is running the Java program.
Platform-Independent and Portable
- The most significant contribution of java over other languages is its
portability.
- Java programs can be easily moved from one computer system to another,
anywhere and anytime.
- Changes and upgrades in Os and processors will not force any changes in java
programs.
- Java ensures portability in two ways. First, Java compiler generates byte code
instructions that can be implemented on any machine.
- Second, the size of the primitive data types is machine independent.
Object-Oriented
- Java is a true object-oriented language.
- Everything in java is an object.
- All programs and data reside within objects and classes.
- Java comes with an extensive set of classes, arranged in packages, that can be
used by inheritance.
Robust and Secure
- Java is a robust language.
- It provides many safeguards to ensure reliable code.
- It has strict compile time and run time checking for data types.
- Java also incorporates the concept of exception handling which captures series
errors and eliminates any risk of crashing the system.
- Security becomes an important issue for a language that ensures no viruses are
communicated with an applet.
-4-
Distributed
- Java is designed as a distributed language for creating applications on
networks.
- It has the ability to share both data and programs.
- This enables multiple programmers at multiple remote locations to collaborate
and work together on a single project.
Simple, Small and Familiar
- Java is a small and simple language. Many features of C and C++ are not part
of java.
- Java does not use pointers, preprocessor header files, goto statement and many
others.
- It also eliminates operator overloading and multiple inheritance.
- Java is a simplified version of C++.
Multithreaded and Interactive
- Multithreaded means handling multiple tasks simultaneously.
- Java supports multithreaded programs. This means that we need not wait for
the application to finish one task before beginning another.
- This feature greatly improves the interactive performance f graphical
applications.
High performance
- Java architecture is also designed to reduce overheads during runtime.
- The incorporation of multithreading enhances the overall execution speed of
java programs.
Dynamic and Extensible
- Java is a dynamic language. Java is capable of linking in new class libraries,
methods, and objects.
- Java programs support functions written in other languages such as C and C+
+. These functions are known as native methods.
-5-
Java Development Environment :
- Java environment includes a large number of development tools and hundreds
of classes and methods.
- The development tools are part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java Standard Library
(JSL), also known as the Application Programming Interface(API).
CHARACTER SET:
Characters are the smallest unit of java language.
These are used to write java tokens.
Java characters are defined by Unicode character set.
The Unicode is a 16 bit character coding system and currently supports more than
34,000 defined characters derived from 24 languages.
JAVA OPERATORS:
- Java supports a rich set of operators.
- Java operators can be classified as unary, binary or ternary-meaning taking
one, two, or three arguments, respectively.
- A unary operator may appear before (prefix) its argument or after(postfix) its
argument.
- A binary or ternary operator appears between its arguments.
- An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.
- Java operators can be classified into a number of related categories as below:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
-6-
8. Special operators
1. Arithmetic operators
- Java provides all the basic arithmetic operators.
- The operators +, -, *, and / all work the same way as they do in other
languages.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Integer Arithmetic
- When both the operands in a single arithmetic expression such as a+b are
integers, the expression is called an integer expression, ant the operation is
called integer arithmetic.
- A=14, b=4 , we have the following results:
A – b = 10
A + b = 18
A * b = 56
A/ b=3
A%b=2
Real Arithmetic
- An arithmetic operation involving only real operands is called real arithmetic.
- A real operand may assume values either in decimal or exponential notation.
Ex:
A = 20.5, b = 6.4
-7-
A + b = 26.9
A – b = 14.1
Mixed-mode Arithmetic
- When one of the operands is real and the other is integer, the expression is
called a mixed-mode arithmetic expression.
- Ex: a=10, b=3.5
A+b=13.5
a-b=6.5
2. Relational Operators
- We often compare two quantities, and depending on their relation, take
certain decisions.
- These comparisons can be done with the help of relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Ex:
A>b
A +b = = c + d
-35 > = 0
Logical Operator
- In addition to the relational operators, java has three logical operators, which
are given below:
-
-8-
Operator Meaning
Assignment operators
- Assignment operators are used to assign the value of an expression to a
variable.
- We have seen the usual assignment operator, ‘ = ‘.
- Java has a set of ‘shorthand’ assignment operators which are used in the form
V op= exp;
-9-
++m or m++;
--m or m—
++m; is equal to m = m + 1; or m += 1;
- A prefix operator first adds 1 to the operand and then the result is assigned to
the variable on left.
- A postfix operator first assigns a value to the variable on left and then
increments the operand.
Conditional Operator
- The character pair ?: is a ternary operator available in java.
- This operator is used to construct conditional expression of the form
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
- 10 -
Special Operators
- Java supports some special operators of interest such as instanceof and
member selection operator (.)
Instanceof Operator
- The instanceof is an object reference operator and returns true if the object on
the left-hand side is an instance of the class given on the right hand side.
- This operator allows us to determine whether the object belongs to particular
class or not.
Ex:
person instanceof student
- is true if the object person belongs to the class student; otherwise it is false.
Dot Operator
- The dot operator is used to access the instance variables and methods of class
objects.
- Ex:
Person1.age // Reference to the variable age
Person1.salary // Reference to the method salary
CONTROL STATEMENTS:
- A java program is a set of statements, which are normally executed
sequentially in the order in which they appear.
- When a program breaks the sequential flow and jumps to another part of the
code, it is called branching.
- When the branching is based on a particular condition, it is known as
conditional branching.
- If branching takes place without any decision, it is known as unconditional
branching.
- 11 -
- Java supports the following statements known as control or decision making
statements.
1. If statement
2. switch statement
3. Conditional operator statement
IF statement
- The if statement is a powerful decision making statement and is used to
control the flow of execution of statements.
- It is basically a two-way decision statement and is used in conjunction with an
expression.
- It takes the following form:
If (test expression)
- It evaluates the computer to evaluate the expression first and then depending
on whether the value of an expression is ‘true’ or ‘false’, it transfers the
control to a particular statement.
- This has two paths to follow, one for the true and the other for the false.
Entry
False
Test
expres
sion ?
True
Ex:
1. If (bank balance is zero)
Borrow money
2. If (room is dark)
- 12 -
Put on lights
If (test expression)
{
statement-block;
}
statement-x;
Ex:
If (category = = sports)
{
marks = marks + bonus_marks;
}
System.out.println(marks);
……….
The IF…ELSE statement
- The if…else statement is an extension of the simple if statement. The general
form is
If (test expression) --
{
True-block statement (s)
}
else
{
- 13statement
False-block - (s)
}
statement-x;
- If the test expression is true, then the true-block statements immediately
following the if statement, are executed; Otherwise the false-block statements
are executed.
- In either case, either true-block or false-block will be executed, not both.
- In both the cases, the control is transferred to the statement-x.
Ex:
………..
if (code = = 1)
boy = boy + 1;
else
girl = girl + 1;
xxx;
………….
If (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
- 14 -
statement-x;
- If the condition-1 is false, the statement-3 will be executed; otherwise it
continues to perform the second test.
- If the condition-2 is true, the statement-1 will be evaluated; otherwise the
statement-2 will be evaluated and then the control is transferred to the
statement-x.
Ex:
……..
if (sex is female)
{
if(balance > 5000)
bonus = 0.05 * balance;
else
bonus = 0.02 * balance;
}
else
{
bonus = 0.02 * balance;
}
balance = balance + bonus;
……………
……………
Ex:
If (marks > 79)
Grade = “Honours”;
Else if (marks > 59)
Grade = “First division”;
Else if (marks > 49)
Grade = “Second division”;
Else if (marks > 39)
Grade = “Third division”;
Else
Grade = “Fail”;
System.out.println (“Grade: “+ grade);
- 16 -
- The switch statement tests the value of a given variable against a list of case
values and when a match is found, a block of statements associated with that
case is executed.
- The general form of the switch statement is as shown below:
Switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
………
………
default:
default-block
break;
}
statement-x;
Repetition Statements:
Looping
- The process of repeatedly executing a block of statements is known as looping.
- The java language provides for three constructs for performing loop operations.
1. The while statement
2. The do statement
3. the for statement
Initialization;
While (test condition)
{
body of the loop
- 18 -
}
- The while is entry-controlled loop statement.
- The test condition is evaluated and if the condition is true, then the body of the
loop is executed.
- This process of repeated execution of the body continues until the test
condition becomes false and the control is transferred out of the loop.
Ex:
………….
sum = 0;
n =1;
while (n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
system.out.println(“Sum = “ + sum);
The DO statement
- It has the following form
Initialization;
do
{
body of the loop
}
While (test condition)
- 20 -
}
Do
{
………
………
if(condition)
break;
……….
}while(…….)
…………….
- 21 -
For(……..)
{
.……..
For (………)
{
if (condition)
break;
………..
}
…………..
}
Continue;
For (………)
{
………..
if (condition)
continue;
………..
}
- 22 -
Return statements:
It is a special branching statement that transfers the control to the caller of the
method.
This statement is used to return a value to the caller method and terminates execution
of method.
This has two forms: one that returns a value and the other that can not return, the
returned value type must match the return type of method.
Syntax:
return:
return values;
- The best way to learn a new language is to write a few simple example
programs and execute them.
- 23 -
Ex:
Class sampleone
{
public static void main(String args[])
{
System.out.println(“Java is better than c++”);
}
}
Class Declaration:
- The first line Class sampleone declares a class. Everything must be placed
inside a class.
- Class name is a valid keyword.
Opening Brace:
- Every class definition in java begins with an opening brace “{“ and ends with
a matching closing brace “}”.
- 24 -
The Output line:
- The only executable statement in the program is
System.out.println(“Java is better than C++’);
- This is similar to the printf() statement of C or cout << construct of C++.
- The println method is a member of the out object, which is a static data
member of System class.
- Every java statement must end with a semicolon.
- 25 -
Sun Microsystems officially describes java with the following attributes:
Compiled and Interpreted
Platform-Independent and Portable
Object-Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High performance
Dynamic and Extensible
- The Java development Kit comes with a collection of tools that are used for
developing and running java programs. They include
- Appletviewer (for viewing java applets)-this tool can be used to run and debug
java applets without a web browser.
- Javac (java compiler) , which converts source code into Java bytecode.
- Java (java interpreter)
- Javap (java disassembler)
- Javah (for C header files)
- Javadoc (for creating HTML documents)
- Jdb (Java debugger)
- 26 -
Text Editor
Javac
Java Jdb
Java Program
output
- 27 -
Applet Package: This includes a set of classes that allows us to create Java
applets.
JAVA TOKENS:
A token is an individual element in a program.
More than one token can appear in a single line separated by white spaces.
Keywords , identifiers, operators, separators, literals.
Java character set: Characters are the smallest unit of java language.
These are used to write java tokens.
Java characters are defined by Unicode character set.
KEYWORDS:
Keywords are words which belong to java language.
They have standard predefined meaning. These words should be used only for their
intended purpose. The keywords should be written in lowercase. Some of the
keywords are:
o For , do, while, goto, if ,else, int, char, byte, switch, void, try, catch,
public,protected, private, static, throw, throws.
IDENTIFIERS:
Identifiers are names given to classes, methods, variables, objects,
arrays, packages, and interfaces in a program. These are user defined names.
Rules:
Identifiers are formed with alphabets, digits, underscore, and dollar
sign characters.
The first character must be an alphabet.
They can be any length.
They are case sensitive.
LITERALS:
Literals are names that represent constant values.
A constant is a quantity that does not change during program execution. There are
five types of literals. They are
- 28 -
o Interger literal
o Floating point literals
o Character literals
o String literals
o Boolean literals
Operators:
An operator is a symbol which represents some operation that can be
performed on data.
There are eight operators in java.
They are Arithmetic operators, relational,logical,short hand assignment
,increment and decrement operators, conditional, bitwise, special operators.
Separators:
Separators are symbols which belong to java language.
These are used to indicate where group of codes are divided and arranged.
There are six operators available. They are
o ( ) Parenthesis – used to enclose arguments.
o { } braces – used to enclose block of codes.
o [ ] bracksets – used in arrays.
o ; Semicolon-used to separate statements.
o , comma- used separate variable in declaration.
o .Period – used to separate package names from sub-packages and classes.
JAVA STATEMENTS:
The java statements in java are like sentences in natural languages.
A statement is an executable combination of tokens ending with a
semicolon(;) mark.
Statements are usually executed in sequence in the order in which they
appear.
List of Statement:
- 29 -
1) Empty Statement – These do nothing and are used during program development as a
place holder.
2) Labelled Statement – Any statement may begin with a label. Such labels must not be
keywords.
3) Expression Statement – Most statements are expression statements.
Statements : Assignment, pre-increment,pre-decrement,post-increment,post-decrement,
method call and allocation Expression.
4) Selection Statement – Theae select one of several control flows. There are 3 types of
selection statements in java: if, if-else and switch.
5) Iteration Statement – These specify how and when looping will take place. There are
3 types of iteration statements: while, do, and for.
6) Jump Statement – It pass control to the beginning or end of the current block, or to a
labeled statement. Such labels must be in the same block, and continue, return, throw.
7) Synchronization Statement – Used for handling issues with multi-threading.
8) Guarding Statement – It used for safe handling of code that may cause exceptions.
number[0]
number[1]
number[2]
number[3]
number[4]
Number[0] 353
35
Number[1] 40
Number[2] 20
Number[3]
57
Number[4] 19
Creating an Array
- Arrays must be declared and created in the computer memory before they are
used.
- Creation of an array involves three steps:
Form2
Type[] arrayname;
Examples:
- Int number[];
- Float average[];
- Int[] counter;
Creation of Arrays
- After declaring an array, we need to create it in the memory.
- Java allows creating arrays using new operator only, as shown below.
Examples:
Number = new int[5];
Average = new float [10];
Initialization of Arrays
- The final step is to put values into the array created. This process is known as
initialization.
- This is done using the array subscripts as shown below.
- We can also initialize arrays automatically in the same way as the ordinary
variables when they are declared, as shown below.
- 32 -
Type arrayname[] = (list of values);
Array length
- In java, all arrays store the allocated size in a variable named length.
- We can access the length of the array a using a.length.
- Example: int a Size = a.length;
Example:
Class NumberSorting
{
Public static void main(String args[])
{
int num[] = {55, 40, 80, 65, 71};
int n = num.length;
System.out.print(“Given list:”);
For(int I = 0; I < n; i++)
{
system.out.print(“ “ + num[i]);
}
system.out.println(“\n”);
for(int I = 0; I < n; i++)
{
for (int j = I + 1; j < n; j++){
if(num[i] < num[j])
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
- 33 -
}
}
system.out.print(“Sorted list :”);
For(int I = 0; I < n; i++){
system.out.print(“ “ + num[i]);
}
system.out.println(“ ”);
}
}
Output:
Given list : 55 40 80 65 71
Sorted list : 80 71 65 55 40
X[0][1]
X[0]
X[1] x[1][3]
X[2]
X[2][2]
VECTORS:
C and C++ programmers will know that generic utility functions with variable
arguments can be used to pass different arguments depending upon the calling
situations.
Java does not support the concept of variable arguments to a function.
This feature can be achieved in java through the use of the Vector class contained
in the java.util package.
This class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number.
The objects do not have to be homogenous.
Arrays can be easily implemented as vectors.
Vectors are created like arrays as follows:
o Vector intVect = new Vector( ); // declaring without size
o Vector list = new Vector(3); // declaring with size
A vector can be declared without specifying any size explicitly.
A vector can accommodate an unknown number of items.
Vectors possess a number of advantages over arrays:
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. we can add and delete objects from the list as and when required.
- 35 -
A major constraint in using vectors is that we cannot
directly store simple data types in a vector; we can only store objects.
We need to convert simple types to objects.
The vector class supports a number of methods that can be
used to manipulate the vectors created.
Important Vector methods:
List.addElement(item) - Adds the item specified to the list at the end
List.elementAt(10) - gives the name of the 10th object
List.size() - Gives the number of objects present
List.removeElement(item) - Removes the specified item from the list
List.removeElementAt(n) - Removes the item stored in the nth position of
the list
List.removeAllElements() - Removes all the elements in the list
List.copyInto(array) - copies all items from list to array
List.insertElementAt(item , n) - inserts the item at nth position
Example programs:
Import java.util.*;
Class languageVector
{
Public static void main(String args[])
{
Vector list = new Vector();
int length = args.length;
for(int i=0; i< length; i++)
{
List.addElement(args[i]);
}
list.insertElementAt(“COBOL”,2);
int size = list.size();
String listArray[] = new String[size];
- 36 -
list.copyInto(listArray);
System.out.println(“list of languages”);
for(int i=0 ; i< size; i++)
{
System.out.println(listArray[i]);
}
}
}
- 37 -
Like arrays it is possible to get the length of string using the length method of the string
class.
int m = firstName.length( );
String Buffer:
StringBuffer is a peer class of String.
While String creates strings of fixed_length, StringBuffer creates strings of flexible
length that can be modified in terms of both length and content.
We can insert characters and substrings in the middle of a string, or append another
string to the end.
StringBuffer Methods:
o S1. setChartAt(n, ‘x’) -Modifies the nth character to x
o S1.append(s2) - Appends the string s2 to s1 at the end
o S1.insert(n, s2) - Inserts the string s2 at the position n of the string s1
o S1.setLength(n) -Sets the length of the string s1 to n. if n<s1.length()
s1 is truncated. If n>s1.length() zeros are added to s1
UNIT II
CLASSES,INTERFACES AND PACKAGES:
CLASSES:
- 38 -
- Class provides a convenient method for packing together a group of logically
related data items and functions that work on them.
- In java, the data items are called fields and the functions are called methods.
- Class is a template for an object, and an object is an instance of a class.
Defining a Class
- Once the class type has been defined, we can create ‘variables’ of that type using
declarations that are similar to the basic type declarations.
- In java, these variables are termed as instances of classes.
- The basic form of a class definition is:
Adding variables
- Data is encapsulated in a class by placing data fields inside the body of the class
definition.
- These variables are called instance variables because they are created whenever
an object of the class is instantiated.
- We can declare the instance variables exactly the same way as we declare local
variables.
- Instance variables are also known as member variables.
Ex:
Class Rectangle
{
- 39 -
int length;
int width;
}
Adding Methods
- A class with only data fields has no life.
- Methods are declared inside the body of the class but immediately after the
declaration of instance variables.
- The general form of a method declaration is
- Let us consider the Rectangle class again and add a method getData ( ) to it.
Class Rectangle
{
int length;
int width;
void getData(int x , int y)
{
length = x;
length = y;
}
}
- 40 -
- We want to compute the area of the rectangle defined by the class. This can be
done as follows:
Class Rectangle
{
int length, width;
void getData (int x, int y)
{
length = x;
width = y;
}
int rectArea ( )
{
int area = length * width;
return (area);
}
}
OBJECTS:
Creating Objects
- Creating an object is also referred to as instantiating an object.
- Objects in java are created using the new operator. The new operator creates an
object of the specified class and returns a reference to that object.
- Example of creating an object of type Rectangle.
Rectangle rect1; // declare
Rect1 = new Rectangle ( ); // instantiate
- The first statement declares a variable to hold the object reference and the second
one assigns the object reference to the variable.
- Both statements can be combined into one as shown below:
Rectangle rect1 = new Rectangle ( );
- The instance variables of the Rectangle class may be accessed and assigned
values as follows:
Rect1.length = 15;
Rect1.width = 10;
Rect2.length = 20;
Rect2.width = 12;
Constructors
- It would be simpler and more concise to initialize an object when it is first
created.
- Java supports a special type of method, called a constructor, that enables an
object to initialize itself when it is created.
- Constructors have the same name as the class itself. They do not specify a return
type, not even void.
Ex:
Class rectangle
{
int length;
int width;
Rectangle (int x, int y) // constructor method
{
length = x;
width = y;
}
int rectArea( )
{
return (length * width);
- 42 -
}
}
Parameterized Constructor
- When a default constructor is used in a class, all the objects of the class will have the
same default values for their member data.
- Consider three objects of integer class which are declared as follows:
Integer a, b, c;
- A constructor, which takes arguments, is called parameterized constructor.
- The arguments are then assigned to the members of the class.
- The general form of a parameterized constructor in class A is as follows:
A(type arg1, type arg2,…., type argn)
{
member1 = arg1;
member2 = arg2;
:
membern = argn;
}
WRAPPER CLASSES:
Vectors cannot handle primitive data types like int, float,long,char and double.
Primitive data types may be converted into object types by using the wrapper classes
contained in the java.lang package.
- 43 -
The wrapper classes have a number of unique methods for handling primitive data
types and objects.
Converting Primitive Numbers to Object Numbers Using Constructor Methods:
- Java packages are classified into two types. The first category is known as Java API
packages and the second is known as user defined packages.
Creating Packages
- Let us see how to create our own packages.
- We must first declare the name of the package using the package keyword followed
by a package name.
- This must be the first statement in a java source file, then we define a class.
Ex:
Package firstpackage; // package declaration
Public class Firstclass // class definition
{
body of the class
}
- Creating our own package involve the following steps:
1. Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
- 45 -
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
Accessing a package
- Java system package can be accessed either using a fully qualified class name or
using a shortcut approach through the import statement.
- The import statement can be used to search a list of packages for a particular class.
- The general form of import statement for searching a class is as follows:
- Here package1 is the name of the top level package, package2 is the name of the
package that is inside the package1, and so on.
- We can have any number of packages in a package hierarchy. Finally, the explicit
classname is specified.
- Multiple import statements are allowed. The statement must end with a semicolon (;).
Ex: import firstpackage.secondpackage.Myclass;
- We can use another approach as follows:
Import packagename.*;
- The star( *) indicates that the compiler should search this entire package hierarchy
when it encounters a class name.
Drawback – It is difficult to determine from which package a particular member came
Advantage – We need not have to use long package names repeatedly in the program.
Using a Package
- The listing below shows a package named package1 containing a single class
ClassA.
- 46 -
Package package1
Public class ClassA
{
public void displayA( )
{
System.out.println (“Class A”);
}
}
- The source file should be named ClassA.java and stroed in the subdirectory package1
as stated earlier. The resultant ClassA.class will be stored in the same subdirectory.
Import package1.ClassA
Class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA ( );
objectA.displayA( );
}
}
- Now let us consider package named package2 containing again a single class as
shown below:
Package package2;
Public class ClassB
{
protected int m = 10;
public void displayB( )
{
System.out.println (“Class B”);
System.out.println(“m = “ + m);
}
}
- 47 -
- As usual, the source file and the compiled file of this package are located in the
subdirectory package2.
- The following program uses classes contained in both the packages and therefore it
imports package1 and package2.
Import package1.ClassA
Import package2.*;
class packageTest2
{
public static void main (String args[])
{
ClassA objectA = new ClassA ( );
ClassB objectB = new ClassB ( );
objectA.displayA ( );
objectB.displayB ( );
}
}
Interfaces
- Java does not support multiple inheritance. That is, classes in java cannot have more
than one superclass.
Class A extends B extends C
{
……………
} is not permitted in java.
- Java provides an alternate approach known as interfaces to support the concept of
multiple inheritance.
- 48 -
- Although a java cannot be subclass of more than one superclass, it can implement
more then one interface
Defining Interfaces
- An interface is a kind of class. Like classes, interface contain methods and variables
but with a major difference.
- The interfaces only define abstract methods and final fields.
- The syntax for defining an interface is very similar to that for defining a class.The
general form of an interface definition is:
Interface InterfaceName
{
variables declaration;
methods declaration;
}
- Methods declaration will contain only a list of methods without any body statements.
Extending Interfaces
- 49 -
- Like classes, Interfaces can also be extended. That is, an interface can be
subinterfaced from other interface.
- The new subinterface will inherit all the members of the superinterface in the manner
similar to subclasses.
- This is achieved using the keyword extends as shown below:
Ex:
Interface Itemconstants
{
int code = 1001;
string name = “Fan”;
}
interface Item extends Itemconstants
{
void display( );
}
- 50 -
Interface item extends Itemconstants, ItemMethods
{
…………….
}
- While interfaces are allowed to extend to other interfaces, subinterfaces
cannot define the methods declared in the superinterfaces.
Implementing Interfaces
- Interfaces are used as “superclasses” whose properties are inherited by classes. It is
necessary to create a class that inherits the given interface.
- This is done as follows:
- 51 -
{
public float compute ( float x, float y)
{
return ( x * y );
}
}
class InterfaceTest
{
public static void main (String args[]){
Rectangle rect = new Rectangle( );
Circle cir = new Circle ( );
Area area; // Interface object
Area = rect;
System.out.println (“Area of Rectangle = “ + area.compute (10,20));
Area = cir;
System.out.println (“Area of Circle = “ + area.compute (10,0));
}
}
The output is as follows:
Area of Rectangle = 200
Area of Circle = 314
Nested Interface
- An interface can be declared a member of a class or another interface. Such an
interface is called a member interface or a nested interface.
- A nested interface can be declared as public, private, or protected.
- When a nested interface is used outside of its enclosing scope, it must be qualified by
the name of the class or interface of which it is a member.
UNIT III
Types of Inheritance :
Single level Inheritance(only one super class)
Multiple Inheritance(several super classes)
Multilevel Inheritance(derived from a derived class)
Hierarchical Inheritance(one super class, many subclasses)
Java does not directly implement multiple inheritance.
Defining a subclass:
A subclass is defined as follows:
Class subclassname extends superclassname
{
Variable declaration;
Methods declaration;
}
- 53 -
Multilevel Inheritance
- Suppose a, B and C are three classes, if the class is derived from A and in turn C is
derived from the class B, it is said to exhibit multilevel inheritance.
- It is symbolically denoted as follows:
Hierarchical Inheritance
- Suppose A , B and C are three classes and the classes B and C are derived from the
class A. It is said to exhibit hierarchical inheritance.
- In hierarchical inheritance, there is only one base class and more than one derived
class.
- In essence hierarchical inheritance is the reverse of multiple inheritance.
- It is symbolically denoted as follows:
A Base Class
B C Derived Class
Hybrid Inheritance
- There arise some situations where we need to combine two or more types of
inheritance to satisfy the requirements.
- The combination of two or more types of inheritance leads to what is known as
hybrid inheritance.
- Suppose A, B, C and D are the classes where class B is derived from A, class C is
derived from both B and D.
- Symbolically which is depicted as follows:
- 54 -
A
B D
Inheritance Basics
- To inherit a class, you simply incorporate the definition of one class into another
by using the extends keyword.
- The following program creates a superclass called A and a subclass called B.
Ex:
Class A
{
int i, j;
void showij( )
{
System.out.println(“I and j : “ + i + “ “ + j);
}
}
Class B extends A
{
int k;
void showk( )
{
System.out.println(“K: “ + k);
}
void sum ( )
{
System.out.println(“i+j+k: “ + (i+j+k));
}
- 55 -
}
- 56 -
Final class Aclass {…………..}
Final class Bclass extends Someclass {……….}
- Any attempt to inherit these classes will cause an error and the compiler will not
allow it.
Declaring a class final prevents any unwanted extensions to the class.
- 57 -
The general form of an interface definition is:
Interface interfaceName
{
Variables declaration;
Methods declaration;
}
Interface is the key word and interfaceName is any valid java variable.
Static final type VariableName = Value;
Note that all variables are declared as constants.
Return-type methodName1 (parameter_list);
Interface item
{
Static final int code = 1001;
Static final String name = “Fan”;
Void display( );
}
EXTENDING INTERFACES:
Interfaces can also be extended. That is an interface can be subinterfaced from
other interfaces.
The new subinterfaces will inherit all the members of the superinterface in the
manner similar to subclasses.
Interface name2 extends name1
{
Body of name2
}
Example:
- 58 -
Interface ItemConstants
{
Int code = 1001;
String name = “Fan”;
}
Interface Item extends ItemConstants
{
Void display( );
}
IMPLEMENTING INTERFACES:
Interfaces are used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
Syntax:
(i) Class classname implements interfacename
{
Body of classname;
}
(ii) Class classname extends superclass implements interface1, interface2,…..
{
Body of classname;
}
Example for implementing interfaces:
Public class main{
Public static void main(String[] args)
{
Shape circleshape = new circle();
Circleshape.Draw();
}
}
Interface shape
- 59 -
{
Public String baseclass=”shape”;
Public void Draw();
}
Class circle implements shape
{
Public void Draw() {
System.out.println(“Drawing Circle here”);
}
}
ACCESSING INTERFACE VARIABLES:
Interface can be used to declare a set of constants that can be used in different classes.
The values can be used in any method, as part of any variable declaration, or
anywhere where we can use a final value.
For Example:
Interface A
{
Int m = 10;
Int n= 50;
}
Class B implements A
{
Int x=m;
Void method(int size)
{
………………..
…………………
If(size<n)
…………………
}
}
Interface A
- 60 -
implementation
Class B
Extension
Class C
UNIT-IV
Exception Handling:
Fundamentals:
- An exception is a condition that is caused by a run-time error in the program.
- When the java interpreter encounters an error such as dividing an integer by zero, it
creates an exception object and throws it.
- If the exception object is not caught and handled properly, the interpreter will display
an error message and will terminate the program.
- If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This task is known as
exception handling.
- The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken.
- The mechanism suggests incorporation of a separate error handling code that
performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information 9Catch the exception)
4. Take corrective actions (Handle the exception)
- 61 -
ERROR HANDLING:
- Errors are the wrongs that can make a program go wrong.
- An error may produce an incorrect output or may terminate the execution of the
program abruptly or even may cause the system to crash.
- To detect and manage properly all the possible error conditions in the program so that
the program will not terminate or crash during execution.
TYPES OF ERRORS:
Compile-time errors
Run-time errors
Compile-Time Errors:
All syntax errors will be detected and displayed by the Java compiler and therefore
these errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
Example:
Class Error1
{
Public static void main(String args[])
{
System.out.println(“Hello Java!”) // Missing
}
}
Most of the compile time errors are due to typing mistakes. Typographical errors
are hard to find.
We may have to check the code word by word, or even character by character.
The most common problems are:
o Missing semicolons
o Missing brackets in classes and methods
o Misspelling of identifiers and keywords
o Missing double quotes in strings
- 62 -
o Use of undeclared variables
o Incompatible types in assignments/initialization
o Bad references to objects
o Use of = in place of == operator
o And so on
Run-Time Errors:
A program may compile successfully creating the .class file but
may not run properly.
Programs may produce wrong results due to wrong logic or may
terminate due to errors such as stack overflow.
Most common run-time errors are:
Example:
Class Error2
{
Public static void main(String args[])
{
int a =10;
- 63 -
int b=5;
int c= 5;
int x= a/(b-c); // Division by zero
System.out.println(“x=”+x);
Int y=a/(b+c);
}
}
- The error handling code basically consists of two segments, one to detect errors and
to throw exceptions and the other to catch exceptions and to take appropriate actions.
- Java exception handling is managed via five keywords: try, catch, throw, throws and
finally.
- 64 -
- All exception types are subclasses of the built-in class Throwable. Throwable is at
the top of the exception class hierarchy.
- Immediately below Throwable are two subclasses that partition exceptions into two-
distinct branches.
- One branch is headed by Exception. This class can be used for exceptional conditions
that user programs should catch.
- There is important subclass of Exception, called RuntimeException.
- Exceptions of this type are automatically defined for the programs that you write and
include things such as division by zero and invalid array indexing.
- The other branch is topped by Error, which defines exceptions that are not expected
to be caught under normal circumstances by your program.
- Exceptions of type Error are used by the java run-time system to indicate errors
having to do with the run-time environment, itself.
Uncaught Exceptions
- When the java interpreter encounters an error such as dividing an integer by zero, it
creates an exception object and throws it.
- If the exception object is not caught and handled properly, the interpreter will display
an error message and will terminate the program.
- The try block can have one or more statements that could generate an exception. If
any one statement generates an exception, the remaining statements in the block are
skipped and exception jumps to the catch block that is placed next to the try block.
- The catch statement is passed a single parameter, which is reference to the exception
object thrown by the try block.
- If the catch parameter matches with the type of exception object, then the exception is
caught and statements in the catch block will be executed.
- Otherwise, the exception is not caught and the default exception handler will cause
the execution to terminate.
Ex:
Class Error3
{
public static void main (String args[ ])
{
int a = 10;
int b = 5;
int c = 5;
int x, y;
try
{
x = a / (b – c); // Exception here
}
catch (ArithmeticException e)
{
System.out.println (“division by zero”);
- 66 -
}
y = a / (b + c);
System.out.println( “y = “ + y);
}
}
Output:
Division by zero
y =1
Multiple Catch Clauses
- It is possible to have more than one catch statement in the catch block as illustrated
below:
……………
……………
try
{
statement; // generates an exception
}
catch (Exception-Type-1 e)
{
statement; // processes exception type 1
}
catch (Exception-Type-2 e)
{
statement; // processes exception type 2
}
.
.
catch (Exception-Type-N e)
{
statement; // processes exception type N
}
…………….
- 67 -
…………….
Example:
Class Error4
{
public static void main (String args[ ])
{
int a[ ] = { 5, 10 };
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch (ArithmeticException e)
{
System.out.println(“Divison by zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch (ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}
int y = a[1] / a[0];
System.out.println (“y =” + y);
}
}
Output:
Array Index error
Y=2
- 68 -
Nested try statements
- The try statement can be nested.
- A try statement cab be inside the block of another try.
- Each time a try statement is entered, the context of that exception is pushed on the
stack.
- If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a
match. This continues until one of the catch statements succeeds, or until the entire
nested try statements are exhausted.
- If no catch statement matches, then the Java run-time system will handle the
exception.
Use of Throw:
- It is possible to throw an exception using the throw statement.
- The general form of throw is shown here:
Throw ThrowableInstance
ThrowableInstance
Throws
- If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that
exception.
- You do this by including a throws clause in the method’s declaration.
- A throws clause lists the types of exceptions that a method might throw.
- 69 -
- This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.
- All other exceptions that a method can throe must be declared in the throws clause.
- The general form of a method declaration that includes a throws clause.
(i) Try
{
…………….
……………
}
Finally
{
……………..
……………..
}
(iii) try
{
…………
…………
Catch(………)
{
……………
……………
}
Catch(……)
{
…………..
…………..
}
- 70 -
.
.
.
.
Finally
{
…………..
……….....
}
The exception-handling can be used to hide errors from rest of the program.
It is possible that the programmers may misuse this technique for hiding errors rather
than debugging the code.
Exception handling mechanism may be effectively used to locate the type and place
of errors.
Once we identify the errors, we must try to find out these errors occur before we
cover them up with exception handlers.
Example:
Class invalidIntegerException extends Exception
{
invalidIntegerException(String s)
{
Super;
}
invalidIntegerException()
{
This(“ ”);
}
}
- 71 -
UNIT V
APPLETS AND GRAPHICS:
APPLET FUNDAMENTALS:
Applets are small applications that are accessed on an Internet Server, transported
over the Internet, automatically installed, and run as part of a web document.
Applets differ from console-based applications in several key areas.
Import java.awt.*;
Import java.applet.*;
Public class simpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“A simple Applet”, 20,20);
}
}
This applet begins with two import statements. The first imports the Abstract Window
Toolkit(AWT) classes.
Applets interact with the user through the AWT, not through the console based I/O
classes.
- 72 -
The AWT contains support for a window-based, graphical user interface.
Applets can also use Swing to provide the graphical user interface.
The second import statement imports the applet package, which contains the class
Applet.
After you enter the source code for SimpleApplet compile in the same way that you
have been compiling programs.
Running simpleapplet involves a different process.
There are two ways in which you can run an applet:
o Executing the applet within a Java-compatible web browser.
o Using an applet viewer, such as the standard tool, appletviewer
o An appletviewer executes your applet in a window. This is generally the
fastest and easiest way to test your applet.
To execute SimpleApplet with an applet viewer, you may also execute the HTML file
C:\>appletviewer RunApp.html
Method Description
Void destroy( ) Called by the browser just before an applet is
terminated.Your applet will override this
method if it needs to perform any cleanup
prior to its destruction.
AccessibleContext Returns the accessibility context for the
getAccessibleContext( ) invoking object.
AppletContext get AppletContext( ) Returns the context associated with the
applet.
String getAppletinfo( ) Returns a string that describes the applet.
AudioClip getAudioClip( URL url) Returns an AudioClip object that
encapsulates the audio clip found at the
location specified by url.
URL getCodeBase( ) Returns the URL associated with the
invoking applet.
URL getDocumentBase( ) Returns the URL of the HTML document
that invokes the applet.
Image getimage(URL url) Returns an image object that encapsulates the
image found at the location specified by url.
Void init( ) Called when an applet begins execution. It is
the first method called for any applet.
Void start( ) Called by the browser when an applet should
start execution. It is automatically called
after init( ) when an applet first begins.
Void stop( ) Called by the browser to suspend execution
of the applet. Once stopped, an applet is
- 75 -
restarted when the browser calls start( ).
Import java.awt.*;
Import java.applet.*;
…………
………….
Public class appletclassname extends Applet
{
……………..
…………….
Public void paint(Graphics g)
{
……………..
…………….. //applet operations code
- 76 -
}
……………
}
The appletclassname is the main class for the applet.
When the applet is loaded, java creates an instance of this class, and then a
series of Applet class methods are called on that instance to execute the code.
Import java.awt.*;
Import java.applet.*;
Public class HelloJava extends applet
{
public void paint(Graphics g)
{
g.drawString(“Hello Java”,10,100);
}
}
OUTPUT:
- 77 -
Java.applet.Applet
java.awt.Panel
Java.lang.Object
java.awt.Component
java.awt.Container
- 78 -
Begin
(load Applet) Initialization
stop()
Display
Paint()
Stopped
Destroy()
Start()
Destroyed End
Exit of Browser
Initialization State:
Applets enters the initialization state when it is first loaded.
This is achieved by calling the init() method of applet Class.
The applet is born. At this stage we may do the following, if required
o Create objects needed by the applet
o Set up initial values
o Load images or fonts
o Set up colors.
The initialization occurs only once in the applet’s life cycle.
- 79 -
To provide any of the behaviours mentioned above, we must override the init()
method.
Public void init()
{
…………….
……………(Action)
……………
}
Running State:
Applet enters the running state when the system calls the start() method of applet
class.
This occurs automatically after the applet is initialized.
Starting can also occur if the applet is already in “stopped”(Idle) state.
For example we may leave the Web page containing the applet temporarily to another
page and return back to the page.
This again starts the applet running.
Init() method, the start() method may be called more than once.
We may override the start() method to create a thread to control the applet.
Public void start( )
{
…………….
…………….(Action)
…………….
}
- 80 -
Public void stop()
{
………..
……….(Action)
………
}
Dead State :
An applet is said to be dead when it is removed from memory.
This occurs automatically by invoking the destroy() method when we quit the
browser.
Destroying stage occurs only once in the applet’s life cycle.
Public void destroy( )
{
...........
………(action)
………..
}
Display State:
Applets moves to the display state whenever it has to perform some output
operations on the screen.
This happens immediately after the applet enters into the running state.
The paint() methods is called to accomplish this task.
Public void paint (Graphics g)
{
...……..
……….
}
It is to be noted that the display state is not considered as a part of the applet’s
life cycle.
GRAPHICS PROGRAMMING:
- 81 -
The Graphics Class:
Java’s Graphics class includes methods for drawing many different types of
shapes, from simple lines to polygons to text in a variety of fonts.
The most commonly used drawing methods in the Graphics class.
X
(0,0) (80,0)
(20,20)
(60,60)
(0,80) (80,80)
Method Description
clearRect( ) Erases a rectangle area of the canvas.
copyArea( ) Copies a rectangular area of the canvas to another area.
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line
drawOval( ) Draws a hollow oval.
drawPolygon( ) Draws a hollow polygon.
drawRect( ) Draws a hollow rectangle.
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawString( ) Displays a text string
fillArc( ) Draws a filled arc.
fillOval( ) Draws a filled oval.
fillPolygon( ) Draws a filled polygon.
fillRect( ) Draws a filled rectangle.
fillRoundRect( ) Draws a filled rectangle with rounded corners.
getColor( ) Retrieves the current drawing colour.
getFont( ) Retrieves the currently used font.
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing colour.
setFont( ) Sets the font.
- 82 -
LINES AND RECTANGLES:
The simplest shape we can draw with the Graphics class is a line.
The drawLine( ) Method takes two pair of coordinates, (x1,y1) and (x2,y2) as
arguments and draws a line between them.
For example the following statement draws a straight line from the coordinate
point(10,10) to (50,50):
g.drawLine(10,10,50,50);
The g is the Graphics object passed to paint( ) method.
We can draw rectangle using the drawRect( ) method. This method takes four
arguments.
The first two represent the x and y coordinates of the top left corner of the
rectangle, and the remaining two represent the width and the height of the
rectangle.
g.drawREct(10,60) 40,30)
(x,y) height
Rectangle
We can draw a solid box by using the method fillRect( ).
This also takes four parameters corresponding to the starting point, the width and the
height of the rectangle.
g.fillRect(60,10,30,80);
example program:
import java.awt.*;
import java.applet.*;
public class LineRect extends Applet
- 83 -
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRect(60,10,30,80);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
}
}
LineRect.html file
<APPLET
CODE = lineRect.class
WIDTH = 250
HEIGHT= 200>
</APPLET>
- 84 -
public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(Color.green);
g.fillOval(70,30,100,100); // this is a circle.
}
g.setColor(Color.green);
After setting the color, all drawing operations will occur in that color.
Appletloader started.
The method getParameter( ) is used to fetch the data values from the HTML
file.
The method getParameter( ) returns only string values and therefore we use
the wrapper class method parseInt( ) to convert strings to integer values.
Example Program:
Import java.awt.*;
Import java.applet.*;
Public class Barchart extends Applet
{
int n=0;
String label[ ];
Int value[ ];
Public void init( )
{
try
{
n = Integer.parseInt(getParameter(“columns”));
label = new String[n];
value = new int [n];
label[0] = getParameter(“label1”);
label[1] = getParameter(“label2”);
label[2] = getParameter(“label3”);
label[3] = getParameter(“label4”);
value[0] = Integer.parseInt(getParameter(“c1”));
value[1] = Integer.parseInt(getParameter(“c2”));
- 87 -
value[2] = Integer.parseInt(getParameter(“c3”));
value[3] = Integer.parseInt(getParameter(“c4”));
}
catch ( NumberFormatException e) { }
}
public void paint(Graphics g)
{
for(int i=0; i<n; i++)
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.fillRect(50,i*50+10,value[i],40);
}
}
}
- 89 -
Java defines two types of streams: byte and character .
Byte streams provide a convenient means for handling input and output of bytes.
Byte streams are used for example, when reading or writing binary data.
Character streams provide a convenient means for handling input and output of
characters.
They use Unicode and therefore can be internationalized.
Character streams are more efficient than byte streams.
One other point: at the lowest level all I/O is still byte-oriented.
The character-based streams simply provide a convenient and efficient means for
handling characters.
- 90 -
The Character Stream Classes:
Character streams are defined by using two class hierarchies.
At the top are two abstract classes, Reader and writer.
These abstract classes handle Unicode character streams . Java has several concrete
subclasses of each of these.
The abstract classes reader and writer define several key methods that the other
stream classes implement.
Stream class Meaning
BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Input stream that Writes from a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
FilterReader Filtered reader
Filterwriter Filtered writer
- 91 -
String getName();
Byte Streams:
Byte streams are defined by using two class hierarchies.
At the top are two abstract classes: InputStream and OutputStream.
Each of these abstract classes has several concrete subclasses that handle the
differences between various devices, such as disk files, network connections, and
even memory buffers.
The abstract classes InputStream and OutputStream define several key methods
that the other stream classes implement.
Two of the most important are read( ) and Write( ) which respectively read and
write bytes of data.
DataInputStream BufferedInputStream
- 92 -
DataOutputStream BufferedOutputStream
1. voidwrite(intb)throwsIOException
2. voidwrite(byteb[])throwsIOException
3. voidwrite(byteb[],intoffset,intlength)throwsIOException
4. Subclasses of OutputStream implement the above mentioned methods.
Reader
- 93 -
InputStreamreader CharArrayReader FilterReader
File Reader
Writer
FileWriter
Thread states:
During the life time of a thread, there are many states it can enter. They
include:
Newborn state
Runnable state
Running state
Blocked state
Dead state
A thread is always in one of these five states. It can move from one state to another via a
variety of ways.
State transition diagram of a thread:
New thread
NewBorn
Running
Running
DEAD
- 95 -
Idle Thread Blocked
(Not Runnable)
Newborn State:
When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running.
o Schedule it for running using start( ) method.
o Kill it using stop( ) method.
If we attempt to use any other method at this stage, an exception will be thrown.
New
born
Start Stop
Run Dea
nabl d
e state
state
Runnable State:
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
The thread has joined the queue of threads that are waiting for execution.
If all threads have equal priority then they are given time slots for execution in round
robin fashion i.e. first-come, first-serve manner.
The thread that relinquishes control joins the queue at the end and again waits for its
turn.
This process of assigning time to threads is known as time slicing.
yield
- 96 -
. Running Runnable Threads
Thread
Relinquishing control using yield( ) method
Running State:
Running means that the processor has given its time to the thread for its
execution.
The thread runs until it relinquishes control on its own or it is preempted by a
higher priority thread.
A running thread may relinquish its control in one of the following situations.
1. It has been suspended using suspend( ) method. A suspended thread can be
revived by using the resume( ) method. This approach is useful when we want
to suspend a thread for some time due to certain reason, but do not want to kill
it.
suspend
resume
2 It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep(time) where time is in milliseconds. This means that the
thread is out of the queue during this time period. The thread re-enters the runnable
state as soon as this time period is elapsed.
Sleep(t)
After t
- 97 -
Running Runnable Sleeping
Relinquishing control using sleep( ) method
3. It has been told to wait until some event occurs. This is done using the wait( )
method. The thread can be scheduled to run again using the notify( ) method.
Wait
Notify
Blocked State:
A thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy
certain requirements.
A blocked thread is considered “not runnable” but not dead and therefore fully
qualified to run again.
Dead State:
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run( ) method. It is a natural death.
A thread can be killed as soon it is born, or while it is running, or even when it is in
“not runnable”(blocked) condition.
THREAD PRIORITY:
Each thread is assigned a priority which affects the order in which it is scheduled
for running.
The threads of the same priority are given equal treatment by the java scheduler and
therefore they share the processor on a first-come, first-serve basis.
ThreadName.setPriority(intNumber);
- 98 -
The intNumber is an integer value to which the thread’s priority is set.
The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10.
The default setting is NORM_PRIORITY.
Most user-level processes should use NORM_PRIORITY, plus or minus 1.
Back-ground tasks such as network I/O and screen repainting should use a value very
near to the lower limit.
By assigning priorities to threads, we can ensure that they are given the attention they
deserve.
Whenever multiple threads are ready for execution the Java chooses the highest
priority thread and executes it.
It stops running at the end of run( ).
It is made to sleep using sleep( ).
It is told to wait using wait( ).
if another thread of a higher priority comes along, the currently running thread will be
preempted by the incoming thread thus forcing the current thread to move to the
runnable state.
The highest priority thread always preempts any lower priority threads.
NETWORKING:
NETWORKING BASICS:
- 99 -
This is accomplished through the use of a port, which is a numbered socket on a
particular machine.
A server process is said to “listen” to a port until a client connects to it.
Socket communication takes place via a 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.
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 data.
UDP User Datagram Protocol sits next to TCP and can be used directly to support
fast, connectionless, unreliable transport of packets.
Once a connection has been established, a higher-level protocol ensures , which is
dependent on which port you are using.
Port number 21 is for FTP; 23 is for Telnet ; 25 is for e-mail; 43 is for whois;79 is for
finger; 80 is for HTTP;119 is for netnews.
It is up to each protocol to determine how a client should interact with the port.
For example, HTTP is the protocol that web browsers and servers use to transfer
hypertext pages and images.
It is a quite simple protocol for a basic page browsing web server.
The numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describe a machine’s location in a name space.
An internet domain name is mapped to an IP address by the Domain Naming
Service(DNS).
InetAddress:
The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address.
You interact with this class by using the name of an IP host, which is more convenient
and understandable than its IP address.
The InetAddress class hides the number inside. InetAddress can handle both IPv4 and
IPv6 addresses.
Factory Methods:
- 100 -
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 merely a convention whereby static methods in a class return
an instance of that class.
Three commonly used InetAddress factory methods are shown here:
Static InetAddress getLocalHost( )
Throws UnknownHostException
Static InetAddress getByName(String hostname) throws
UnknownHostException
Static InetAddress[ ] getAllByName(String hostname) throws
UnknownHostException
The getLocalHost The getLocalHost() method simply returns the InetAddress object
that represents the local host.
The getByName() method returns an InetAddress for a host name passed to it.
If these methods are unable to resolve the host name, they throw an
UnknownHostException.
The getAllByName() factory method returns an array of InetAddress that represents
aa of the addresses that a particular name resolves to.
EX: Prints the addresses and names of the local machine and two well-known internet Web
sites.
Import java.net.*;
Class InetAddressTest
{
- 101 -
System.out.println(Address);
Address = InetAddress.getByName(“asborne.com”);
InetAddress SW[] = InetAddress.getAllByName(“www.nba.com”) ;
for(int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Output:
default/206.148.209.138
osborne.com/198.45.24.162
www.nba.com/64.5.96.214
www.nba. com/64.5.96.216
Instance Methods:
Boolean equals(Object other) Returns true if this object has the same
Internet address as other.
Byte[] getAddress() Returns a byte array that represents the
object’s IP address in network byte order.
String getHostAddress() Returns a string that represents the host
address associated with the InetAddress
object.
String getHostName() Returns a string that represents the host
name associated with the InetAddress
object.
Boolean isMulticastAddress() Returns true if this address is a multicast
address.
String toString() Returns a string that lists the host name and
the IP address for convenience.
Subclasses of InetAddress:
- 102 -
Java was able to add IPv6 functionality without breaking the existing code.
TCP/IP Client Sockets:
Socket(String hostname. Int port) throws Creates a socket connected to the named
UnknownHostException, IOException host and port.
Socket(InetAddress ipAddress, int port) Creates a socket using preexisting
throws IOException InetAddress object and a port.
Socket defines several instance methods. For example a socket can be examined
at any time for the address and port information associated with it by use the
following methods:
- 103 -
Int getPort( ) Returns the remote port to which the
invoking socket object is connected. It
returns 0 if the socket is not connected.
Int getLocalport( ) Returns the local port to which the
invoking socket object is bound. It returns
-1 if the socket is not found.
The input and output streams associated with a socket by use of the
getInputStream( ) and getOutputStream methods.
Each can thrown an IOException if the socket has been invalidated by a loss of
connection.
- 104 -