0% found this document useful (0 votes)
25 views

Introduction to Web Services Development (CS311) - Updated Handouts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Introduction to Web Services Development (CS311) - Updated Handouts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Introduction to Web Services Development (CS311)

Introduction to Web Services Development


CS311 – Handouts
Syed Nauman Ali Shah

© Copyright Virtual University of Pakistan 1


Introduction to Web Services Development (CS311)

Contents
Booklet of Introduction to Web Services Development .....................................................................1
Contents ................................................................................................................................................2
Module 1 (Object Oriented Paradigm) ................................................................................................3
Module 2: Basics of Java Programming .............................................................................................38
Module 3: (Program Control Flow) ....................................................................................................46
Module 4: (Using Objects) ..................................................................................................................56
Module 5: (Primitive values as objects) .............................................................................................71
Module 6: (Arrays) ..............................................................................................................................76
Module 7: (Classes).............................................................................................................................82
Module 8 (Object Communication) .................................................................................................118
Module 9: (Modifiers) .......................................................................................................................129
Module 10: (Exception Handling).....................................................................................................143
Module 11: (XML) .............................................................................................................................153
Module 12: (XML) .............................................................................................................................175
Module 13 :( XML DOM)...................................................................................................................197
Modue 14: Introduction to JAXP ......................................................................................................246
Module 15: (Servlets)........................................................................................................................263
Module-16: Java Database Connectivity (JDBC)..............................................................................327
Module 17 Introduction WebServices .............................................................................................338
Module 18 Web Services Architecture ............................................................................................345
Module 19 Web Services with JAX-WS ............................................................................................353

© Copyright Virtual University of Pakistan 2


Introduction to Web Services Development (CS311)

Module 1 (Object Oriented Paradigm)

Objective:
In this lecture we will discuss Object Orientation in detail. It will be followed by discussion on
Data Modeling with reference to Abstraction, Inheritance, Encapsulation and Information
Hiding, what are the advantages and they are used in classes and their examples.

What is an Object Orientation?


In real world, object oriented approach focuses on objects that represents abstract or concrete
things.
What is a Model?
Modeling is an approach that is used at the beginning of software. The reasons to model a system
are:
Communication: Model diagrams before implementation can be more understandable and can
allow users to give developers feedback on the appropriate structure of the system.
Abstraction: The goal of the software methodology is to first what functionality is used and then
how to take this abstract description and refine it into an implementable design.

What is an Object?
For understanding an object orientation, you need to understand object first. Objects are key to
understand object-oriented. Look around yourself and you'll find many examples of real-world
objects: your dog, your desk, your television set, your bicycle. Object is something tangible.
Object has two characteristics; state and behavior. State is a noun, attribute, a well-defined
behavior and behavior is a certain operation. For example dog which is a tangible object, an
object which can be touched has a state of colour, name, and breed and has behavior of barking,
fetching.

© Copyright Virtual University of Pakistan 3


Introduction to Web Services Development (CS311)

Object

"Object" can be a combination of variables and functions. You may also notice that some
objects, in turn, will also contain other objects. Relationships of identified objects are constructed
(such as relating a person's age to a specific person). For example there are several objects like
Ali, House, Car, and Tree. Relationships are built between these objects like; Ali lives in the
house and Ali drives a car. In these two sentences, Ali, house and car are objects which interact
with each other and form a certain relation.
Time is another example in which Hours, minutes and seconds are the objects and the operations
performed on time like set Hours, set minutes and set seconds are the behavior and operations
performed on the object.

Advantages:
In real world, we are surrounded by objects. Modeling picks up each thing/object in the real
world which is involved in the requirement. It makes the requirement simple and easily
understandable by representing simple diagrams.

What is Abstraction?
Abstraction is the process of taking out characteristics from something in order to reduce it into a
set of essential characteristics. Through the process of abstraction, a programmer hides all the
irrelevant data about an object in order to reduce complexity and increase efficiency.

© Copyright Virtual University of Pakistan 4


Introduction to Web Services Development (CS311)

Examples:
Ali is a PhD student and teaches BS students. Below table shows the attributes of Ali as a student
and employee. When Ali is at university, then he is a "Student". When he is at work, he is an
"Employee".

Attributes:
Name Employee ID
Student Roll No Designation
Year of Study Salary
CGPA Age

Ali has different relationships in different roles. So it boils down to what in what context we are
looking at an entity/object. So if I am modelling a Payroll System, I will look at Ali as an
Employee (employee ID, name, designation, salary and age) shown in the table below.
Attributes:
Employee ID
Name
Designation
Salary
Age

If am modelling a Course Enrollment System, then I will consider Ali’s aspects and
characteristics as a Student (student roll number, name, year of study, cgpa, age) shown in the
table below.
Attributes:
Name
Student Roll No
Year of Study
CGPA
Age

© Copyright Virtual University of Pakistan 5


Introduction to Web Services Development (CS311)

Abstract class and abstract method.

Abstraction means putting all the variables and methods in a class which are necessary.
Abstraction is the common thing.

Example:
If somebody in your collage tell you to fill application form, you will fill your details like name,
address, data of birth, which semester, percentage you have got etc.
If some doctor gives you an application to fill the details, you will fill the details like name,
address, date of birth, blood group, height and weight.

See in the above example what is the common thing?

Age, name, address so you can create the class which consist of common thing that is called
abstract class.
That class is not complete and it can inherit by other class.

Graphical Representation of Classes


The class is represented as a rectangle, divided in 3 boxes one under another. The name of the
class is at the top. Next, there are the attributes of the class. At the very bottom are the operations
or methods. The plus/minus signs indicate whether an attribute / operation is visible (+ means
public) or not visible (- means private). Protected members are marked with #.
(Class Name)

-(Attribute) (Class Name)

+(Operations) Suppressed Form

Normal Form
Abstraction in Programming:
© Copyright Virtual University of Pakistan 6
Introduction to Web Services Development (CS311)

A Car has Engine, wheels and many other parts. When we write all the properties of the Car,
Engine, and wheel in a single class, it would look this way:

public class Car {

int price;
String name;
String color;

int engineCapacity;
int engineHorsePower;

String wheelName;
int wheelPrice;

void move(){
//move forward
}

void rotate(){
//Wheels method
}

void internalCombustion(){
//Engine Method
}

In the above example, the attributes of wheel and engine are added to the Car type. This will not
create any kind of issues programming. But it becomes more complex when it comes to
maintenance of the application.

Abstraction has three advantages:


 By using abstraction, we can separate the things that can be grouped to another type.
 Frequently changing properties and methods can be grouped to a separate type so that the
main type need not undergo changes.
 Simplifies the representation of the domain models.

© Copyright Virtual University of Pakistan 7


Introduction to Web Services Development (CS311)

Applying the abstraction with composition, the above example can be modified as given below:

public class Car {

Engine engine = new En


gine();
Wheel wheel = new Whee
l();

int price;
String name;
String color;

void move(){
//move forward
}

public class Engine {


int engineCapacity;
int engineHorsePower;

void internalCombustion(
){
//Engine Method
}

public class Wheel {


String wheelName;
int wheelPrice;

void rotate(){
//Wheels method
}

© Copyright Virtual University of Pakistan 8


Introduction to Web Services Development (CS311)

Engine and Wheel are referred from the Car type. Whenever an instance of Car is created, both
Engine and Wheel will be available for the Car and when there are changes to these Types
(Engine and Wheel), changes will only be confined to these classes and will not affect the Car
class.

What is Inheritance?
Inheritance enables new objects to take on the properties of existing objects. A class that is used
as the basis for inheritance is called a superclass or base class. A class that inherits from a
superclass is called a subclass or derived class. The terms parent class and child class are also
acceptable terms to use respectively. The parent class is called base class and the child class is
called derived class. A child inherits characteristics from its parent while adding additional
characteristics of its own.
Subclasses and superclasses can be understood in terms of the is a relationship. A subclass is a
more specific instance of a superclass. For example, orange is a fruit, parrot is a bird. An orange
is a fruit; so it is okay to write an Orange class is a subclass of a Fruit class.

Examples:
If a class B inherits from class A then it contains all the characteristics (information structure and
behaviour) of class A as shown in figure below.

© Copyright Virtual University of Pakistan 9


Introduction to Web Services Development (CS311)

Super Class

"is a"

B
Sub Class

Person

Student Teacher Doctor

In the example above, Class Student, Teacher and Doctor inherits from Class Person. Each child
class contain “is a” relation with parent class. Student “is a” person, Teacher “is a” person and
Doctor “is a” person. Each child contains all the characteristics of parent class.

Similarly:

Shape

Line Circle Triangle

© Copyright Virtual University of Pakistan 10


Introduction to Web Services Development (CS311)

In the example above, Class Line, Circle and Triangle inherits from Class Shape. Each child
class contain “is a” relation with parent class. Line “is a” Shape, Circle “is a” shape and Triangle
“is a” Shape. Each child contains all the characteristics of parent class.

Generalization:
Generalization is the process of extracting shared characteristics from two or more classes, and
combining them into a generalized superclass. Shared characteristics can be attributes,
associations, or methods.

The classes Circle and Rectangle partially share the same attributes. From a domain perspective,
the two classes are also very similar.

During generalization, the shared characteristics are combined and used to create a new
superclass Shape. Circle and Rectangle become subclasses of the class Shape.

The shared attributes are only listed in the superclass, but also apply to the two subclasses, even
though they are not listed there.

© Copyright Virtual University of Pakistan 11


Introduction to Web Services Development (CS311)

Example of Generalization

Specialization:
In contrast to generalization, specialization means creating new subclasses from an existing
class. If it turns out that certain attributes, associations, or methods only apply to some of the
objects of the class, a subclass can be created. The most inclusive class in a
generalization/specialization is called the superclass and is generally located at the top of the
diagram. The more specific classes are called subclasses and are generally placed below the
superclass.
The class Freight has the attribute Degree of Hazardousness, which is needed only for cargo, but
not for passenger luggage. Obviously, here two similar but different domain concepts are
combined into one class. Through specialization the two special cases of freights are formed:
Piece of Cargo and Piece of Luggage. The attribute Degree of Hazardousness is placed where it
belongs—in Piece of Cargo. The attributes of the class Freight also apply to the two subclasses
Piece of Cargo and Piece of Luggage:

© Copyright Virtual University of Pakistan 12


Introduction to Web Services Development (CS311)

Example of specialization

Specialization & Extension:


As the name suggests, class extension is concerned with adding something to a class. We can add
both variables and operations.

These considerations lead us to the following definition of class extension.

If class B is an extension of class A then

 B may add new variables and operations to A


 Operations and variables in A are also present in B
 B-objects are not necessarily conceptually related to A-objects

© Copyright Virtual University of Pakistan 13


Introduction to Web Services Development (CS311)

Here are the three classes given below that specialize the class BankAccount.

A specialization hierarchy of bank accounts

Figure below shows the extensions of the bank account classes. The specialized bank accounts
overlap in such a way that there can exist a bank account which is both a CheckAccount, a
SavingsAccount, and a LotteryAccount. An overlapping is the prerequisite for multiple
specialization.

Possible extensions of the bank account classes

Specialization & Restriction:


Specialization means that derived class is behaviorally incompatible with the base class,
behaviorally incompatible means that base class can’t always be replaced by the derived class.

For example, new subclasses from an existing class. Through specialization, Person class is
formed: Age is an attribute which is common for every person but in subclass, a condition is
defined in which age of an adult should be above 18 otherwise, error will occur. So the subclass
was restricted to adult age which should be above 18.

© Copyright Virtual University of Pakistan 14


Introduction to Web Services Development (CS311)

Advantages:
Main purpose of inheritance is reuse:
We can easily add new classes by inheriting from existing classes and can select an existing class
closer to the desired functionality. We can create a new class and inherit it from the selected
class. We can add to and/or modify the inherited functionality.

The classes Student and Teacher partially share the same attributes. From a domain perspective,
the two classes are also very similar.
During generalization, the shared characteristics are combined and used to create a new
superclass Person. Student and Teacher become subclasses of the class Person. The shared
attributes are only listed in the superclass like name, age and gender, but also apply to the two
subclasses, even though they are not listed there.
A new class of doctor has common attributes of class Teacher so the teacher class eventually
become the superclass of Doctor. As Teacher is a subclass of Person class so the Doctor class
will indirectly have the properties of Person class as well as shown in figure below.

© Copyright Virtual University of Pakistan 15


Introduction to Web Services Development (CS311)

If the inheritance of Doctor Class is changed from Teacher class to Person class, there will be no
change in Teacher class. Doctor class will still be the same but only the functions of Teacher
class will be excluded.

© Copyright Virtual University of Pakistan 16


Introduction to Web Services Development (CS311)

What is Encapsulation?
An object has to provide its users only with the essential information for manipulation, without
the internal details. A Secretary using a Laptop only knows about its screen, keyboard and
mouse. Everything else is hidden internally under the cover. She does not know about the inner
workings of Laptop, because she doesn’t need to. Therefore parts of the properties and methods
remain hidden to her.
The person writing the class has to decide what should be hidden and what not. When we
program, we must define as private every method or field which other classes should not be able
to access.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the
fields within the class. For this reason, encapsulation is also referred to as data hiding (not data
security).
Thus encapsulation is said to be providing “access control” through which we can control which
parts of the program can access the members of any class and thus prevent misuse. Various
access controls are public, private and protected.

Real world Example of Encapsulation:-


Let's take example of Mobile Phone and Mobile Phone Manufacturer
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone
design(class), now by using machinery you are manufacturing a Mobile Phone(object) for
selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but
not that how this Mobile Phone works.

Another example is the TV operation. It is encapsulated with cover and we can operate with
remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change
the things in TV.

© Copyright Virtual University of Pakistan 17


Introduction to Web Services Development (CS311)

Implementation:
Hide the data for security such as making the variables as private, and expose the property to
access the private data which would be public.
So, when you access the property you can validate the data and set it.

Example:

class Demo
{
private int _mark;

public int Mark


{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Advantages:
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.

What is Information Hiding?


Information hiding concept restricts direct exposure of data. All information should not be
accessible to all persons. Private information should only be accessible to its owner.
By Information Hiding we mean “Showing only those details to the outside world which are
necessary for the outside world and hiding all other details from the outside world.”

© Copyright Virtual University of Pakistan 18


Introduction to Web Services Development (CS311)

Your name and other personal information is stored in your brain we can’t access this
information directly. For getting this information we need to ask you about it and it will be up to
you how much details you would like to share with us.

An email server may have account information of millions of people but it will share only our
account information with us if we request it to send anyone else accounts information our request
will be refused.

A phone SIM card may store several phone numbers but we can’t read the numbers directly from
the SIM card rather phone-set reads this information for us and if the owner of this phone has not
allowed others to see the numbers saved in this phone we will not be able to see those phone
numbers using phone.

Advantages of Information Hiding


 Information Hiding makes easier for everyone to understand object oriented model.
 It is a barrier against change propagation. As implementation of functions is limited to our
class and we have only given the name of functions to user along with description of
parameters so if we change implementation of function it doesn’t affect the object oriented
model.

© Copyright Virtual University of Pakistan 19


Introduction to Web Services Development (CS311)

Types of Inheritance:

Single Inheritance:
It is the inheritance hierarchy wherein one derived class inherits from one base class. The below
flow diagram shows that class Circle extends only one class which is Shape. Here Shape is a parent
class of Circle and Circle would be a child class of Shape.

Multilevel Inheritance:
It is the inheritance hierarchy wherein subclass acts as a base class for other classes. In Multilevel
inheritance there is a concept of grandparent class. As you can see in below flow diagram
Semicircle is subclass or child class of Circle and Circle is a child class of Shape. So in this case
class Semicircle is implicitly inheriting the properties and method of class Shape along with Circle
that’s what is called multilevel inheritance.

Multiple Inheritance:

© Copyright Virtual University of Pakistan 20


Introduction to Web Services Development (CS311)

It is the inheritance hierarchy wherein one derived class inherits from multiple base class (es).
The problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes. In figure below, Mermaid is child class of class Woman and
Fish. Mermaid will have all the properties of both Woman and Fish class.

There are problems in multiple inheritance. Both woman and Fish have the attribute of eat with
their aspects so duplicate attribute of eat in Mermaid will cause complexity in choosing which
property will Mermaid will follow as shown in figure below.

Links & Relationship:

© Copyright Virtual University of Pakistan 21


Introduction to Web Services Development (CS311)

Association

Class Association Object Association

Inheritance Simple Association Composition Aggregation

Simple Association
Association is a relationship between two objects. In other words, Two objects may depend on
each other but don’t interact directly (weak association). Association defines the multiplicity
between objects. For example, the project management system involves various general
relationships, including manage, lead, execute, input, and output between projects, managers,
teams, work products, requirements, and systems. Consider, for example, how a project manager
leads a team.
One Way Association:
Associations are generally assumed to be bi-directional i.e. a message can pass in both directions
between objects. However in implementation this doesn't have to be the Case as shown in the
example bellow:
Single directional arrow shows the message conveying from one object to other. For example:
Ali lies in house but house lives in Ali will be incorrect. Moreover, Remote operates TV and not
TV operates Remote so these both are one way Associations.

Ali Lives House Remote Operates TV


and

Two Way Association:

© Copyright Virtual University of Pakistan 22


Introduction to Web Services Development (CS311)

This type of association is bi-directional i.e. a message can pass in both directions between
objects. It is usually donated by a single straight line or an arrow on both sides of the objects. For
example, Employee works for company and the company employs many employees.

Ternary Association
Any association may be drawn as a diamond with a solid line for exactly 3 associations end
connecting the diamond. For example, Teacher can teaches many courses, Many Students can
enroll many courses, each teacher can teaches many students.

N-ary association with more than two ends can only be drawn this way.

Composition:
Composition is specialized form of Aggregation. It is a strong type of Aggregation. Child object
does not have its lifecycle and if parent object is deleted, all child objects will also be deleted.
Let’s take again an example of relationship between House and Rooms. House can contain
multiple rooms - there is no independent life of room and any room cannot belong to two
different houses. If we delete the house - room will automatically be deleted. Let’s take another
example relationship between Questions and Options. Single questions can have multiple options

© Copyright Virtual University of Pakistan 23


Introduction to Web Services Development (CS311)

and option cannot belong to multiple questions. If we delete questions options will automatically
be deleted.
This is a strong type of relation because composed objects become the part of the composer. For
example, Ali is made of 1 Head, 2 Arm, 2 Leg and 1 Body. These four classes cannot exist
independently. If Ali is deleted, all four classes will automatically be removed because these
classes are dependent on Ali.

Aggregation:
Aggregation is a specialized form of Association where all objects have their own lifecycle, but
there is ownership and child objects can not belong to another parent object. Take an example of
Department and teacher. A single teacher cannot belong to multiple departments, but if we delete
the department teacher object will not be destroyed. We can think about it as a “has-a”
relationship. Aggregation is weaker relationship, because aggregate object is not a part of the
container, they can exist independently. Aggregation is represented by a line with unfilled-
diamond head towards the container. Direction between them specified which object contains the
other object.
In the example below, Room has 1 bed, 1 table, 1 cupboard and many chairs. Furniture is not the
intrinsic part of the composer. They are weak aggregation and can exist independently. Furniture
can shift to other room so they can exist independent of a particular room.

© Copyright Virtual University of Pakistan 24


Introduction to Web Services Development (CS311)

Take another example of plant and garden. They are weak aggregation and can exist
independently. Plant is not the intrinsic part of the garden and can exist independently. They can
be planted to other garden and it is not dependent to the particular garden.

Abstract Class:
An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a
method that is declared without an implementation. If a class includes abstract methods, then the
class itself must be declared abstract. When an abstract class is subclassed, the subclass usually
provides implementations for all of the abstract methods in its parent class. However, if it does
not, then the subclass must also be declared abstract.
For example, you can draw circles, rectangles, triangles and many other shapes. These objects all
have certain states (for example: center, orientation, line color, fill color) and behaviors (for
example: area, rotate, draw) in common. Some of these states and behaviors are the same for all
shapes (for example: center, area, and draw). All shapes must be able to draw themselves; they

© Copyright Virtual University of Pakistan 25


Introduction to Web Services Development (CS311)

just differ in how they do it. This is a perfect situation for an abstract superclass. You can take
advantage of the similarities and declare all the graphic objects to inherit from the same abstract
parent object (for example, Shape) as shown in the following figure. Classes Rectangle, triangle
and Circle Inherit from Shape.

Concrete Class:
A concrete class has concrete methods, i.e., with code and other functionality. This class may
extend an abstract class or implements an interface. The derived class is expected to provide
implementations for the methods that are not implemented in the base class. A derived class that
implements all the missing functionality is called a concrete class.
In example below, Student, Teacher and Doctor are concrete classes and Person is the Abstract
class.

© Copyright Virtual University of Pakistan 26


Introduction to Web Services Development (CS311)

Interface (Java):
An interface is an elegant way of defining the public services that a class will provide without
being bogged down by implementation details.
An interface is used to define the public services of a class. The interface provides no
implementation details. Think of an interface as a business contract between two parties. The
class implementing the interface agrees to provide the services defined in that interface to other
classes. The other classes calling on the public services agree to abide by the semantics of the
interface.
In the diagram below, both the Professor and Student classes implement the Person interface and
do not inherit from it. We know this for two reasons:
1) The Person object is defined as an interface — it has the "«interface»" text in the object's
name area, and we see that the Professor and Student objects are class objects because they are
labeled according to the rules for drawing a class object.
2) We know inheritance is not being shown here, because the line with the arrow is dotted and
not solid. As shown in Figure, a dotted line with a closed, unfilled arrow means realization (or
implementation); a solid arrow line with a closed, unfilled arrow means inheritance.

© Copyright Virtual University of Pakistan 27


Introduction to Web Services Development (CS311)

Overloading:
Overloading occurs when two or more methods in one class have the same method name but
different parameters.
An appropriate example would be a Print(object O) method. In this case one might like the
method to be different when printing, for example, text or pictures. The two different methods
may be overloaded as Print(text_object T); Print(image_object P). If we write the overloaded
print methods for all objects our program will "print", we should not have to worry about the
type of the object, and the correct function call again, the call is always: Print(something).

Rules:
The overloaded function must differ by data types...
The same function name is used for various instances of function call.

© Copyright Virtual University of Pakistan 28


Introduction to Web Services Development (CS311)

Programming Example:

In the example below variables are added with two datatypes, int and double. Through datatype
int, out will be in real numbers and through double, the output will be in floating numbers as
shown below. The method is same of addition in both case but from different datatypes, the
output is different.

#include
#include
void add(int x, int y);
void add(double x, double y);
int main()
{
clrscr();
add(10,20);
add(10.4,20.4);
return(0);
}
void add(int x, int y)
{
cout
}
void add(double x,double y)
{
cout
}

Run output

30
30.8

© Copyright Virtual University of Pakistan 29


Introduction to Web Services Development (CS311)

Overriding:

Overriding means having two methods with the same method name and parameter. One of the
methods is in the parent class and the other is in the child class. Overriding allows a child class to
provide a specific implementation of a method that is already provided its parent class.

One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().

class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}

Output:
Boy is eating.

© Copyright Virtual University of Pakistan 30


Introduction to Web Services Development (CS311)

Here is another example of overriding. The dog variable is declared to be a Dog. During compile
time, the compiler checks if the Dog class has the bark() method. As long as the Dog class has
the bark() method, the code compilers. At run-time, a Hound is created and assigned to dog. Dog
is referring to the object of Hound, so it calls the bark() method of Hound.

class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}

public void bark(){


System.out.println("bowl");
}
}

public class OverridingTest{


public static void main(String [] args){
Dog dog = new Hound();
dog.bark();
}

Output:
Bowl

The main advantage of overriding is that the class can give its own specific implementation to an
inherited method without even modifying the parent class(base class).

© Copyright Virtual University of Pakistan 31


Introduction to Web Services Development (CS311)

Polymorphism:
"Poly" means "many" and "morph" means "form". Polymorphism is an object-oriented
programming concept that refers to the ability of a variable, function or object to take on
multiple forms.
There are two types of polymorphism one is compile time polymorphism and the other is run
time polymorphism. Compile time polymorphism is functions and operators overloading.
Runtime time polymorphism is done using inheritance and virtual functions. Here are some ways
how we implement polymorphism in Object Oriented programming languages.

Compile time polymorphism -> Operator Overloading, Function Overloading


Run time polymorphism -> Interface and abstract methods, Virtual member functions.

An example would be:


A "Shape" class can be a part of an inheritance hierarchy where derived classes are "Circle",
“Triangle” and "Rectangle". Derived from "Rectangle" could be "Square",

Now, using such an example, it is true that any object below in a hierarchy is also something that
is directly up in the hierarchy. Hence, Square “is a" Rectangle, and Rectangle "is a" Shape. Also,
Square "is a" Shape.
Each of these classes will have different underlying data. A point shape needs only two co-
ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and

© Copyright Virtual University of Pakistan 32


Introduction to Web Services Development (CS311)

radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners
(and possibly) a rotation.
And, by making the class responsible for its code as well as its data, you can achieve
polymorphism. In this example, every class would have its own Draw() function and the client
code could simply do: shape.Draw().
Hence, using pointers of Base classes (higher in an inheritance hierarchy) can be assigned to
objects of derived classes and can be used in a unified manner with the use of virtual functions.
Hence, Polymorphism.

(The plus "+" operator example used above would not be correct, as that is actually an
overloaded operator (in the case the last poster presumed) and not precisely polymorphism).

Dynamic Binding:
Late binding means the binding occurs at runtime, based on the type of the object. Late binding
is also called dynamic binding or runtime binding. When a language implements late binding,
there must be some mechanism to determine the type of the object at runtime and call the
appropriate member function. In the case of a compiled language, the compiler doesn’t know the
actual object type, but it inserts code that finds out and calls the correct function body.

An example of polymorphism is the technique by which a reference that is used to invoke a


method can actually invoke different methods at different times depending on what it is referring
to at the time. This can be illustrated by the following example.

In the for loop, the statement all[i].toString() will either invoke the definition in Student or
MScStudent depending on what type of object the polymorphic reference all[i] is pointing to at
the time.

© Copyright Virtual University of Pakistan 33


Introduction to Web Services Development (CS311)

public class TestPoly2


{
public static void main(String [] args)
{
Student [] all= new Student[3];
all[0]= new Student("kate");
all[1]= new MScStudent("mike");
all[2]= new Student("Jane");

for (int i=0;i<3;i++)


System.out.println(all[i].toString());
}
}

Up-casting:

In up-casting we convert a smaller datatype into a larger datatypes. Since converting a smaller
dataytype into a larger datatype does not cause any information loss therefore up-casting is
implicit (i.e. it occurs automatically and we do not have to write any extra piece of code)

In primitive datatypes such as int, float, double upcasting occurs when we convert a smaller data
type (in terms of size (bytes)) into a large data type. For example; converting int (4 bytes) to long
(8 bytes) or float (4 bytes) to double(8 bytes). This has been shown in the following code
fragment.

int i = 4;
double d ;
d = i;

© Copyright Virtual University of Pakistan 34


Introduction to Web Services Development (CS311)

The diagram below is our polymorphism example.

Consider the following code:


Shape s = new Circle(100, 100);

We have cast Circle to the type Shape. This is possible, because Circle has been derived from
Shape and you expect all methods and properties of Shape to exist in Circle. Executing the Draw
method by doing s.Draw() gives the following output:

Drawing a CIRCLE at 100,100

If we had declared the Draw method in Circle as follows, public new void Draw() the output
would have been:

Drawing a SHAPE at 100,100

As we have already mentioned, marking the method with new, tells the compiler that we are not
overriding the base class implementation of the method.
So why is this called up-casting?
Consider the diagram above. From Circle, we are moving up the object hierarchy to the type
Shape, so we are casting our object "upwards" to its parent type.
Up-casting is implicit and is safe. By mentioning “safe”, we can happily cast Circle to Shape and
expect all the properties and methods of Shape to be available.

© Copyright Virtual University of Pakistan 35


Introduction to Web Services Development (CS311)

Down-Casting:
In down-casting we convert a larger datatype into a smaller datatype. Since converting a larger
dataytype into a smaller datatype may cause an information loss therefore down-casting is
explicit (i.e. it does not occur automatically and we have to tell compiler that we want to
downcast otherwise it won’t let us compile the code).

Since double is a bigger type, conversion is automatic but when we convert from double to int
there can be a loss of information and therefore explicit casting is required (i,e, we are telling the
compiler that we know what we are going to do, so do it.)

double d = 4;
int i ;
i =(int)d;

To help us better understand down-casting, we are going to add a new method to our Circle
class. This will be a simple method called FillCircle.

public void FillCircle()


{
Console.WriteLine("Filling CIRCLE at {0},{1}", m_xpos, m_ypos);
}
Using the example from up-casting, we know that we are able to write the following:

Shape s = new Circle(100, 100);

We are then free to call the Draw method. Having added the FillCircle method to our Circle class
we are not able to call this method by doing the following:
s.FillCircle ();
Because we have cast Circle to the type Shape, we are only able to use methods found in Shape,
that is, Circle has inherited all the properties and methods of Shape. If we want to call FillCircle,

© Copyright Virtual University of Pakistan 36


Introduction to Web Services Development (CS311)

we need to down-cast our type to Circle. In down-casting, we are simply moving down the object
hierarchy, from Shape down to Circle. The code for doing this is quite simple:

Circle c;
c = (Circle)s;

Simply, we are declaring c as the type Circle and explicitly casting s to this type. We are now
able to call the FillCircle method by doing the following:

c.FillCircle();

This gives us the following output:

Drawing a CIRCLE at 100,100

Filling CIRCLE at 100,100


We could also write ((Circle)s).FillCircle() reducing the lines of code needed to down-cast our
type and call the required method.

Disadvantages:
Down-casting is potentially unsafe, because you could attempt to use a method that the derived
class does not actually implement. With this in mind, down-casting is always explicit, that is, we
are always specifying the type we are down-casting to.

© Copyright Virtual University of Pakistan 37


Introduction to Web Services Development (CS311)

Module 2: Basics of Java Programming

There are three kinds of variables in Java:

 Local variables
 Instance variables
 Class/static variables

Local variables:

Local variables are declared in methods, constructors, or blocks.

 Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor or block.
 Local variables are implemented at stack level internally.

 There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.

© Copyright Virtual University of Pakistan 38


Introduction to Web Services Development (CS311)

Instance variables:

 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However
visibility for subclasses can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) should be called using the fully qualified name .
ObjectReference.VariableName.

© Copyright Virtual University of Pakistan 39


Introduction to Web Services Development (CS311)

Class/static variables:

 Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final and static. Constant variables never change from
their initial value.
 Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program stops.
 Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
 Static variables can be accessed by calling with the class name ClassName.VariableName.
 When declaring class variables as public static final, then variables names (constants) are all
in upper case. If the static variables are not public and final the naming syntax is the same as
instance and local variables.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms.

© Copyright Virtual University of Pakistan 40


Introduction to Web Services Development (CS311)

 A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
 An implementation its implementation is known as JRE (Java Runtime Environment).
 Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

Jvm Internal

© Copyright Virtual University of Pakistan 41


Introduction to Web Services Development (CS311)

Data Types in Java

In java, there are two types of data types

 primitive data types


 non-primitive data types

© Copyright Virtual University of Pakistan 42


Introduction to Web Services Development (CS311)

Java - Basic Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators

© Copyright Virtual University of Pakistan 43


Introduction to Web Services Development (CS311)

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

Operator and Example


+ ( Addition )
Adds values on either side of the operator
Example: A + B will give 30

- ( Subtraction )
Subtracts right hand operand from left hand operand
Example: A - B will give -10

* ( Multiplication )
Multiplies values on either side of the operator
Example: A * B will give 200

/ (Division)
Divides left hand operand by right hand operand
Example: B / A will give 2

% (Modulus)
Divides left hand operand by right hand operand and returns remainder
Example: B % A will give 0

++ (Increment)
Increases the value of operand by 1
Example: B++ gives 21

© Copyright Virtual University of Pakistan 44


Introduction to Web Services Development (CS311)

-- (Decrement)
Decreases the value of operand by 1
Example: B-- gives 19

© Copyright Virtual University of Pakistan 45


Introduction to Web Services Development (CS311)

Module 3: (Program Control Flow)

Control Flow:
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute
particular blocks of code. This section describes the decision-making statements (if-then, if-then-
else, switch), the looping statements (for, while, do-while), and the branching statements (break,
continue, return) supported by the Java programming language.

Selection Statements:

The if-then Statement


The if-then statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test evaluates to true.
For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. One possible implementation of the applyBrakes method could be
as follows:

void applyBrakes()
{
// the "if" clause: bicycle must be moving
if (isMoving)
{
// the "then" clause: decrease current speed
currentSpeed--;
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end
of the if-then statement.
The if-then-else Statement

© Copyright Virtual University of Pakistan 46


Introduction to Web Services Development (CS311)

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates
to false. You could use an if-then-else statement in the applyBrakes method to take some action
if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply
print an error message stating that the bicycle has already stopped.

void applyBrakes()
{
if (isMoving)
{
currentSpeed--;
}
else
{
System.err.println("The bicycle has already stopped!");
}
}

Loop:
A loop is a sequence of instruction s that is continually repeated until a certain condition is
reached.

For Loop:

A for loop iterates over elements of a sequence. A variable is created to represent the object in
the sequence. Programmers often refer to it as the "for loop" because of the way in which it
repeatedly loops until a particular condition is satisfied. The general form of the for statement
can be expressed as follows:

for (initialization; termination; increment)


{
statement(s)
© Copyright Virtual University of Pakistan 47
}
Introduction to Web Services Development (CS311)

For example,

x = [100,200,300]
for i in x:
print i

This will output:


100
200
300

The for loop loops over each of the elements of a list or iterator, assigning the current element to
the variable name given. In the example above, each of the elements in x is assigned to i.

While Loop:
The loop construct, found in nearly all procedural languages, that executes one or more
instructions (the "loop body") repeatedly so long as some condition evaluates to true. In contrast
to a repeat loop, the loop body will not be executed at all if the condition is false on entry to the
while.
For example, in C, a while loop is written
while () ;
Where is any expression and is any statement, including a compound statement within braces
"..".

Its syntax can be expressed as:

while (expression)
{
statement(s)
}

© Copyright Virtual University of Pakistan 48


Introduction to Web Services Development (CS311)

For example:

x= 5
while x > 0:
print x
x=x-1

Will output:
5
4
3
2
1

While loops can also have an 'else' clause, which is a block of statements that is executed (once)
when the while statement evaluates to false. The break statement inside the while loop will not
direct the program flow to the else clause. For example:

x=5
y=x
while y > 0:
print y
y=y-1
else:
print x
This will output:
5
4
3
2
1
5

© Copyright Virtual University of Pakistan 49


Introduction to Web Services Development (CS311)

The Java programming language also provides a do-while statement, which can be expressed as
follows:

do {
statement(s)
} while
(expression);

The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo program:

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}

© Copyright Virtual University of Pakistan 50


Introduction to Web Services Development (CS311)

Nested Statement:

#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}

If variable “a” is equal to 100 then it will proceed to next statement. It will then check the next
condition, if “b” is equal to 200 then it will print the statement and the output is given below.

When the above code is compiled and executed, it produces the following result −

Value of a is 100 and b is 200


Exact value of a is: 100
Exact value of b is: 200

© Copyright Virtual University of Pakistan 51


Introduction to Web Services Development (CS311)

If gas tank is less than 3/4 full then the system will check the next statement. Then check if it is
less than 1/4 full, it will then print "Low on gas!", otherwise it will print "At least 3/4 tank. Go
on!"

A Local Block:
Statements which are enclosed in left brace ({) and the right brace (}) forms a local Block. Local
Block can have any number of statements. Branching Statements or Conditional Statements,
Loop Control Statements such as if, else, switch, for, while forms a local block. These
Statements contain braces, so the portion of code between two braces would be considered a
local block. Variables declared in a local block have local scope i.e they can be accessed within
the block only.

© Copyright Virtual University of Pakistan 52


Introduction to Web Services Development (CS311)

#include<stdio.h>
int x = 40 ; // Scope(Life) : Whole Program
int main()
{
int x = 10 ; // Scope(Life) : In main
{
x = 30 ;
printf("%d",x);
}
printf("%d",x);
}

Output:
30 10

Statement terminator:
Semicolon (;) is used to terminate a statement in Java. A compound statement does not need a
semicolon to terminate it. A semicolon alone denotes the empty statement that does nothing.
The semicolon terminates a statement. Although by convention you should always end your
statements with semicolons, they are not strictly required in ActionScript. The interpreter
attempts to infer the end of a statement if the semicolon is omitted. For example:

// These are preferred


var x = 4;
var y = 5;
// But these are also legal
var x = 4
var y = 5

© Copyright Virtual University of Pakistan 53


Introduction to Web Services Development (CS311)

Java Program Structure


Let’s use example of HelloWorld Java program to understand structure and features of class.
This program is written on few lines, and its only task is to print “Hello World from Java” on the
screen. Refer the following picture.

1. “package sct”:

It is package declaration statement. The package statement defines a name space in which classes
are stored. Package is used to organize the classes based on functionality. If you omit the
package statement, the class names are put into the default package, which has no name. Package
statement cannot appear anywhere in program. It must be first line of your program or you can
omit it.

2. “public class HelloWorld”:


This line has various aspects of java programming.
a. public: This is access modifier keyword which tells compiler access to class.
b. class: This keyword used to declare class. Name of class (HelloWorld) followed by this
keyword.

3. Comments section:
We can write comments in java in two ways.

© Copyright Virtual University of Pakistan 54


Introduction to Web Services Development (CS311)

a. Line comments: It start with two forward slashes (//) and continue to the end of the current
line. Line comments do not require an ending symbol.
b. Block comments start with a forward slash and an asterisk (/*) and end with an asterisk and a
forward slash (*/).Block comments can also extend across as many lines as needed.

4. “public static void main (String [ ] args)”:


Its method (Function) named main with string array as argument.
a. public : Access Modifier
b. static: static is reserved keyword which means that a method is accessible and usable even
though no objects of the class exist.
c. void: This keyword declares nothing would be returned from method. Method can return any
primitive or object.
d. Method content inside curly braces. { } asdfla;sd

5. System.out.println("Hello World from Java") :


a. System:It is name of Java utility class.
b. out:It is an object which belongs to System class.
c. println:It is utility method name which is used to send any String to console.
d. “Hello World from Java”:It is String literal set as argument to println method.

Download and Install JDK:


To develop and run any java program you need to install JDK in your system.
After selecting the Windows platform and clicking the Download button you’ll see a Login for
Download screen. Click Save File on the pop-up screen (the file name depends on the version of
JDK). Once download completes you can start installation.

© Copyright Virtual University of Pakistan 55


Introduction to Web Services Development (CS311)

Sentinel Controlled Loop:


The type of loop where the number of execution of the loop is unknown, is termed by sentinel
controlled loop. The value of the control variable differs within a limitation and the execution
can be terminated at any moment as the value of the variable is not controlled by the loop. The
control variable in this case is termed by sentinel variable.

Example: The following do....while loop is an example of sentinel controlled loop.


======
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
while(num>0);
======
In the above example, the loop will be executed till the entered value of the variable num is not 0
or less than 0. This is a sentinel controlled loop and here the variable num is a sentinel variable.

Module 4: (Using Objects)

Object Model:

© Copyright Virtual University of Pakistan 56


Introduction to Web Services Development (CS311)

A collection of objects or classes through which a program can examine and manipulate some
specific parts of its world. Such an interface is said to be the object model of the represented
service or system.
For example, the Document Object Model (DOM) is a collection of objects that represent a page
in a web browser, used by script programs to examine and dynamically change the page. There is
a Microsoft Excel object model for controlling Microsoft Excel from another program, and the
ASCOM Telescope Driver is an object model for controlling an astronomical telescope.

Object Reference
Objects can be accessed via object references. To invoke a method in an object, the object
reference and method name are given, together with any arguments.

Important Aspects of Object Model:

1. Abstraction:
Abstraction is the process of taking away or removing characteristics from something in order to
reduce it to a set of essential characteristics. It provides a generalized view of your classes or
object by providing relevant information.
Example:
Suppose you have 3 mobile phones as following:-

Nokia 1400 (Features:- Calling, SMS)


Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-
mails)

Abstract information which are Necessary and Common Information for the object "Mobile
Phone" is make a call to any number and can send SMS." The abstract class for object mobile
phone is as follows:

abstract class MobilePhone{ public void Calling(); public void SendSMS(); }


public class Nokia1400 : MobilePhone {
© Copyright Virtual University of Pakistan 57
}
public class Nokia2700 : MobilePhone{
public void FMRadio();
Introduction to Web Services Development (CS311)

2. Encapsulation:
Encapsulation is a way to obtain "information hiding" so, following your example, you don't
"need to know the internal working of the mobile phone to operate" with it. You have an
interface to use the device behavior without knowing implementation details. Encapsulation is
like your bag in which you can keep your pen, book etc. It means this is the property of
encapsulating members and functions.

Example:
TV operation
It is encapsulated with cover and we can operate with remote and no need to open TV and
change the channel.

Realization of the Object Model:

1. Classes:
Class is a blueprint of an object that contains variables for storing data and functions to
performing operations on these data. Class will not occupy any memory space and hence it is
only logical representation of data.

© Copyright Virtual University of Pakistan 58


Introduction to Web Services Development (CS311)

The class is represented as a rectangle, divided in 3 boxes one under another. The name of the
class is at the top. Next, there are the attributes of the class. At the very bottom are the operations
or methods. The plus/minus signs indicate whether an attribute / operation is visible (+ means
public) or not visible (- means private). Protected members are marked with #.
(Class Name)

-(Attribute)

+(Operations)

Normal Form
To create a class, you simply use the keyword "class" followed by the class name:
Class Employee
{

2. Object:
Objects are the basic run-time entities in an object oriented system. They may represent a person,
a place or any item that the program has to handle.

"Object is a Software bundle of related variable and methods.”


“Object is an instance of a class”

Class will not occupy any memory space. To work with the data represented by the class a
variable must be created, which is called as an object.
When an object is created by using the keyword “new”, then memory will be allocated for the
class in heap memory area, which is called as an instance and its starting address will be stored
in the object in stack memory area.

© Copyright Virtual University of Pakistan 59


Introduction to Web Services Development (CS311)

Example:

class Employee
{

}
Syntax to create an object of class Employee:-

Employee objEmp = new Employee();

Class Declaration:
The class declaration component declares the name of the class along with other attributes such
as the class's superclass, and whether the class is public, final, or abstract.
The class body (the area between the braces) contains all the code that provides for the life cycle
of the objects created from the class: constructors for initializing new objects, declarations for
the fields that provide the state of the class and its objects, and methods to implement the
behavior of the class and its objects.
Class declaration must contain the class keyword and the name of the class that is being defined.
Thus the simplest class declaration looks like this:

class NameOfClass
{
...
}

Class declarations can include these components, in order:

1. Modifiers such as public, private, and a number of others that you will encounter later.
2. The class name, with the initial letter capitalized by convention.

© Copyright Virtual University of Pakistan 60


Introduction to Web Services Development (CS311)

3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. The class body, surrounded by braces, {}.

Object Reference:
An "object reference" is a variable that acts as a handle/pointer/marker to a given object so that
its methods and fields maybe manipulated.
We can assign value of reference variable to another reference variable. Reference Variable is
used to store the address of the variable. By assigning Reference we will not create distinct
copies of Objects but all reference variables are referring to same Object.
Consider This Example –

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

r1 is reference variable which contain the address of Actual Rectangle Object.


r2 is another reference variable
r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does not
create duplicate object , nor does it allocate extra memory.

© Copyright Virtual University of Pakistan 61


Introduction to Web Services Development (CS311)

[468×60]

String:
String is a contiguous sequence of symbols or values, such as a character string or a binary digit
string. It represents text as a series of Unicode characters. A string is generally understood as a
data type and is often implemented as an array of bytes that stores a sequence of elements,
typically characters, using some character encoding.

Java uses the 16-bit Unicode character set that contains the characters from the ISOLatin-1 and
the 7-bit ASCII character sets.
To standardize the storing of alphanumeric characters, the American Standard Code for
Information Interchange (ASCII) was created. It defined a unique binary 7-bits number for each

© Copyright Virtual University of Pakistan 62


Introduction to Web Services Development (CS311)

storable character to support the numbers from 0-9, the upper/lower case English alphabet (a-z,
A-Z), and some special characters like ! $ + - ( ) @ < > .

Since ASCII used one byte (7 bits for the character, and one of bit for transmission parity
control), it could only represent 128 different characters. In addition 32 of these characters were
reserved for other control purposes.
Charsets are named by strings composed of the following characters:

The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'),


The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'),
The digits '0' through '9' ('\u0030' through '\u0039'),
The dash character '-' ('\u002d', HYPHEN-MINUS),
The plus character '+' ('\u002b', PLUS SIGN),
The period character '.' ('\u002e', FULL STOP),
The colon character ':' ('\u003a', COLON), and
The underscore character '_' ('\u005f', LOW LINE).

String:
String is traditionally a sequence of characters, some kind of variable. A string is generally
understood as a data type and is often implemented as an array of bytes (or words) that stores a
sequence of elements, typically characters, using some character encoding.

String is designed to be immutable. That is, once a String is constructed, its contents cannot be
modified. Otherwise, the other String references sharing the same storage location will be
affected by the change. The original String object will be deallocated, once there is no more
references, and subsequently garbage-collected.

Because String is immutable, it is not efficient to use String if you need to modify your string
frequently (that would create many new Strings occupying new storage areas). For example,

// inefficient codes

© Copyright Virtual University of Pakistan 63


Introduction to Web Services Development (CS311)

String str = "Hello";


for (int i = 1; i < 1000; ++i) {
str = str + i;
}

Creating a String object:


String can be created in number of ways, here are a few ways of creating string object.
1. String literal is a simple string enclosed in double quotes " ". A string literal is treated as a
String object.
String str1 = "Hello";
2. String str2 = new String(str1);
3. Using + operator (Concatenation)

String str4 = str1 + str2;


or,
String str5 = "hello"+"Java";

String object and How they are stored:

When we create a new string object using string literal, that string literal is added to the string
pool, if it is not present there already.

String str= "Hello";

© Copyright Virtual University of Pakistan 64


Introduction to Web Services Development (CS311)

And, when we create another object with same string, then a reference of the string literal already
present in string pool is returned.

String str2=str;

But if we change the new string, its reference gets modified.

© Copyright Virtual University of Pakistan 65


Introduction to Web Services Development (CS311)

str2=str2.concat("world");

String Length:
Returns the length of the string, in terms of bytes. This is the number of actual bytes that
conform the contents of the string, which is not necessarily equal to its storage capacity.

Example

Return the number of characters in a string:

var str = "Hello World!";


var n = str.length;

The result of n will be:


12

© Copyright Virtual University of Pakistan 66


Introduction to Web Services Development (CS311)

charAt(int index):
The method charAt(int index) returns the character at the specified index. The index value
should lie between 0 and length()-1. For e.g. s.charAt(0) would return the first character of the
string “s”. It throws IndexOutOfBoundsException if the index is less than zero or greater than
equal to the length of the string (index<0|| index>=length()).

Concatenation:
This method concatenates the string str at the end of the current string.
For e.g. s1.contact("Hello"); would concatenate the String “Hello” at the end of the String s1.
This method can be called multiple times in a single statement like this

1. Using concat() method


String s1="Beginners";
s1= s1.contact("Book").contact(".").concat("com");

2. Using + operator

string str = "Rahul";


string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";

String Comparison:
This means that if you call the equals() method to compare 2 String objects, then as long as the
actual sequence of characters is equal, both objects are considered equal. The == operator checks
if the two strings are exactly the same object.

String comparison can be done in 3 ways.

© Copyright Virtual University of Pakistan 67


Introduction to Web Services Development (CS311)

1. Using equals() method


2. Using == operator
3. By CompareTo() method

1. Using equals() method


Equals() method compares two strings for equality. Its general syntax is,

boolean equals (Object str)

It compares the content of the strings. It will return true if string matches, else returns false.

String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false
2. Using == operator
== operator compares two object references to check whether they refer to same instance. This
also, will return true on successful match.

String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false

3. By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less
than, equal to or greater than th other string. Its general syntax is,

© Copyright Virtual University of Pakistan 68


Introduction to Web Services Development (CS311)

int compareTo(String str)

To use this function you must implement the Comparable Interface. compareTo() is the only
function in Comparable Interface.

String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1

Comparing Object references


The two operators that can be used with object references are comparing for equality (==) and
inequality (!=). These operators compare two values to see if they refer to the same object.

If the objects have the same value, and not whether two objects are a reference to the same
object. For example,
(Star == Singer)
This is true only if name is a reference to the same object that "Singer" refers to. This will be
false if the String in name was read from other object, even though name really does have
exactly those characters in it.

Comparing Object values


The equals() method returns a boolean value. The previous example can be fixed by writing:

if (Star.equals("Singer")) // Compares values, not references.

© Copyright Virtual University of Pakistan 69


Introduction to Web Services Development (CS311)

(Star.equals("newSinger")) // Compares values, not references.

Because the equals() method makes a == test first, it can be fairly fast when the objects are
identical. It only compares the values if the two references are not identical.

More on Control Structures

© Copyright Virtual University of Pakistan 70


Introduction to Web Services Development (CS311)

Module 5: (Primitive values as objects)

A wrapper class is simply a class that encapsulates a single, immutable value.

Integer class wraps up an int value


Float class wraps up a float value.

Autoboxing and Unboxing


Autoboxing is the automatic conversion between the primitive types and their corresponding
object wrapper classes. For example, converting an int to an Integer, a double to a Double, and
so on. If the conversion goes the other way, this is called unboxing.
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is
called unboxing.
Passed as a parameter to a method that expects a value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive type.
Here is the simplest example of autoboxing and unboxing:

Integer iRef = 10; //Automatic boxing

© Copyright Virtual University of Pakistan 71


Introduction to Web Services Development (CS311)

Int j = iRef; // Automatic Unboxing


Extending Assignment Operator:
+= assigns the result of the addition.
-= assigns the result of the subtraction.
*= assigns the result of the multiplication
/= assigns the result of the division.
%= assigns the remainder of the division.
&= assigns the result of the logical AND.
|= assigns the result of the logical OR.
^= assigns the result of the logical XOR.
<<= assigns the result of the signed left bit shift.
>>= assigns the result of the signed right bit shift.
>>>= assigns the result of the unsigned right bit shift.

Examples:

To assign the result of an addition operation to a variable:

//add 2 to the value of number


number = number + 2;

Using the assignment operator "+=" to do the same thing:

//add 2 to the value of number


number += 2;

Unary increment & decrement operators:


Increment (++) and decrement (--) operators easily add 1 to, or subtract 1 from, a variable. For
example, using increment operators, you can add 1 to a variable named a like this:

a++;

© Copyright Virtual University of Pakistan 72


Introduction to Web Services Development (CS311)

An expression that uses an increment or decrement operator is a statement itself. That’s because
the increment or decrement operator is also a type of assignment operator because it changes the
value of the variable it applies to.

An increment or decrement can also be used as operator in an assignment statement:

int a = 5;
int b = a--; // both a and b are set to 4

Increment and decrement operators can be placed before (prefix) or after (postfix) the variable
they apply to. If an increment or decrement operator is placed before its variable, the operator is
applied before the rest of the expression is evaluated. If the operator is placed after the variable,
the operator is applied after the expression is evaluated.

For example:

int a = 5;
int b = 3;
int c = a * b++; // c is set to 15
int d = a * ++b; // d is set to 20

Counter-controlled loops: for loop


The general loop construction is mostly used for counter-controlled loops where the number of
iterations is known beforehand.

for (initialization ; condition ; increment)


statement

© Copyright Virtual University of Pakistan 73


Introduction to Web Services Development (CS311)

The initialization names the loops control variable and provides its initial value, condition
determines whether the loop should continue executing and increment modifies the control
variable's value so that the loop-continuation condition eventually becomes false.

All three expressions in a for statement are optional. If the condition is omitted, loop-continuation
condition is always true, thus creating an infinite loop. The initialization expression may be
omitted if the program initializes the control variable before the loop. The increment expression
may be omitted if the program calculates the increment with statements in the loop's body or if no
increment is needed.

Example:
public class ForCounter
{
public static void main( String[] args )
{
// for statement header includes initialization,
// loop-continuation condition and increment
for ( int counter = 1; counter <= 10; counter++ )
System.out.printf( "%d ", counter );

System.out.println(); // output a newline


} // end main
} // end class ForCounter

© Copyright Virtual University of Pakistan 74


Introduction to Web Services Development (CS311)

A common logic error with counter-controlled repetition is an off-by-one error.


For example, if the above condition is changed to counter < 10, the loop would iterate only nine
times.

Nested Loop:

Nested repetition is when a control structure is placed inside of the body or main part of another
control structure. Put any construct inside of any other construct. However, you may not have
them partially overlap each other.

Example: Print the multiplication tables from 1 to 10.

© Copyright Virtual University of Pakistan 75


Introduction to Web Services Development (CS311)

Module 6: (Arrays)

Arrays:
An array is an object containing a list of elements of the same data type.

We can create an array by:


 Declaring an array reference variable to store the address of an array object.
 Creating an array object using the new operator and assigning the address of the array to the
array reference variable.

Here is a statement that declares an array reference variable named dailySales:

double[ ] dailySales;

The brackets after the key word double indicate that the variable is an array reference variable.
This variable can hold the address of an array of values of type double. We say the data type of
dailySales is double array reference.

The second statement of the segment below creates an array object that can store seven values of
type double and assigns the address of the array object to the reference variable named
dailySales:

double[ ] dailySales;

dailySales = new double[7];

The operand of the new operator is the data type of the individual array elements and a bracketed
value that is the array size declarator. The array size declarator specifies the number of elements
in the array.

© Copyright Virtual University of Pakistan 76


Introduction to Web Services Development (CS311)

It is possible to declare an array reference variable and create the array object it references in a
single statement.

Here is an example:

double[ ] dailySales = new double[7];

The statement below creates a reference variable named dailySales and an array object that can
store seven values of type double as illustrated below:

double[ ] dailySales = new double[7];

dailySales address

1st value 2nd value 3rd value 4th value 5th value 6th value 7th value

Initializing an Array:
Declare an array of 10 integer values.

This declaration declares an array named num that contains 10 integers. When the compiler
encounters this declaration, it immediately sets aside enough memory to hold all 10 elements.

© Copyright Virtual University of Pakistan 77


Introduction to Web Services Development (CS311)

The square brackets ([ ]) after the "type" indicate that num is going to be an array of type int
rather than a single instance of an int. Since the new operator creates (defines) the array, it must
know the type and size of the array. The new operator locates a block of memory large enough
to contain the array and associates the array name, num, with this memory block.

A program can access each of the array elements (the individual cells) by referring to the name
of the array followed by the subscript denoting the element (cell). For example, the third
element is denoted num[2].

Storing Array Elements:

One dimensional arrays are stored in the memory in exactly the way you see them in your head.
In a line. The array gets stored in exactly that way in the memory.

Two-dimensional arrays are stored row wise, i.e. n elements of first row are stored in first n
locations, n elements of second row are stored in next n locations and so on.

© Copyright Virtual University of Pakistan 78


Introduction to Web Services Development (CS311)

Multi-Dimensional Array:
Arrays can have more than one dimension, these arrays-of-arrays are called multidimensional
arrays.
Multi-Dimensional array reserves space (construct) for each array that will store the values;
because each array is processed separately, it is possible to set different sizes and create a zig-
zag, this is precisely the logic computer would use to understand any n-dimensional arrays, i.e.
each time as a single row of elements, where each element is itself an array of n-1 dimensions.
Keep doing till 0-dimensional array, or a single element.

Iterating over an array.


One-dimensional array
To walk through every element of a one-dimensional array, we use a for loop, that is:

int[] myArray = new int[10];


for (int i = 0; i < myArray.length; i++) {

© Copyright Virtual University of Pakistan 79


Introduction to Web Services Development (CS311)

myArray[i] = 0;
}
Two-dimensional array
For a two-dimensional array, in order to reference every element, we must use two nested loops.
This gives us a counter variable for every column and every row in the matrix.

int cols = 10;


int rows = 10;
int[][] myArray = new int[cols][rows];

// Two nested loops allow us to visit every spot in a 2D array.


// For every column I, visit every row J.
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
myArray[i][j] = 0;
}
}

Multidimensional Array:
Simply use two nested for loops. To get the sizes of the dimensions, use GetLength():

for (int i = 0; i < arrayOfMessages.GetLength(0); i++)


{
for (int j = 0; j < arrayOfMessages.GetLength(1); j++)
{
string s = arrayOfMessages[i, j];
Console.WriteLine(s);
}
}

© Copyright Virtual University of Pakistan 80


Introduction to Web Services Development (CS311)

This assumes you actually have string[,]. By using GetLowerBound() and GetUpperBound() the
get the bounds for each dimension.

To generate a random number we can use the class java.util.Random. Such number are called
pseudo-random numbers, as they are not really random.
If you wanted a random double between 0.0 and 10.0 here is how you would generate it.

// Generate random doubles 0.0 <= d < 10.0


import java.util.Random;
// ...
// This time, to get different results each run,
Random wheel = new Random();
//...
for ( int i=0; i<100; i++ ){
// generate a number between 0.0 <= x < 1.0, then scale
double d = wheel.nextDouble() * 10.0d;
out.println( d );
}

© Copyright Virtual University of Pakistan 81


Introduction to Web Services Development (CS311)

Module 7: (Classes)

Class:
Class are templates that are used to create objects, and to define object data types and methods.
Core properties include the data types and methods that may be used by the object. All class
objects should have the basic class properties. Classes are categories, and objects are items
within each category.

Classes defined in the following way:

class MyClass {
// field, constructor, and
// method declarations
}

This is a class declaration. The class body (the area between the braces) contains all the code that
provides for the life cycle of the objects created from the class: constructors for initializing new
objects, declarations for the fields that provide the state of the class and its objects, and methods
to implement the behavior of the class and its objects.

Parameter Passing:
The terms "arguments" and "parameters" are used interchangeably; they mean the same thing.
We use the term formal parameters to refer to the parameters in the definition of the method. In
the example that follows, x and y are the formal parameters.

We use the term actual parameters to refer to the variables we use in the method call. In the
following example, length and width are actual parameters.

// Method definition

© Copyright Virtual University of Pakistan 82


Introduction to Web Services Development (CS311)

public int mult(int x, int y)


{
return x * y;
}

// Where the method mult is used


int length = 10;
int width = 5;
int area = mult(length, width);

Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is
passed. Copy inside the method is changed, but this will have no effect on the actual parameter.

Passing Arrays:
Arrays are references. This means that when we pass an arrays as a parameter, we are passing its
handle or reference. So, we can change the contents of the array inside the method.

public static void tryArray(char[] b)


{
b[0] = 'x';
b[1] = 'y';
b[2] = 'z';
}

When the following code is executed, the array a does indeed have the new values in the array.

char[] a = {'a', 'b', 'c'};


tryArray(a);
System.out.println("a[0] = " + a[0] + ", a[1] = " + a[1] +
", a[2] =" + a[2]);

© Copyright Virtual University of Pakistan 83


Introduction to Web Services Development (CS311)

The print statements produces "a[0] = x, a[1] = y, a[2] = z".

Constructors:
Constructors are the methods which are used to initialize objects. Constructor method has the
same name as that of class, they are called or invoked when an object of class is created and can't
be called explicitly.
Constructor declarations look like method declarations—except that they use the name of the
class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {


gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

New Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument
constructor:

public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}

© Copyright Virtual University of Pakistan 84


Introduction to Web Services Development (CS311)

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle
object called yourBike.

In general, class declarations can include these components, in order:

 Modifiers such as public, private, and a number of others that you will encounter later.
 The class name, with the initial letter capitalized by convention.
 The name of the class's parent (superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
 A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
 The class body, surrounded by braces, {}.

Object Creation and Referencing:


Object is something that has a state in memory.

When an object is created by using new operator, the space in memory is reserved and the
structure to hold variables is created. This would definitely like to create a handler (reference)
that would keep track of Meta information (like the memory address where the object memory is
reserved etc).

A class provides the blueprint for objects; you create an object from a class. Each of the
following statements taken from the CreateObjectDemo program creates an object and assigns it
to a variable:

Point originOne = new Point(23, 94);


Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

© Copyright Virtual University of Pakistan 85


Introduction to Web Services Development (CS311)

The first line creates an object of the Point class, and the second and third lines each create an
object of the Rectangle class.

Each of these statements has three parts (discussed in detail below):

 Declaration: The code set in bold are all variable declarations that associate a variable name
with an object type.
 Instantiation: The new keyword is a Java operator that creates the object.
 Initialization: The new operator is followed by a call to a constructor, which initializes the
new object.

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you
create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the
constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to
a variable of the appropriate type, like:

Point originOne = new Point(23, 94);

The reference returned by the new operator does not have to be assigned to a variable. It can also
be used directly in an expression. For example:

© Copyright Virtual University of Pakistan 86


Introduction to Web Services Development (CS311)

int height = new Rectangle().height;


Initializing an Object

The code for the Point class:

public class Point {


public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor in the Point class takes
two integer arguments, as declared by the code (int a, int b). The following statement provides 23
and 94 as values for those arguments:

Point originOne = new Point(23, 94);

The result of executing this statement can be illustrated in the figure:

originOne now points to a Point object.

© Copyright Virtual University of Pakistan 87


Introduction to Web Services Development (CS311)

The code for the Rectangle class, which contains four constructors:

public class Rectangle {


public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle


public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

© Copyright Virtual University of Pakistan 88


Introduction to Web Services Development (CS311)

// a method for computing the area of the rectangle


public int getArea() {
return width * height;
}
}

Each constructor lets you provide initial values for the rectangle's origin, width, and height, using
both primitive and reference types. If a class has multiple constructors, they must have different
signatures.

Rectangle rectOne = new Rectangle(originOne, 100, 200);

This calls one of Rectangle's constructors that initializes origin to originOne. Also, the
constructor sets width to 100 and height to 200. There are two references to the same Point
object—an object can have multiple references to it.

© Copyright Virtual University of Pakistan 89


Introduction to Web Services Development (CS311)

The following line of code calls the Rectangle constructor that requires two integer arguments,
which provide the initial values for width and height. If you inspect the code within the
constructor, you will see that it creates a new Point object whose x and y values are initialized to
0:

Rectangle rectTwo = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn't take any arguments, so it's
called a no-argument constructor:

Rectangle rect = new Rectangle();

All classes have at least one constructor. If a class does not explicitly declare any, the compiler
automatically provides a no-argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor, or the Object constructor if the class
has no other parent. If the parent has no constructor (Object does have one), the compiler will
reject the program.

Declaring a Variable to Refer to an Object


1. Create Distinct Objects.
2. Allocate Memory
3. Create duplicate Copy

Consider This Example –

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

r1 is reference variable which contain the address of Actual Rectangle Object.


r2 is another reference variable

© Copyright Virtual University of Pakistan 90


Introduction to Web Services Development (CS311)

r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does not
create duplicate object , nor does it allocate extra memory.

class Rectangle {
double length;
double breadth;
}

class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

r1.length = 10;
r2.length = 20;

System.out.println("Value of R1's Length : " + r1.length);


System.out.println("Value of R2's Length : " + r2.length);

© Copyright Virtual University of Pakistan 91


Introduction to Web Services Development (CS311)

}
}

Output:

Value of R1's Length: 20.0


Value of R2's Length: 20.0

When variable is declared as field (static or instance variable inside class), then initialization of
that variable is optional. In other words, while declaring field variable you may or may not
initialize to its value.

Following table shows variables types and their default values


data type Default value
boolean false
char \u0000
int,short,byte / long 0 / 0L
float /double 0.0f / 0.0d
any reference type null

Char primitive default value is \u0000, which means blank/space character.

© Copyright Virtual University of Pakistan 92


Introduction to Web Services Development (CS311)

When you have the variable of reference types then it gets the null as default value.

When local/block variable is declared, they didn’t get the default values. They must assigned
some value before accessing it otherwise compiler will throw an error.

Declaration of Behaviors: methods


A method is a set of code which is referred to by name and can be called (invoked) at any point
in a program simply by utilizing the method's name.
Each method has its own name. When that name is encountered in a program, the execution of
the program branches to the body of that method. When the method is finished, execution
returns to the area of the program code from which it was called, and the program continues on
to the next line of code.

Example of a typical method declaration:

public double calculateAnswer(double wingSpan, int numberOfEngines,


double length, double grossTons) {
//do the calculation here
}

© Copyright Virtual University of Pakistan 93


Introduction to Web Services Development (CS311)

The only required elements of a method declaration are the method's return type, name, a pair of
parentheses, (), and a body between braces, {}.

More generally, method declarations have six components, in order:

 Modifiers—such as public, private, and others.


 The return type—the data type of the value returned by the method, or void if the method
does not return a value.
 The method name—the rules for field names apply to method names as well, but the
convention is a little different.
 The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by
their data types, enclosed by parentheses, (). If there are no parameters, you must use empty
parentheses.
 The method body, enclosed between braces—the method's code, including the declaration of
local variables, goes here.

Access Modifiers
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.

Private Access Modifier - private:


Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Class and
interfaces cannot be private. Variables that are declared private can be accessed outside the class
if public getter methods are present in the class. Using the private modifier is the main way that
an object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:

© Copyright Virtual University of Pakistan 94


Introduction to Web Services Development (CS311)

public class Logger {


private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly. So to make this variable available to the outside world, we
defined two public methods: getFormat(), which returns the value of format, and
setFormat(String), which sets its value.

Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.

Example:

The following function uses public access control:

public static void main(String[] arguments) {


// ...
}

© Copyright Virtual University of Pakistan 95


Introduction to Web Services Development (CS311)

The main() method of an application has to be public. Otherwise, it could not be called by a Java
interpreter (such as java) to run the class.

Return Value

The method's return type is an int type in the code above. After the method type, you need a
space followed by the name of method. In between a pair of round brackets we've method
variable called aNumber, and that it will be an integer.

To separate this method from any other code, a pair of curly brackets are needed. The return
value can't be a string if you started the method with int total.

A method that doesn't return any value at all can be set up with the word void. In which case, it
doesn't need the return keyword. Here's a method that doesn't return a value:

Parameter Names

© Copyright Virtual University of Pakistan 96

You might also like