You are on page 1of 75

Content Developed by : Mr. Faiz Mohd Arif Khan & Mr.

Harish Kumar
1
Introduction to Java:
The term Java refers to more than just a computer language like C or Pascal. Java encompasses
several distinct components:
A high-level language Java is an object-oriented computer programming language whose
source code at a glance looks very similar to C and C++ but is unique in many ways.
Java bytecode A compiler transforms the Java language source code to files of binary
instructions and data called bytecode that run in the Java Virtual Machine.
Java Virtual Machine (JVM)
A JVM program takes bytecode as input and interprets the instructions just as if it were a
physical processor executing machine code.
All language compilers translate source code in machine code for a specific computer. Java
compiler does the same thing. Java compiler produces an intermediate code known as byte
code for a machine that does not exist physically, this machine is called Java Virtual
Machine(JVM) and it exists only inside the computer memory, it is a simulated computer with
in a computer. This virtual machine is not machine specific code, the machine specific code is
generated by the java interpreter by acting as a intermediate between virtual machine and real
machine.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
2
History of Java:
During 1990, James Gosling, Bill Joy and others at Sun Microsystems began developing a
language called Oak. They primarily intended it as a language for microprocessors embedded
in consumer devices such as cable set-top boxes, VCRs, and handheld computers (now known
as personal data assistants or PDAs). To serve these goals, Oak needed the following features:
platform independence, since it must run on devices from multiple manufacturers extreme
reliability (cant expect consumers to reboot their VCRs!) compactness, since embedded
processors typically have limited memory.
They also wanted a next-generation language that built on the strengths and avoided the
weaknesses of earlier languages. Such features would help the new language provide more
rapid software development and faster debugging.
By 1993 the interactiveTVand PDAmarkets had failed to take off, but internet and web activity
began its upward zoom. So Sun shifted the target market to internet applications and changed
the name of the project to Java. The portability of Java made it ideal for the Web, and in 1995
Suns HotJava browser appeared. Written in Java in only a few months, it illustrated the power
of applets programs that run within a browser and the ability of Java to accelerate program
development.
Versions of Java:
Since its introduction, Sun has released new versions of the Java core language with significant
enhancements about every two years or so. Until recently, Sun denoted the versions with a 1.x
number, where x reached up to 4. (Less drastic releases with bug fixes were indicated with a
third number as in 1.4.2.) The next version, however, will be called Java 5.0. Furthermore, Sun
has split its development kits into so-called editions, each aimed towards a platform with
different capabilities.
Standard Edition
Below is a time line for the different versions of the Standard Edition (SE) of Java, which offers
the core language libraries (called packages in Java) and is aimed at desktop platforms. We
include a sampling of the new features that came with each release.
1995 Version 1.0. The Java Development Kit (JDK) included:
8 packages with 212 classes.
Netscape 2.04.0 included Java 1.0.
Microsoft and other companies licensed Java.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
3
1997 Version 1.1
23 packages, 504 classes.
Improvements included better event handling, inner classes, improved VM. Microsoft
developed its own 1.1-compatible Java Virtual Machine for the Internet Explorer.
Many browsers in use are still compatible only with 1.1. Swing packages with greatly improved
graphics became available during this time but were not included with the core language.
1999 Version 1.2. Sun began referring to the 1.2 and above versions as the Java 2 Platform.
The Software Development Kit (SDK) included: 59 packages, 1520 classes.
Java Foundation Classes (JFC), based on Swing, for improved graphics and user interfaces, now
included with the core language. Collections Framework API included support for various lists,
sets, and hash maps.
2000 Version 1.3:
76 packages, 1842 classes.
Performance enhancements including the Hotspot virtual machine.
2002 Version 1.4:
135 packages, 2991 classes.
2004 Version 5.0 (previously known as 1.5).
It includes a number of tools and additions to the language to enhance program development,
such as: 4faster startup and smaller memory footprint, metadata, formatted output, generics
improved multithreading features.
165 packages, over 3000 classes
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
4
Features Of Java:
Before we examine how Java can benefit technical applications, we look at the features that
make Java a powerful and popular general programming language.
These features include:
Compiler/interpreter combination
Code is compiled to bytecode, which is interpreted by a Java Virtual Machine (JVM). This
provides portability to any base operating system platform for which a virtual machine has
been written.The two-step procedure of compilation and interpretation allows for extensive
code checking and improved security.
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
Assuming that you have some programming experience, you will not find Java hard to master.
If you already understand the basic concepts of object-oriented programming, learning Java
will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of the object-
oriented features of C++, most programmers have little trouble learning Java.
Object-oriented
Object-oriented programming (OOP) throughout no coding outside of class definitions.
The bytecode retains an object structure.
An extensive class library available in the core language packages.
Automatic memory management
A garbage collector in the JVM takes care of allocating and reclaiming memory.
Robust
Exception handling built-in, strong type checking (that is, all variables must be assigned an
explicit data type), local variables must be initialized.
Platform independence
The bytecode runs on any platform with a compatible JVM.
The Write Once Run Anywhere ideal has not been achieved (tuning for different
platforms usually required), but is closer than with other languages.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
5
Secure
The elimination of direct memory pointers and automatic array limit checking .
Untrusted programs are restricted to run inside the virtual machine sandbox. Access to
the platform can be strictly controlled by a Security Manager.
Code is checked for pathologies by a class loader and a bytecode verifier.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that do many things simultaneously
Dynamic binding
Classes, methods, and variables are linked at runtime.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
6
Object Oriented Concepts of Java:
Object-Oriented Programming
Object-oriented programming is at the core of Java. In fact, all Java programs are object
orientedthis isnt an option the way that it is in C++, for example. OOP is so integral to Java
that you must understand its basic principles before you can write even simple Java programs.
Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.
Two Paradigms
As you know, all computer programs consist of two elements: code and data. Furthermore, a
program can be conceptually organized around its code or around its data. That is, some
programs are written around what is happening and others are written around who is being
affected. These are the two paradigms that govern how a program is constructed.
The first way is called the process-oriented model. This approach characterizes a program as a
series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success. The
problems with this approach appear as programs grow larger and more complex. To manage
increasing complexity,
The second approach, called object-oriented programming, was conceived. Object-oriented
programming organizes a program around its data (that is, objects) and a set of well-defined
interfaces to that data. An object-oriented program can be characterized as data controlling
access to code
The Three OOP Principles
All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are encapsulation, inheritance, and polymorphism.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. One way to think about encapsulation is
as a protective wrapper that prevents the code and data from being arbitrarily accessed by
other code defined outside the wrapper/class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
7
Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly. However, by
use of inheritance, an object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent.
Polymorphism
Polymorphism (from the Greek, meaning many forms) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation. Polymorphism is a way by which an object can exhibit multiple behaviour in
multiple instances or situations.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
8
Class & Object:
Class: A class denotes a category of objects, and acts as a blueprint for creating such objects. A
class models an abstraction by defining the properties and behaviors for the objects
representing the abstraction. An object exhibits the properties and behaviors defined by its
class. The properties of an object of a class are also called attributes, and are defined by fields in
Java. A field in a class definition is a variable which can store a value that represents a
particular property. The behaviors of an object of a class are also known as operations, and are
defined using methods in Java. Fields and methods in a class definition are collectively called
members.
Object: Class Instantiation: The process of creating objects from a class is called instantiation.
An object is an instance of a class. The object is constructed using the class as a blueprint and is
a concrete instance of the abstraction that the class represents. An object must be created
before it can be used in a program. In Java, objects are manipulated through object references
(also called reference values or simply references). The process of creating objects usually
involves the following steps:
1. Declaration of a variable to store the object reference - This involves declaring a
reference variable of the appropriate class to store the reference to the object.
// Declaration of two reference variables that will denote/refer two distinct objects,
ClassName ob1, ob2;
2. Creating an object - This involves using the new operator in conjunction with a call to a
constructor, to create an instance of the class.
// Create two distinct objects.
Ob1 = new ClassName();
Ob2 = new ClassName();
The new operator returns a reference to a new instance of class. This reference can be
assigned to a reference variable of the appropriate class. Each object has a unique
identity and has its own copy of the fields declared in the class definition.
The purpose of the constructor call on the right side of the new operator is to initialize
the newly created object.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
9
Constructors in Java:
Constructors are special methods of class.
A constructor initializes an object immediately after creation.
Once defined, the constructor is automatically called immediately after the object is
creation.
Constructors look a little strange because :
They dont have any return type, not even void.
It has the same name as the class in which it resides.
The constructor is automatically invoked.
Types Of Constructors:
Default Constructor: Constructor with zero parameter called default constructor.
Parameterized Constructor: A constructor with one or more parameter called
parameterized constructor.
Constructor Example :
class ConstructorDemo {
ConstructorDemo() {
System.out.println(Default Constructor!!!);
}
ConstructorDemo(int a) {
System.out.println(Parameterized Constructor!!!);
}
}
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
10
Inheritance in Java:
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly. However, by
use of inheritance, an object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent.
Features of Inheritance:
One of the key concepts of OOP.
Establishes a hierarchical relationship among classes.
Establishes a super class/sub class relationship.
Establishes is a relationships.
A super class defines a general set of functionality, whereas subclasses define
functionalities specific to them.
In other sense, inheritance in Java builds a hierarchy of classes & thus supports the
concept of classification.
Inheritance is implemented in Java using extends keyword.
Benefits of Inheritance:
Reusability of code.
Put code in one class, use it in all the subclasses.
Write general purpose code designed for a super type that works for all subtypes.
Points to Remember :
Private members of the super class are not accessible by the sub class and can only be
indirectly accessed.
Constructors and Initializer blocks are not inherited by a subclass.
When you construct an object, the default base class constructor is called implicitly,
before the body of the derived class constructor is executed. So, objects are constructed
top-down under inheritance.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
11
Example :
class A{
A(){
System.out.println("Default constructor of class A");
}
A(int val){
System.out.println(Parameterized constructor of class A");
}
}
class B extends A{
B(){
System.out.println("Default constructor of class B");
}
B(int val){
System.out.println(Parameterized constructor of class B");
}
}
Predict the output.
B ref1 = new B();
B ref2 = new B(5);
Output :
Default constructor of class A
Default constructor of class B
Default constructor of class A
Parameterised constructor of class B
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
12
Inheritance Example :
class Calculator {
float num1, num2, ans;
float add() {
ans = num1 + num2;
return ans;
}
float sub() {
ans = num1 + num2;
return ans;
}
float mul() {
ans = num1 * num2;
return ans;
} }//End of Calculator Class
class ScientificCalculator extends Calculator {
float sqrt()
{
ans = (float)Math.sqrt(num1);
return ans;
} }//End of ScientificCalculator Class
class CalculatorDemo {
public static void main(String [] args) {
ScientificCalculator sc = new ScientificCalculator();
sc.num1 = 20.0f; sc.num2 = 10.0f;
sc.add(); sc.sub();
sc.mul(); sc.sqrt();
} }//End of CalculatorDemo Class
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
13
String Handling in Java:
Unlike many other languages that implement strings as character arrays, Java implements
strings as objects of type java.lang.String.
String are immutable objects in java means when you create a String object, you are creating a
string that cannot be changed. That is, once a String object has been created, you cannot
change the characters that comprise that string.
In some cases in which a modifiable string is desired, there is a companion class to String called
StringBuffer, whose objects contain strings that can be modified after they are created. Both the
String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs
automatically.
Constructor Of String Class :
String s = new String();
String s = new String(abcd);
char [] ch = {a,b,c,d};
String s = new String(ch);
Using String Literal ;
String s = abcd;
String Operation :
1. Concatenation :
Method that concatenates two strings, producing a String object as the result.
Eg :
String s1 = abcd;
String s2 = xyz;
String s3 = s1.concat(s2); //Using concat method of String class.
String s3 = s1 + s2; // Using + Operator for concatenation.
2. Length :
Returns the length of String as integer represents number of character encapsulated in
String objects
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
14
Eg:
String s = new String(Elephant);
Int len = s.length(); // return 8
3. Character Extraction :
char charAt(int index)
byte [] getBytes()
char [] toCharArray()
4. Comparison :
boolean equals(String str ) and
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object.
It returns true if the strings contain the same characters in the same order, and false otherwise.
The comparison is case-sensitive. To perform a comparison that ignores case differences, call
equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z.
5. Other Utility Method :
String toUpperCase()
String toLowerCase()
String trim()
int indexOf(char)
int indexOf(String str)
.etc
Java.lang.StringBuffer : StringBuffer is a peer class of String, that represents mutable type
String objects in Java.
StringBuffer defines these three constructors:
StringBuffer( ) Default Constructor
StringBuffer(int size) - int Defines size of String Object
StringBuffer(String str) to get StringBuffer object from String object
Example:
String s = new String(abc);
StringBuffer sb = new StringBuffer(s);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
15
Package in Java:
Java provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package. The package is both a naming and a visibility control
mechanism. You can define classes inside a package that are not accessible by code outside that
package.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored.
package MyPackage;
Finding Packages and CLASSPATH
As just explained, packages are mirrored by directories. This raises an important question: How
does the Java run-time system know where to look for packages that you create? The answer
has two parts. First, by default, the Java run-time system uses the current working directory as
its starting point. Thus, if your package is in the current directory, or a subdirectory of the
current directory, it will be found. Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable.
Importing Packages:
Java includes the import statement to bring certain classes, or entire packages, into visibility.
Once imported, a class can be referred to directly, using only its name. The import statement is
a convenience to the programmer and is not technically needed to write a complete Java
program. If you are going to refer to a few dozen classes in your application, however, the
import statement will save a lot of typing. In a Java source file, import statements occur
immediately following the package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pack1.subaack.* or class/interface Name
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
16
Package Example :
SourceCode : Message.java
package com;
public class Message {
public void showMessage(String name) {
System.out.println("Hello "+name);
}
} // End Of Message Class
Compiling Message.java javac d . Message.java
SourceCode : Test.java
import com.Message;
class Test {
public static void main(String [] args) {
Message m = new Message();
m.showMessage("United, Allahabad");
}
}//End Of Test Class.
Compile and Run Test.java javac Test.java
java Test
Output Hello United, Allahabad
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
17
Access Protection:
Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods. Packages act as containers for classes and other subordinate
packages. Classes act as containers for data and code. The class is Javas smallest unit of
abstraction. Because of the interplay between classes and packages,
Java addresses four categories of visibility for class members:
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories. While Javas access control mechanism
may seem complicated, we can simplify it as follows:
PUBLIC : Anything declared public can be accessed from anywhere.
PRIVATE : Anything declared private cannot be seen outside of its class.
DEFAULT : When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package. This is the default access.
PROTECTED : If you want to allow an element to be seen outside your current package, but
only to classes that subclass your class directly, then declare that element protected.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
18
Abstract methods and classes:
An abstract method is a method that's been declared (as abstract) but not implemented.
In other words, the method contains no functional code. And if you recall from the
earlier section " Abstract Classes," an abstract method declaration doesn't even have curly
braces for where the implementation code goes, but instead closes with a semicolon. In
other words, it has no method body. You mark a method abstract when you want to
force subclasses to provide the implementation.
A super class that only defines a generalized form that will be shared by all its sub
classes, leaving the implementation details to its subclasses is said to an abstract class.
A concrete class has concrete methods, including implementations of any abstract
methods inherited from its super classes.
Any class with abstract methods should be declared abstract.
Abstract Method & Class Example :
abstract class Shape { //abstract class
abstract double area(); //abstract method
void displayDetail() { //concrete method
System.out.println(Showing Details of Shape.);
}
}
class Square extends Shape{
double side;
double area() { //Overriding the abstract method.
return side*side;
}
}
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
19
Pointes to remember : Abstract classes and methods
An abstract class cannot have objects because it is not complete, but it can have
references.
Eg : Shape s = new Square();
Static methods and constructors cannot be declared abstract.
Eg: abstract static void show();
Any subclass of an abstract class must either implement all the abstract methods in the
super class or be itself declared abstract.
A concrete method can be overridden to become abstract.
It is illegal to declare a class and method both final and abstract.
Eg: abstract final void show();
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
20
Interface in Java:
Javas interfaces are an improvement over multiple inheritance mechanism of C++.
While designing a software system in java, Interfaces help us defining the interfaces
between the components.
Interfaces help us achieve a special kind of multiple inheritance : multiple
inheritance of interfaces without multiple inheritance of implementation.
When you create an interface, you're defining a contract for what a class can do,
without saying anything about how the class will do it. An interface is a contract.
Interfaces can be implemented by any class, from any inheritance tree. This lets you
take radically different classes and give them a common characteristic.
But while an abstract class can define both abstract and non-abstract methods, an
interface can have only abstract methods. Another way interfaces differ from abstract
classes is that interfaces have very little flexibility in how the methods and variables
defined in the interface are declared.
These rules are strict:
All interface methods are implicitly public and abstract. In other words, you do not need
to actually type the public or abstract modifiers in the method declaration, but the
method is still always public and abstract.
All variables defined in an interface must be public, static, and finalin other words,
interfaces can declare only constants, not instance variables.
Interface methods must not be static.
Because interface methods are abstract, they cannot be marked final.
An interface can extend one or more other interfaces.
An interface cannot extend any class.
An interface cannot implement another interface or class.
An interface must be declared with the keyword interface.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
21
Interface Example :
interface Shape {
float PI = 3.14F; //by default public, static and final
float area(); //by default public and abstract
}
class Square implements Shape {
float side ;
public void area() { //overriding area method of Shape Interface
return side*side
}
}
class ShapeDemo {
public static void main(String [] ar) {
Square s = new Square();
s.side = 2.3f;
float sarea = s.area();
System.out.println(AREA IS : +sarea);
}
}
OUTPUT:
AREA IS : 5.29
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
22
Polymorphism:
Polymorphism (from the Greek, meaning many forms) is a feature that allows one
interface to be used for a general class of actions. The specific action is determined by
the exact nature of the situation. Polymorphism is a way by which an object can
exhibit multiple behaviour in multiple instances or situations.
Types of polymorphism:
Compile Time Polymorphism Method Overloading
Run Time Polymorphism Method Overriding
Method Overloading :
Method overloading is a mechanism by which we can create more than one method
with the same name in the same class but their parameter or argument list should
be different. When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call. Thus, overloaded methods must differ in the type and/or number of
their parameters. While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a method. When Java
encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
We can overload the method by any one of the following changes in argument list:
Change the number of arguments.
Change the type of arguments.
Change the order of arguments.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
23
Method Overloading Example :
class Result {
void showResult() {
//Display the result of all students.
System.out.println("Display Results);
}
void showResult(String rollno) {
//Display the result of a student whose rollno is passed as argument.
System.out.println("Display Result : "+rollno);
}
}
class OverloadDemo {
public static void main(String [] args) {
Result ob = new Result();
ob.showResult();
ob.showResult("0901010071");
}
}
Output:
Display Results
Display Result : 0901010071.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
24
Method Overriding :
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its super class, then the method in the subclass is said to override the
method in the super class. When an overridden method is called from within a subclass,
it will always refer to the version of that method defined by the subclass
Method Overriding Example :
class Alto {
void speedoMeter() {
System.out.println("Analog System.");
}
void breakControl() {
System.out.println("Power Break System.");
} }//End Of Alto Class
class AltoK10 extends Alto {
void speedoMeter() {
System.out.println("Digital System.");
} }//End Of AltoK10 Class
class TestDrive {
public static void main(String [] args) {
Alto ob1 = new Alto();
Alto ob2 = new AltoK10();
ob1.speedoMeter(); ob1.breakControl();
ob2.speedoMeter(); ob2.breakControl();
} } //End Of TestDrive Class
Output :
Analog System.
Power Break System.
Digital System.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
25
Power Break System.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
26
Inner / Member Classes:
Sometimes, though, you find yourself designing a class where you discover you need
behavior that belongs in a separate, specialized class, but also needs to be intimately tied
to the class youre designing.
Member classes let you define one class within another.
They provide a type of scoping for your classes since you can make one class a
member of another class.
Just as classes have member variables and methods, a class can also have member
classes.
Types of Member Class :
o Inner Class.
o Nested Class.
o Method Local Inner Class.
o Anonymous Inner Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
27
Inner Class :
o One of the key benefits of an inner class is the special relationship an inner
class instance shares with an instance of the outer class.
o That special relationship gives code in the inner class access to members of the
enclosing (outer) class.
o An inner class instance has access to all members of the outer class, even those
marked private.
o The members of inner of class cannot be declared as static.
Inner Class Example :
class Outer {
void show() {
System.out.println("Hello From Show of Outer Class.");
}
class Inner {
void display() {
System.out.println("Hello From Display of Inner Class.");
}
}//End Of Inner Class
}//End Of Outer Class
class MemberClassDemo {
public static void main(String [] args) {
Outer o = new Outer();
o.show();
Outer.Inner i = o.new Inner();
//or
Outer.Inner i = new Outer.new Inner();
i.display();
}
}//End Of MemberClassDemo
Output :
Hello From Show of Outer Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
28
Hello From Display of Inner Class.
Nested Class :
o If we mark or specify the member class as static that member class is called
Nested Class.
o Nested Class can have static member data and methods.
o We can instantiate static member class outside the outer class without object of
outer class.
Nested Class Example :
class Outer {
static class Nested {
void display() {
System.out.println("Hello From Display of Nested Class.");
}
static void show() {
System.out.println("Hello From Static Show of Nested Class.");
}
}//End Of Nested Class
}//End Of Outer Class
class MemberClassDemo {
public static void main(String [] args) {
Outer.Nested.show();
Outer.Nested n = Outer.new Nested();
n.display();
}
}//End Of MemberClassDemo
Output :
Hello From Static Show of Nested Class.
Hello From Display of Nested Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
29
Method Local Inner Class (MLIC):
o We can define class with in a method that type of classes are called method local
inner class.
o A method-local inner class can be instantiated only within the method where
the inner class is defined.
o We cant mark a method-local inner class as public, private, protected, static,
transient . The only modifiers you can apply to a method-local inner class are
abstract and final.
MLI Class Demo :
class Test {
void show() {
class Local {
void print() {
System.out.println("Hello From Local Inner Class.");
}
}//End Of Local Class
Local l = new Local();
l.print();
}
}//End Of Test Class
class MLICDemo {
public static void main(String [] ar) {
Test t = new Test();
t.show();
}
}//End Of MLICDemo Class.
Output :
Hello From Local Inner Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
30
Anonymous Inner Class :
o An anonymous inner class is one that is not assigned a name.
o Were going to look at the most unusual syntax you might ever see in Java, inner
classes declared without any class name at all (hence the word anonymous).
Anonymous Inner Class Example :
class Test {
void show() {
System.out.println("Hello World from United!!!");
}
}//End Of Test Class
class AICDemo {
public static void main(String [] args) {
Test t1 = new Test();
//Anonymous Inner Class
Test t2 = new Test(){
void show() {
System.out.println("Hello World from UCER!!!");
}
}; //End Of Anonymous Inner Class
t1.show();
t2.show();
}
}//End Of AICDemo Class
Output :
Hello World from United!!!
Hello World from UCER!!!
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
31
Java IO (Input-Output)
Java programs perform Input Output through streams. A stream is an abstraction that
either produces or consumes information. A stream is simply a sequence of bytes that flows
into or out of our program. Its an abstract representation of an input or output device.
A stream is linked to a physical device by the Java IO stream.
All streams behave in the same manner even if the actual physical devices to
which they are linked differ.
Thus, the same IO classes and method can be applied to any type of decvice.
This means that an input stream can abstract many different kinds of input:
from a disk file, a keyboard or a network socket.
Java implements stream within class hierarchies define in the java.io package.
Types Of Streams:
o Byte or Binary Stream.
o Character Stream.
Byte/Binary Stream :
Byte stream provide a convenient means for handling IO of bytes. Byte streams are
used for example, when reading and writing binary data.
Byte streams are defined by using two class hierarchies. At the top are two abstract
class: java.io.InputStream and java.io.OutputStream. Each of these abstract classes has
several concrete sub classes, that handle the differences between various devices. The
abstract classes InputStream and OutputStream several key methods, that the other
stream classes implement. Two of the most important methods are read() and write(),
which respectively read and write bytes of data. Both methods are declared as abstract
inside InputStream and OutputStream. They are overridden by drived stream classes.
int read() throws IOException
Returns the next byte available from the stream as type int. If the end of the
stream is reached, the method will return the value -1.
int read(byte [] array) throws IOException
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
32
This method reads bytes from the stream into successive elements of
array. The maximum of array.length bytes will be read.
Similarly, we have methods for writing byte to stream;
void write(int data) throws IOException
void write(byte [] array) throws IOException
Character Stream:
Character streams provide a convenient means for handling IO of characters. They
use Unicode and therefore internationalized. Also, in some cases character stream are
more efficient than byte stream.
Character streams are defined by using two class hierarchies. At the top are two abstract
class: java.io.Reader and java.io.Writer. These abstracter class handle Unicode character
streams. Java has several concrete subclasses of each of these. . The abstract classes
Reader and Writer several key methods, that the other stream classes implement. Two of
the most important methods are read() and write().
Methods for performing character based reading operation:
int read( ) throws IOException
int read(char [] array) throws IOException
Methods for performing character based writing operation:
void write(int data) throws IOException
void write(char [] array) throws IOException
Read User Input from Standard IO :
Java does not have a generalized and standard console input methods like
scanf(), getc(), and gets() functions of C language. In Java, console input is accomplished
by reading from System.in (represents Standard Input Device i.e. Keyboard). We wrap
System.in in a BufferedReader, Scanner, DataInputStream..etc type objects to perform
read operation. BufferedReader supports buffered input stream, it is most commonly
used for taking user input in Java.
Using java.io.BufferReader class:-
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
33
System.out.println(Please Enter Your Name : );
String name = br.readLine();
System.out.println(Hello : +name);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
34
File Handling in Java:
Java provides a number of classes and methods that allow you to read and write files.
In Java, all files are byte-oriented, and Java provides methods to read and write bytes
from and to a file. However, Java allows you to wrap a byte-oriented file stream within
a character-based object. This technique is described in Part II. This chapter examines
the basics of file I/O.
Two of the most often-used stream classes are FileInputStream and FileOutputStream,
which create byte streams linked to files. To open a file, you simply create an object of
one of these classes, specifying the name of the file as an argument to the constructor.
While both classes support additional, overridden constructors,
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
FileOutputStream(String filename,boolean mode) throws FileNotFoundException
The FileReader and FileWriter classes creates a Reader and Writer that you can use to
read and write the contents from and to a file. Its most commonly used constructors are
shown here:
FileReader(String filePath) throws FileNotFoundException
FileWriter(String filePath) throws IOException
FileWriter(String filePath, boolean mode) throws IOException
File Content: Data.txt
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
35
File Reading Example : Read File(Data.txt) Content byte by byte
import java.io.*;
class ReadFileByteByByte {
public static void main(String [] args) throws Exception {
FileInputStream fis = new FileInputStream("Data.txt");
int ch;
while(true) { //infinite loop
ch = fis.read();
if(ch==-1) { //Check for EOF(End Of File)
break;
}
System.out.print((char)ch);
}//End Of While Block.
}//End Of Main Method.
}//End Of ReadFileByteByByte Class.
File Reading Example : Read File(Data.txt) Content Line By Line
import java.io.*;
class ReadFileLineByLine {
public static void main(String [] args) throws Exception {
FileInputStream fis = new FileInputStream("Data.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
while(true) { //infinite loop
line = br.readLine();
if(line==null) { //Check for EOL(End Of Line)
break;
}
System.out.println(line);
}//End Of While Block.
}//End Of Main Method.
}//End Of ReadFileLineByLine Class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
36
File Writing Example : Write Content to File(WriteData.txt) byte by byte
import java.io.*;
class WriteFileByteByByte {
public static void main(String [] args) throws Exception {
FileOutputStream fos = new FileOutputStream("WriteData.txt");
String data = "Pepsi - Nothing Official About It.";
for(int i=0;i<data.length();i++) {
fos.write(data.charAt(i));
} //End Of For Loop
System.out.print("Data Saved");
}//End Of Main Method.
}//End Of WriteFileByteByByte Class.
Output:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
37
Exception Handling in Java:
What is an Exception ?
Exception is an abnormal condition that occurs during the execution of a program, &
due to which the normal flow of the program's instructions may disrupt.
For example:-
class Test{
public static void main(String[] args){
System.out.println("Hello");
System.out.println(5/0);
System.out.println("Hello Again");
// do something else
}
}
output
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at NewClass.main(NewClass.java:3)
Throwing an Exception:
When an error occurs within a method, the run-time system creates an object and
hands it off to the method. The object, called an exception object, contains information
about the error, including its type and the state of the program when the error
occurred. Creating an exception object and handing it to the relevant method is called
throwing an exception.
After a method throws an exception, the runtime system attempts to find the ordered list
of methods that had been called to get to the method where the error occurred. The list
of methods is known as the call stack.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
38
Exception Handler:
The runtime system searches the call stack for a method that contains a block of code
that can handle the exception. This block of code is called an exception handler.
The search begins with the method in which the error occurred and proceeds through
the call stack in the reverse order in which the methods were called.
When an appropriate handler is found, the runtime system passes the exception object
to the handler.
An exception handler is considered appropriate if the type of the exception object
thrown matches the type that can be handled by the handler.
Handling an Exception:
Java exception handling is managed via five keywords: try, catch, finally, throw, and
throws. Briefly, here is how they work. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within the try block,
it is thrown. Your code can catch this exception (using catch) and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java
run-time system. To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by a throws clause.
Any code that absolutely must be executed before a method returns is put in a finally
block.
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 before try block ends
}
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
39
Type Of Exception:
All exception types are subclasses of
the built-in class Throwable. Thus,
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 is used for
exceptional conditions that user
programs should catch. This is also
the class that you will subclass to create your own custom exception types. There is an
important subclass of Exception, called RuntimeException.
Points To Remember:
o java.lang.Exception and its sub classes are checked or compile time exception.
o For checked exceptions, compiler prompts either to provide exception handler
block or exception to be thrown.
o java.lang.RuntimeException and its sub classes are unchecked or run time
exception.
o For unchecked exceptions, compiler does not prompt to provide handler.
o Exception handler blocks contains try, catch and finally(optional) blocks.
o A try block can be associated with zero or more catch blocks.
o try block can be associated with zero or one finally block.
o Each try statement requires at least one catch or a finally block.
o We cannot write catch or finally block without try block.
o The finally block will execute whether or not an exception is thrown.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
40
Exception Handling Example :
class Calculator {
void divide(int a,int b) {
try {
System.out.println(Result : +(a/b));
}
catch(ArithmeticException ae) {
System.out.println("Error Found : "+ae.getMessage());
}
finally {
System.out.println("Task Completed.");
}
} // End Of Divide Method.
} // End Of Calulator Class.
class TestCalulator {
public static void main(String [] ar) {
Calculator ob = new Calculator();
ob.divide(20,10);
ob.divide(20, 0);
} //End Of Main Method.
} //End Of TestCalculator Class.
Output:
Result : 2
Task Completed.
Error Found : java.lang.ArithmeticException: /by zero
Task Completed.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
41
throw Keyword:
So far, you have only been catching exceptions that are thrown by the Java run-time
system. However, it is possible for your program to throw an exception explicitly, using
the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of the exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected,
and so on.
throw Example :
class ThrowDemo {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = a / b;
if(c < 1){
ArithmeticException ae = new ArithmeticException(Denominator is Greater);
throw ae;
}
System.out.println(Division : +c);
}//End Of Main
}//End Of ThrowDemo class
Output :
Exception in thread "main" java.lang.ArithmeticException: Denominator is Greater.
at NewClass.main(NewClass.java:8)
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
42
Multi-Threading:
Unlike most other computer languages, 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.
The benefit of Javas multithreading is that the main loop/polling mechanism is
eliminated. One thread can pause without stopping other parts of your program. For
example, the idle time created when a thread reads data from a network or waits for
user input can be utilized elsewhere. Multithreading allows animation loops to sleep for
a second between each frame without causing the whole system to pause. When a thread
blocks in a Java program, only the single thread that is blocked pauses. All other threads
continue to run.
Life Cycle Of Thread :
Threads exist in several
states. A thread can be
running. It can be ready to
run as soon as it gets CPU
time. A running thread can
be suspended, which
temporarily suspends its
activity. A suspended thread
can then be resumed,
allowing it to pick up where
it left off. A thread can be
blocked when waiting for a
resource. At any time, a
thread can be terminated, which halts its execution immediately. Once terminated, a
thread cannot be resumed.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
43
Implementing Multi-Threading in Java :
In Java, Multi-Threading can be implement in two different ways. That is
by
Extending java.lang.Thread class
Implementing java.lang.Runnable interface.
Extending java.lang.Thread class:
class MyThread extends Thread {
public void run() { // overriding run
// code that the thread will execute
}
}
------------------------------------------------
public static void main(String[] args) {
Thread t = new MyThread();
t.start(); // creating a thread executing a task parallel to others
// code the main thread will execute
}
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
44
Implementing java.lang.Runnable Interface:
class MyThread implements Runnable {
public void run() { // overriding run
// code that the thread will execute
}
}
------------------------------------------------
public static void main(String[] args) {
Runnable r = new MyThread();
Thread t = new Thread( r );
t.start(); // creating a thread executing a task parallel to others
// code the main thread will execute
}
Methods Of Runnable Interface:
o pulic void run() Defines the JOB/TASK of the thread.
Methods Of Thread Class
o String getName() -Obtain a threads name.
o int getPriority() - Obtain a threads priority.
o void setPriority(int prioritiy) - Set a threads priority.
o void setName(String name) - Set a threads name.
o boolean isAlive() - Determine if a thread is still running.
o void join() - Wait for a thread to terminate.
o void run() - Entry point for the thread.
o start() - Start a thread by calling its run method.
o boolean isDaemon() - Checks wheather thread is daemon or not.
o void setDaemon(boolean state) - Makes daemon thread.
o static void sleep(long time) - Suspend a thread for a period of time.
o void suspend() - Send active thread to wait state.
o void resume() - Resumes suspended thread from wait to active state.
o void stop() - Terminate active thread.
o static Thread currentThread() - Returns the reference of current Thread.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
45
o int activeCount() - Returns the number of active threads.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
46
Thread Example : To print thread name & priority.
class ThreadDemo {
public static void main(String [] ar) {
Thread t = Thread.currentThread();
System.out.printlb("Thread Name : "+t.getName());
System.out.printlb("Thread Priority : "+t.getPriority());
}//End Of Main
}//End Of ThreadDemo.
Output:
Thread Name: main
Thread Priority: 5
Thread Example : To print digital clock on console.
import java.util.Date;
class ClearScreen extends Thread {
public void run() {
while(true) {
System.out.print("\r");
try {
Thread.sleep(1000); }catch(Exception e){}
} //End Of While Loop
}//End Of run method }//End Of ClearScreen class
class ThreadDemo {
public static void main(String ... a)throws Exception {
ClearScreen cs = new ClearScreen();
cs.start();
while(true) {
Date d = new Date();
System.out.printf("%tr",d);
Thread.sleep(1000);
}//End Of While Loop
}//End Of main method }//Enf Of ThreadDemo class
Output :
03:53:27 pm
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
47
Synchronization
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization. As you will see, Java provides unique,
language-level support for it.
Key to synchronization is the concept of the monitor (also called a semaphore). A
monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread
can own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other threads are said to be
waiting for the monitor.
Using Synchronized Methods -
Synchronization is easy in Java, because all objects have their own implicit monitor
associated with them. To enter an objects monitor, just call a method that has been
modified with the synchronized keyword. While a thread is inside a synchronized
method, all other threads that try to call it (or any other synchronized method) on the
same instance have to wait.
synchronized return-type method-name(Argument-list) {
// Method Body
}
The Synchronized Statement/Block -
While creating synchronized methods within classes that you create is an easy and
effective means of achieving synchronization, it will not work in all cases. To
understand why, consider the following. Imagine that you want to synchronize access
to objects of a class that was not designed for multithreaded access. That is, the class
does not use synchronized methods. Further, this class was not created by you, but by a
third party, and you do not have access to the source code. Thus, you cant add
synchronized to the appropriate methods within the class. How can access to an object
of this class be synchronized? Fortunately, the solution to this problem is quite easy: You
simply put calls to the methods defined by this class inside a synchronized block. This is
the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized }
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
48
Networking in Java:
The term network programming refers to writing programs that execute across
multiple devices, in which the devices are all connected to each other using a
network.
The java.net package contains a collection of classes and interfaces that provide the
low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
In java network programming is done by using socket paradigm:
What is SOCKET ?:
A network socket is a lot like an electrical socket. Various plugs around the network
have a standard way of delivering their payload. Anything that understands the
standard protocol can plug in to the socket and communicate.
With electrical sockets, it doesnt matter if you plug in a lamp or a toaster; as long as
they are expecting 60Hz, 115-volt electricity, the devices will work. Think how
your electric bill is created. There is a meter somewhere between your house and
the rest of the network. For each kilowatt of power that goes through that meter,
you are billed. The bill comes to your address. So even though the electricity flows
freely around the power grid, all of the sockets in your house have a particular
address.
The same idea applies to network sockets, except we talk about TCP/IP packets and
IP addresses rather than electrons and street addresses.
Internet Protocol (IP) : is alow-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 your data.
User Datagram Protocol (UDP) : sits next to TCP and can be used directly
to support fast, connectionless, unreliable transport of packets. UDP is a
connection-less protocol that allows for packets of data to be transmitted
between applications.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
49
Reserved Sockets
Once connected, a higher-level protocol ensues, which is dependent on which port you
are using. TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these
will seem familiar to you if you have spent any time surfing the Internet. Port number
21 is for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP and the
list goes on. It is up to each protocol to determine how a client should interact with the
port.
You often hear the term client/server mentioned in the context of networking.
Server : A server is anything that has some resource that can be shared. There
are compute servers, which provide computing power; print servers, which
manage a collection of printers; disk servers, which provide networked disk
space; and web servers, which store web pages.
Client : A client is simply any other entity that wants to gain access to a
particular server. The interaction between client and server is just like the
interaction between a lamp and an electrical socket. The power grid of the house
is the server, and the lamp is a power client. The server is a permanently
available resource, while the client is free to unplug after it is has been served.
Socket Programming in Java:
When a connection is made, the server creates a socket object on its end of the
communication. The client and server can now communicate by writing to and
reading from the socket.
Socket provides the communication mechanism between two computers using TCP.
A client program creates a socket on its end of the communication and attempts to
connect that socket to a server.
Java supports both the TCP and UDP protocol families. TCP is used for reliable
stream-based I/O across the network. UDP supports a simpler, hence faster, point-
to-point datagram-oriented model.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
50
Java Network API :
All java classes and interfaces for network programming lies in the package name
java.net. Following are the main classes of java.net package responsible for basic
networking operation:
InetAddress class:
Whether you are making a phone call, sending mail, or establishing a connection across
the Internet, addresses are fundamental. The InetAddress class is used to encapsulate
both the numerical IP address and the domain name for that address.
The InetAddress class has no visible constructors. To create an InetAddress object, you
have to use one of the available factory methods.
Three commonly used InetAddress factory methods are shown here:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
51
InetAddress Example :
import java.net.*;
class InetDemo {
public static void main(String args[]) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println("Address : "+address);
System.out.println("Host Address : "+address.getHostAddress());
System.out.println("Host Name : "+address.getHostName());
} // End Of main method.
} // End Of InetDemo class.
OUTPUT :
Address : United-Lab5/192.168.1.20
Host Address : 192.168.1.20
Host Name : United-Lab5
ServerSocket class:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
52
The java.net.ServerSocket class is used to create server that listen for either local
machine or remote machine.
The ServerSocket class has following contructors:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
53
If the ServerSocket constructor does not throw an exception, it means that our
application has successfully bound to the specified port and is ready for client
request.
The ServerSocket class has following instance method:
Socket class:
The java.net.Socket class is design to connect to server socket and initiate protocol
exchanges. The client obtains a Socket object by instantiating one, whereas the sever
obtains a Socket object from the return value of the accept() method.
The Socket class has the following constructors:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
54
The Socket class has following instance method:
Example: Client and Server interaction through console.
SOURCE : ServerConsole.java
import java.io.*;
import java.net.*;
public class ServerConsole {
public static void main(String [] args) {
ServerSocket server=null;
Socket client;
try {
server = new ServerSocket(1234); //1234 is an unused port number
} catch (IOException ie) {
System.out.println("Cannot open socket.");
System.exit(1);
}
while(true) {
try {
client = server.accept();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
55
String msg = br.readLine();
System.out.println("Client : "+msg);
msg = System.console().readLine("Server : ");
pw.println(msg);
} catch (IOException ie) {}
}//End Of Main method
}//End Of SeverConsole class.
SOURCE : ClientConsole.java
import java.io.*;
import java.net.*;
public class ClientConsole {
public static void main(String args[]) {
try {
Socket client =new Socket("localhost", 1234);
InputStream clientIn = client.getInputStream();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut,true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Client : ");
pw.println(stdIn.readLine());
System.out.print("Server : ");
System.out.println(br.readLine());
pw.close(); br.close(); client.close();
} catch (ConnectException ce) {
System.out.println("Cannot connect to the server.");
} catch (IOException ie) {
System.out.println("I/O Error.");
}
}//End Of Main method
}//End Of ClientConsole class.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
56
Output:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
57
Collection API:
Collections Framework provides a well-designed set of interfaces and classes for
storing and manipulating groups of data as a single unit, a collection.
It provides a convenient API to many of the ADTs like maps, sets, lists, trees, arrays,
hash tables, and other collections.
All the classes and interfaces of collection framework are available in a java.util
package.
The java.util package contains one of Javas most powerful subsystems: collections.
Collections were added by the initial release of Java 2, and enhanced by Java 2, version
1.4. A collection is a group of objects.
Collection Framework Hierarchy :

Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
58
java.util.Collection Interface
The Collection interface is the foundation upon which the collections framework
is built. It declares the core methods that all collections will have.
The ArrayList Class:
The ArrayList class implements the List interface. ArrayList supports dynamic arrays
that can grow as needed.
The Vector Class:
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.
The LinkedList Class
The LinkedList class implements the List and Deque interfaces. It provides a linked-list
data structure.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
59
The HashSet Class
HashSet implements the Set interface. It creates a collection that uses a hash table for
storage. As most readers likely know, 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, called its hash code. In HashSet collection, objects are stored in un-ordered way and it
does not allow duplicated 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 and it also does not allows duplicated elements.
Collection Example:
import java.util.*;
class CollectionDemo {
public static void main(String [] args) {
List al = new ArrayList();
al.add("UCER"); al.add("UIT");
al.add("UIM"); al.add("UIP"); al.add("UCER");
List v = new Vector();
v.addAll(al);
Set s = new HashSet();
s.addAll(al);
Set ss = new TreeSet();
ss.addAll(al);
System.out.println("ArrayList : "+al);
System.out.println("Vector : "+v);
System.out.println("Set :"+s);
System.out.println("Sorted Set : "+ss);
}//End Of Main Method
}//End Of CollectionDemo class
Output: Note:
ArrayList : [UCER, UIT, UIM, UIP, UCER] Unsorted and Ordered
Vector : [UCER, UIT, UIM, UIP, UCER] Unsorted and Ordered
Set : [UIT, UCER, UIP, UIM] Unordered and No Duplicate
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
60
Sorted Set : [UCER, UIM, UIP, UIT] Sorted and No Duplicate
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
61
java.util.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.
Given a key and a
value, you can store
the value in a Map object. After the value is stored, you can retrieve it by using its key.
The methods declared by Map are:
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
62
The HashMap Class:
HashMap implements Map. It does not add any methods of its own. You should note that
a hash map does not guarantee the order of its elements. Therefore, the order in which
elements are added to a hash map is not necessarily the order in which they are read by
an iterator.
The TreeMap Class:
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an
efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You
should note that, unlike a hash map, a tree map guarantees that its elements will be
sorted in ascending key order.
Map Example :
import java.util.*;
class MapDemo {
public static void main(String [] ar) {
Map m = new TreeMap();
m.put(1,"Nuzhat Haleem);
m.put(3,"Abhinav Mishra");
m.put(4,"Abhinav Srivastava");
m.put(2,"Abhinav Malviya);
Set<Map.Entry> em = m.entrySet();
for(Map.Entry me : em) {
System.out.println(me.getKey()+" : "+me.getValue());
}
}//End Of Main Method.
}//End Of Map Demo
Output: - Well get the elements in sorted order because of TreeMap
1 : Nuzhat Haleem
2 : Abhinav Malviya
3 : Abhinav Mishra
4 : Abhinav Srivastava
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
63
Java Beans:
The JavaBeans architecture is based on a component model which enables developers
to create software units called components. Java bean is a software component that is
reusable in a variety of different environments. Java bean is just a java class with the
following requirements:
It has public constructor with no arguments.
It has private properties.
It has setters and getters methods for its properties.
It may have some other general methods.
If required it can be Serializable.
Application Builder Tool :
When working with Java Beans, most developers use an application builder tool, a utility
that enables you to configure a set of Beans, connect them together, and produce a working
application. In general, Bean builder tools have the following capabilities.
A palette is provided that lists all of the available Beans. As additional Beans are
developed or purchased, they can be added to the palette.
A worksheet is displayed that allows the designer to layout Beans in a graphical user
interface. A designer may drag and drop a Bean from the palette to this worksheet.
Special editors and customizers allow a Bean to be configured. This is the mechanism by
which the behavior of a Bean may be adapted for a particular environment.
Capabilities exist to interconnect Beans. This means that events generated by one
component are mapped to method invocations on other components.
When a collection of Beans has been configured and connected, it is possible to save all
of this information in a persistent storage area. At a later time, this information can then
be used to restore the state of the application.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
64
The Bean Developer Kit(BDK)
The Bean Developer Kit (BDK), is a simple example of a tool that enables you to create,
configure, and connect a set of Beans. There is also a set of sample Beans with their source
code.
Installing the BDK
The Java 2 SDK must be installed on your machine for the BDK to work. Confirm that the SDK
tools are accessible from your environment. The BDK can then be downloaded from the
JavaSoft site (http://java.sun.com). It is packaged as one file that is a self-extracting archive.
Follow the instructions to install it on your machine. The discussion that follows assumes that
the BDK is installed in a directory called bdk. If this is not the case with your system, substitute
the proper directory.
Starting the BDK
To start the BDK, follow these steps:
1. Change to the directory c:\bdk\beanbox.
2. Execute the batch file called run.bat. ToolBox lists all of the different Beans that have been
included with the BDK. BeanBox provides an area to layout and connect the Beans selected
from the ToolBox. Properties provides the ability to configure a selected Bean.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
65
Java Archive (JAR) Files:
The jar tool combines multiple files into a single JAR archive file. jar is a general-purpose
archiving and compression tool, based on ZIP compression format. However, jar was designed
mainly to facilitate the packaging of java beans, applets or applications into a single archive.
Manifest Files
A developer must provide a manifest file to indicate which of the components in a JAR file are
Java Beans. An example of a manifest file is provided in the following listing. It defines a JAR
file that contains two .gif files and one .class file. The last entry is a Bean.
Name: sunw/demo/slides/slide0.gif
Name: sunw/demo/slides/slide1.gif
Name: sunw/demo/slides/Slides.class
Java-Bean: True
A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be
immediately followed by the line Java-Bean: True.
The JAR Utility
A utility is used to generate a JAR file. Its syntax is shown here:
jar options files
Creating a JAR File
The following command creates a JAR file named Xyz.jar that contains all of the .class and .gif
files in the current directory:
jar cf Xyz.jar *.class *.gif
Option Description
c A new archive is to be created.
C Change directories during command execution.
f first element in the file list is the name of the archive that is to be created or accessed.
i Index information should be provided.
m The second element in the file list is the name of the external manifest file.
M Manifest file not created.
t The archive contents should be tabulated.
u Update existing JAR file.
v Verbose output should be provided by the utility as it executes.
x Files are to be extracted from the archive.
0 Do not use compression.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
66
Introspection
Introspection is the process of analyzing a Bean to determine its capabilities. This is an essential
feature of the Java Beans
There are two ways in which the developer of a Bean can indicate which of its properties,
events, and methods should be exposed by an application builder tool. With the first method,
simple naming conventions are used.
In the second way, an additional class is provided that explicitly supplies this information.
Design Patterns for Properties
A property is a subset of a Beans state. The values assigned to the properties determine
the behavior and appearance of that component.
Simple Properties
A simple property has a single value. It can be identified by the following design patterns,
where N is the name of the property and T is its type.
public T getN( );
public void setN(T arg);
Boolean Properties
A Boolean property has a value of true or false. It can be identified by the following design
patterns, where N is the name of the property:
public boolean isN( );
public boolean getN( );
public void setN(boolean value);
Indexed Properties
An indexed property consists of multiple values. It can be identified by the following
design patterns, where N is the name of the property and T is its type:
public T getN(int index);
public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
67
Example :
public class MediaPlayer {
private String name; //Simple Property
private boolean on; // Boolean Property
private String [] playlist; //Indexed Property
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isOn() {
return on;
}
public boolean getOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public String getPlayList(int index) {
return playList[index];
}
public void setPlayList(int index, String value) {
this.playList[index] = value;
}
public String [] getPlayList() {
return playList; }
public void setPlayList(String [] playList) {
this.playList = playList;
}
}//End Of MediaPlayer Class
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
68
Design Patterns for Events
Beans use the delegation event model that was discussed earlier in this book. Beans can
generate events and send them to other objects. These can be identified by the following design
patterns, where T is the type of the event:
public void addTListener(TListener eventListener);
public void removeTListener(TListener eventListener);
Example :
public class PlayList {
public void addPlayListListener(PlayListListener tl) {
.......
..
}
public void removePlayListListener(PlayListListener tl) {
..........

}
}//End Of PlayList class
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
69
Developing A Simple Bean:
Create a New Bean
Here are the steps that you must follow to create a new Bean:
1. Create a directory for the new Bean.
2. Create the Java source file(s).
3. Compile the source file(s).
4. Create a manifest file.
5. Generate a JAR file.
6. Start the BDK.
7. Test.
Using Bound Properties
A Bean that has a bound property generates an event when the property is
changed. The event is of type PropertyChangeEvent and is sent to objects that previously
registered an interest in receiving such notifications.
The accessor methods for a bound property are defined in the same way as those
for simple properties. However, you also need to provide the event listener registration
methods forPropertyChangeListener classes and fire a PropertyChangeEvent event to the
PropertyChangeListener objects by calling their propertyChange methods.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
70
The Java Beans API:
The Java Beans functionality is provided by a set of classes and interfaces in the java.beans
package. This section provides a brief overview of its contents.
Interfaces of Java Bean API:
Interface Description
AppletInitializer Methods in this interface are used to initialize Beans that are also applets.
BeanInfo This interface allows a designer to specify information about the
properties, events, and methods of a Bean.
Customizer This interface allows a designer to provide a graphical user interface
through which a Bean may be configured.
DesignMode Methods in this interface determine if a Bean is executing in
design mode.
ExceptionListener A method in this interface is invoked when anexception has
occurred.
PropertyChangeListener A method in this interface is invoked when a bound property is
changed.
PropertyEditor Objects that implement this interface allow designers to change
and display property values.
VetoableChangeListener A method in this interface is invoked when a constrained
property is changed.
Visibility Methods in this interface allow a Bean to execute in environments where a graphical
user interface is not available.
Classes of Java Bean API:
Class Description
BeanDescriptor This class provides information about a Bean. It also allows you to
associate a customizer with a Bean.
Beans This class is used to obtain information about a Bean.
EventHandler Supports dynamic event listener creation.
IndexedProperty Descriptor Instances of this class describe an indexed property of
a Bean.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
71
IntrospectionException An exception of this type is generated if a problem occurs when
analyzing a Bean.
Introspector This class analyzes a Bean and constructs a BeanInfo object that
describes the component.
MethodDescriptor Instances of this class describe a method of a Bean.
PropertyChangeEvent This event is generated when bound or constrained properties are
changed. It is sent to objects that registered an interest in these
events and implement either the PropertyChangeListener or
VetoableChangeListener interfaces.
PropertyChangeSupport Beans that support bound properties can use this class to notify
PropertyChangeListener objects.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
72
Introduction to Enterprise Java Beans(EJB):
What Is an Enterprise Java Bean?
An enterprise bean is a server-side component that encapsulates the business logic of an
application. The business logic is the code that fulfills the purpose of the application. In an
inventory control application, for example, the enterprise beans might implement the business
logic in methods called checkInventoryLevel and orderProduct etc.
When to Use Enterprise Beans
You should consider using enterprise beans if your application has any of the following
requirements:
The application must be scalable. To accommodate a growing number of users, you
may need to distribute an applications components across multiple machines.
Transactions must ensure data integrity. Enterprise beans support transactions, the
mechanisms that manage the concurrent access of shared objects.
EJBs provide:
EJB run inside ejb container, The container provides certain built-in services to EJB.
The services that EJB container provides are:
o Component Pooling: If there are no request for a particular EJB then the
container contains zero or one instance of that component in memory, and it
increases instance as per need arises.
o Transaction Management: A transaction is a single unit of work, composed of
one or more steps. If all the steps succeed then the transaction is committed
otherwise it is rolled back.
o Security: Container provides its own authentication and authorization control.
o Persistence: Container if desired can also maintain persistent data of application.
Container is then responsible for retrieving and saving the data for us while
taking care of concurrent access from multiple clients.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
73
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
74
Types of Enterprise Beans
There are three types of enterprise beans.
Enterprise Bean Type and Purpose
Session Bean Performs a task for a client; implements a web service.
Entity Bean Represents a business entity object that exists in persistent storage.
Message-Driven Bean Acts as a listener for the Java Message Service API, processing
messages asynchronously.
Session Beans:
What Is a Session Bean?
A session bean represents a single client inside the Application Server. To access an application
that is deployed on the server, the client invokes the session beans methods. The session bean
performs work for its client, shielding the client from complexity by executing business tasks
inside the server.
As its name suggests, a session bean is similar to an interactive session. A session bean is not
shared; it can have only one client, in the same way that an interactive session can have only
one user. Like an interactive session, a session bean is not persistent. (That is, its data is not
saved to a database.) When the client terminates, its session bean appears to terminate and is no
longer associated with the client.
There are two types of session beans: stateless and stateful.
Stateless Session Beans:
A stateless session bean does not maintain a conversational state for the client. When a
client invokes the method of a stateless bean, the beans instance variables may contain
a state, but only for the duration of the invocation. When the method is finished, the
state is no longer retained.
Stateful Session Beans:
The state of an object consists of the values of its instance variables. In a stateful session
bean, the instance variables represent the state of a unique client-bean session. Because
the client interacts (talks) with its bean, this state is often called the conversational
state.
Content Developed by : Mr. Faiz Mohd Arif Khan & Mr. Harish Kumar
75
Entity Beans:
What Is an Entity Bean?
An entity bean represents a business object in a persistent storage mechanism. Some examples
of business objects are customers, orders, and products. In the Application Server, the persistent
storage mechanism is a relational database. Typically, each entity bean has an underlying table
in a relational database, and each instance of the bean corresponds to a row in that table.
There are two types of entity beans:
Container-Managed Persistence(CMP) Entity Bean :
CMP beans persistence is managed by the EJB container which is responsible for saving
and retrieving the data from the underlying database for us. CMP beans are easier to
develop and work well with database access.
Bean-Managed Persistence(BMP) Entity Bean :
BMP beans persistence has to be managed by the EJB itself. While it gives more control
to the EJB developer to save and retrieve data, they are harder to build as more coding is
required. On use of BMP beans would be to retrieve and save data from non-database
sources like XML files.

You might also like