Você está na página 1de 50

Object Oriented

Programming

This book belongs to

Name :

Batch :

SQL Star International Ltd.


Copyright © 2009
First Edition

SQL STAR INTERNATIONAL LIMITED

SQL Star House,


No. 8-2-293/174/A 25,
Road No. 14, Banjara Hills,
Hyderabad - 500 034,
Andhra Pradesh, INDIA
Tel. No. 91- 40-23101600(30 lines)
Fax No. 23101663
Toll Free No: 1800 425 2944

Email: knowledge.services@sqlstar.com

No part of this publication may be reproduced (incl. photocopying) in any way, without prior
agreement and written permission of SQL Star International Ltd., Hyderabad. SQL Star
International Ltd., Hyderabad assumes no responsibility for its use, nor for any infringements
of patents or other rights of third parties which could result.
Table of Contents

Chapter Page No

Chapter 01: Object-Oriented Programming 01 -09

Procedural Paradigm Fallbacks


Procedural vs. Object Oriented
Object Oriented Programming
Benefits of Object Oriented Programming
Most common Reasons for Project Failure
Advantages of the OOP Approach

Chapter 02: OOP Core Concepts 01-13

OOP Core Concepts


Implementing Corner stones of OOP
Some OOP Terminologies
Visibility of Members

TM
Chapter 03: Explaining Java Technology 01-25

SDLC Process
Understand the features of Java Technology
Major characteristics of Java programming language
Java Technology Product Groups
Java 2 Platform Standard Edition Documentation
Setting up a Java environment
Writing your first java Program
Testing the sample program
Various java tools

© SQL Star International Ltd. 2009


Object-Oriented Programming

Chapter 1

Object-Oriented Programming
Procedural Paradigm Fallbacks
Procedural vs. Object Oriented
Object Oriented Programming
Benefits of Object Oriented Programming
Most common Reasons for Project Failure
Advantages of the OOP Approach

© SQL Star International Ltd. 2009


Object-Oriented Programming

Objective

At the end of this chapter, you will be able to:

• Understand Procedural Paradigm Fallbacks

• Distinguish Procedural vs. Object Oriented

• Get an idea about Object Oriented Programming

• Know the benefits of Object Oriented Programming

• Learn the most common reasons for Project Failure

© SQL Star International Ltd. 2009


2
Object-Oriented Programming

Introduction
To draw a real world parallel, programming languages are like civilizations. They have
followed the same phenomenon like civilizations – they rose, flourished, and declined. And
yet, like the rise and fall of nations paved the path for mankind to progress, programming
languages have evolved through time. In case of programming languages, whenever a
new language replaced its predecessor, the ongoing refinement of programming
proceeded.
Like other modern programming languages such as C++, Java uses a combination of
techniques developed over the years. Therefore, we will start exploring object-oriented
programming (OOP) by briefly looking at the history of programming languages and their
consequent developments.
Once you understand why OOP was developed, you will know exactly what makes a
programming language object-oriented.
Early days of programming or computing demanded an extremely labored process. Each
and every process had to be thoroughly checked to ensure flawless program. Early
languages were known as machine languages, which later evolved to assembly languages.
Machine language programming required programmers to code CPU instructions to
manipulate individual memory locations to achieve a desired result. Assembly language
programming provided a minimal level of abstraction by combining commonly used
sequences of instructions into higher-level instructions that could be referred by a name.
Assembly languages were easier to work with than machine languages, but programmers
soon saw the need to move beyond CPU instructions and work at a higher level of
abstraction. They achieved this abstraction through “Procedural Languages” helping
programmers to manipulate easily with functions and data types without concerning about
the underlying machine instructions. For instance, you might create a procedure to write
something to the screen, such as writeln in Pascal or printf in C. Initially, with this type
of programming you could always write these functions without any modification to any
data that existed external to them.
But as the complexity grew dramatically with increasing program size, attention focused
on how well code was actually written and how well it could be maintained. This led to the
implementation of structured development practices. “Structured development” didn't
necessarily change the languages that were being used, but rather provided a new method
of designing and writing software. Under a structured development philosophy,
programmers were expected to plan 100% of a program before writing any code. In
addition, the programmers were pushed to pre-design all their code before actually writing
any of it.

Procedural Paradigm Fallbacks


Earlier a program had to be written in a procedural manner- i.e. the statements were
written in the form of a batch. But eventually, the level of program code became large
with respect to the requirements that were always hard to maintain. To solve this problem,

© SQL Star International Ltd. 2009 3


Object-Oriented Programming

functions were introduced to reduce the size of the programs that considerably reduced
the size of the program code. But this was not a permanent solution to the problem.

“Procedural Paradigm” had a critical problem of giving more importance to the function
and treating data as a stepson. In such kind of programming, the original data gets
corrupted easily and any one who does not have the rights, can easily access, as data is
accessible to all the functions.

Procedural vs. Object Oriented


Whenever objects are created in a program, these objects and their methods are used to
operate the program. The distinct difference between procedural or structured and object-
oriented programming is that the structured programming uses the data given to them
through parameters, while in object-oriented programming, the methods act upon the
object’s data or fields. The programming became quite easier in case of object-oriented
concept as the fields were already set and you did not have to worry whether the correct
field was passed to the correct method. You only had to call that method whenever you
need it in the program code.

Try it out:

Briefly describe the major difference object-oriented and procedural programming


languages?

Object Oriented Programming


Object-oriented programming (OOP) is a programming language model that is centered
around "objects" rather than "actions" and “data” rather than logic. Earlier you considered
a program to be a logical procedure with input data processed to produce output data.
Object-oriented programming is concerned mainly with objects and their manipulation
rather than the logic required to manipulate data.

I am also an Object!

Fig 1: Objects in the world

© SQL Star International Ltd. 2009


4
Object-Oriented Programming

The world consists of many objects like table, cycle, computer, pen, telephone etc. In this
world, even you are an Object! Every object; be it a pen or a chair or ‘You’; has attributes
and behavior. Such objects are shown in Fig.1. All objects have features and each such
feature is called an attribute of that object. For example, ink in a pen is an attribute of
pen. The functionality of an object is called behavior. For example, writing is a behavior of
pen.
Most of the objects manipulate other objects or data. For example, a car is an object that
manipulates its speed and direction to transport people to a different location. This car
object encapsulates all the functions and data that it needs to get its job done. It has a
switch to turn it on, a steering wheel to control its direction of motion, and brakes to slow
it down. These functions directly manipulate the car's data, including direction, position,
and speed.
When you travel in a car, however, you do not have to know the details of how these
operations work. To turn a car, simply revolve the steering wheel. You do not have to
know how the steering wheel turns the car. You simply know that it works.

Seat Wheel
Steering

• Fig. 2: Aggregation diagram for Objects

Objects can be part of other objects. This relationship between objects is known as
aggregation as shown in Fig. 2.

Benefits of Object Oriented Programming


Object Oriented Programming tries to address three main goals of software engineering:

• Re-usability
• Flexibility
• Extensibility
OOP has the following benefits over conventional approaches by bundling code into
individual software objects:
• Modularity: The source code for an object can be written and maintained
independent of the source code for other objects. Once created, an object can be
easily passed around inside the system.
• Information hiding: By interacting only with an object's methods, the details of
its internal implementation remain hidden from the outside world.
• Code reusability: If an object already exists (perhaps written by another software

© SQL Star International Ltd. 2009 5


Object-Oriented Programming

Developer), you can use it in your program. This allows specialists to


implement/test/debug complex, task-specific objects, which you can then trust, to
run in your own code.
• Pluggability and debugging ease: If a particular object turns out to be
problematic, you can simply remove it from your application and plug in a different
object as its replacement. This is same as to fixing mechanical problems in the real
world. If a bolt breaks, you replace it, not the entire machine.

Try it out:

If a developer has written a code for medicine detail, can another developer
develop codes for patient detail and at the same time using medicine detail
code? What concept is used behind this?

Why Projects Fail?


Information Technology projects sometimes fail due to certain reasons. Technical issues,
project management, and business decisions are some of the factors that determine why
they fail. The way each dimension interacts with the other becomes complicated at times.
This intensifies risks and problems involved in the project thus increasing the chances of
failure.

A project may fail because of a number of reasons. Some of these are listed below.

• Poor Scope Management


There is poor initial scope definition, which means underestimation of project
complexity. This results from the failure to progressively elaborate and document the
changes to the scope that has the potential to delay delivery of project because
deliverables fall short of sponsor expectations.
• Poor Time Management
If the time management is poor, then the probability of failing to identify and define all
activities required for the project as well as gross underestimation of these activities is
more. Hence, the delivery of projects may not be on time. This may lead to increasing
sponsor anxiety, resulting in abrupt termination of project.
• Poor Cost Management
If the cost management is poor, it means there is not enough provision for required
resource scope and cost during the early planning (often quotation) stage. This may
lead to cancellation of the project due to a “cost blowout” later in the project.
• Poor Quality Management
It is essential to perform a regular quality check and to take remedial actions at every
step in a project, if there is any requirement for the quality of the project deliverables.
Any project fails due to its low quality during development, as the sponsor cannot
maintain faith in the final outcome and cancels the project.

© SQL Star International Ltd. 2009


6
Object-Oriented Programming

• Poor Human Resource Management


Human resource management is poor means that the team planning and development
is poor. This again means vague responsibilities, under-staffing and instability that lead
to a lack of staff motivation and direction. These situations lead to lapse in quality and
ultimately slowing-down of progress.
• Poor Communication Management
Sound communication among the Project Manager, the project sponsor and team
members facilitates success of project, otherwise there is a chance of project failure
due to misunderstandings.
• Poor Risk Management
Due to untested assumptions, failure to manage risk items is more in case you are not
addressing them adequately early in a project. This may lead to a huge cost blowout
later on as the severity of these items becomes fully apparent.

OOP technology comes to rescue


Software development productivity is one of the major concerns in the highly competitive
software market because of the shortening of the software development cycle. The object-
oriented technology has features like re-usability, better understanding of the problem,
simpler and cheaper designs and implementations. It helps in improving software
development productivity considerably.

Advantages of the OOP Approach


Like structured programming in legacy systems, object-oriented programming (OOP) has
so far succeeded to manage the complexity of software systems. Moreover, OOP
technology provides several advantages.
• Enables the use of real-world modeling:
Consider an example. A motorbike is an object that has specific attributes, such as an
engine and wheels. Using OOP principles, you would model the motorbike as a
motorbike object in Java that would have the same properties.
• Promotes the reuse of code:
Instead of writing the code from scratch for every new project, consider how
advantageous it will be if you can build a software by integrating already available code
blocks. Thus, a code that defines an object can be shared with several other objects in
the application. For example, the code used to define a type of pen can be used for
designing different types of pens. Thus, you do not have to rewrite the code for various
types of pens. The amount of effort required for coding, debugging, testing and
possible up gradation in future is reduced.
• Provides flexibility in the modification of an existing application:
Flexibility in terms of design and implementation of a solution is promoted by OOP.
What are the further cycles in application development? maintenance and upgrades.
With OOP practices, it becomes easier to extend applications.
To understand it in a better way, take the example of a car. A car may differ in types
of seating arrangement. Suppose an automobile manufacturing company produces a

© SQL Star International Ltd. 2009 7


Object-Oriented Programming

two-seated and a four-seated car. Sometime later, it decides to manufacture a six-


seated car. To meet the change in the requirement, the company needs to incorporate
changes into its current application system. If the company is already using OOP
concept, extension to the current system can be simplified. Thus the new car would be
able to reuse some of the code written for older car.
• Helps with the maintenance of Code:
In OOP, code maintenance is easier because you can create separate components or
modules as per the requirement. We are able to divide a component into separate
class. For example, to design the trader-buyer status, you can create classes such as
Trader and Buyer. By creating the Trader and the Buyer classes, information related to
each class can be separated. Thus, whenever you want to change any of the detail in
any class, it will not affect the functionality of the other class. Thus, the maintenance
of the whole process is simplified by reducing dependencies between classes.
• Encourages development of OOP Languages & Platforms:
We have seen a remarkable development in OOP Languages & Platforms. In late 1960s
SIMULA was the first object-oriented language used for simulating system behavior. In
1970s, the first object-oriented programming language, Xerox's Smalltalk, was used to
create the graphical user interface (GUI). Some time later ACTOR and Eiffel were OOP
languages. Today, C++ and Java are the major OOP languages, while C#, Python,
Visual Basic.NET and JavaScript are also popular.

© SQL Star International Ltd. 2009


8
Object-Oriented Programming

Summary
In this chapter, you learned:

y Like other modern programming languages such as C++, Java uses a


combination of techniques developed over the years.
y Machine language programming required programmers to code CPU
instructions to manipulate individual memory locations to achieve a desired result.
Assembly language programming provided a minimal level of abstraction by
combining commonly used sequences of instructions into higher-level instructions
that could be referred to by name.
y “Procedural Languages” helped programmers to write logics easily using
functions and data types without concerning about the underlying machine
instructions.
y “Procedural Paradigm” had a critical problem of giving more importance to
the function and treating data as a stepson.
y The distinct difference between procedural or structured and object-oriented
programming is that the structured programming uses the data given to them
through parameters, while in object-oriented programming, the methods of object
act upon the object’s data or fields.
y Object-oriented programming (OOP) is a programming model that is
centered on "objects" rather than "actions" and “data” rather than logic.
y Object Oriented Programming solves three main software engineering goals
i.e. Re-usability, Flexibility and Extensibility.

© SQL Star International Ltd. 2009 9


OOP Core Concepts

Chapter 2

OOP Core Concepts


OOP Core Concepts
Implementing Corner stones of OOP
Some OOP Terminologies
Visibility of Members

© SQL Star International Ltd. 2009


OOP Core Concepts

Objective
At the end of this chapter, you will be able to:

• Describe OOP Core Concepts

¾ Class

¾ Object

¾ Abstraction

¾ Encapsulation

¾ Inheritance

¾ Polymorphism

• Implement Corner stones of OOP

• Understand Some OOP Terminologies

• Understand about the Visibility of Members

© SQL Star International Ltd. 2009


2
OOP Core Concepts

Introduction
You have gained introductory knowledge about the “Evolution of OOP as a concept” and its
benefits over other programming models. In this chapter you will delve deeper into the
OOP model and understand what it takes to make an “OOP”.

OOP Core Concepts


To learn about OOP, you need to understand the main concepts that form the backbone of
OOP. These concepts, which are covered in the following sections, are:
• Class
• Object
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

Class
In real world, you will often find many individual objects, all of the same kind. Take the
example of a car. There may be thousands of other cars in existence, all of the same make
and model. Each car is built from the same set of blueprints and therefore contains the
same components. In object-oriented terms, we say that car is an instance of the class of
objects known as Car. A class is the blueprint from which individual objects are created.
What is a class? It is a template for multiple objects with similar features. All the features
of a particular set of objects are embodied by the class. So, it is the class and not the
actual objects that are defined when a program is written in an object-oriented language.

Object
The key to understand object-oriented technology is to have a clear understanding of
objects. What are the real-world examples of objects? Well, almost anything and
everything – your dog for instance. Or the desk you use, the computer, the bike etc.
Two characteristics shared by the real-world objects are:
1. State and
2. Behavior
A very efficient point to begin thinking in object-oriented programming is identifying the
state and behavior of real-world objects. For instance, the state for dog will be its name,
color, breed or whether it is hungry? It will also have behavior like barking, wagging tail,
fetching things, etc. Your bike will also have state (current speed, current gear, and
current wheel rotation, etc.) and behavior (acceleration, changing gear, changing wheel
rotation, etc.).
Now you can see that conceptually software objects are similar to real-world objects. They
also have state and related behavior. The state of the object is stored in fields (the
variables in some Programming languages). The internal state of an object is operated by
methods and serves as the primary mechanism for object-to-object communication.

© SQL Star International Ltd. 2009 3


OOP Core Concepts

Try it out

1. In real world, a ballpoint pen is used for writing purpose.


So, what do we call a ballpoint pen in object-oriented programming
language? What characteristic does it share?

2. In the above question, specify the Class?

Abstraction
What is abstraction? It is a process that reduces the information content of a concept. It is
typically done to retain only the information which is relevant for a particular purpose. The
complexity of the program is managed by abstraction. For instance, take the white
Doberman pinscher breed of dog. Abstracting this to a dog retains only the information on
general dog attributes and behaviour.
Abstraction has four major attributes such as Coherence, Conciseness, Identity and
Completeness. These features make ‘Abstraction’ an essential element for Object-Oriented
Programming. In a sense, when someone works on a computer, it is not necessary that
he should know the working of each and every part of the computer. Even without the
hardware knowledge, he can e-mail, type or do other jobs on the computer.

Do you think about how the


different parts of your car
engine work while driving?

Fig. 1: Abstraction diagram

Similarly, people do not think of a computer as a unit made up of hundreds of cards and
chips, but as a well-defined object with its own unique behavior. When you interact with
objects in the world, often you are only concerned with a subset of their properties.

© SQL Star International Ltd. 2009


4
OOP Core Concepts

Without this ability to abstract or filter out the extra properties of objects, you would find it
hard to process all the code and concentrate on the task at hand. As a result of
abstraction, when two different people interact with the same object, they often deal with
a different subset of attributes. Fig. 1 gives you a brief idea about abstraction. When you
are driving a car, for example, you need to know the speed of the car and the direction it
is going. Because the car is automatic, you do not need to know the RPMs of the engine.
Hence, you filter this information out. On the other hand, this information would be critical
to a racecar driver, who would not filter it out.
While constructing objects in OOP applications, it is important to incorporate the concept
of abstraction. If you were building a shipping application, you would construct a product
object with attributes, such as size and weight. The color of the item would be extraneous
information and filtered out. On the other hand, when constructing an order-entry
application, the color could be important and would be included as an attribute of the
product object.
Consider a simple “student” object. A real “student” has an identity, a family genealogy, a
medical history, a genetic profile, a credit record, a set of talents, and many more. These
are the student's attributes. Similarly, there is a rich set of actions or behaviors of which
the student is capable (singSong, doDance, getSick, increaseCreditLimit, payBills, etc.). To
know the genetic profile of the student you can abstract it out and avoid other extraneous
information.

Encapsulation
Encapsulation is a process by which you can hide data fields and methods inside the
object. It is needless to say that data fields and methods are the two main elements of an
object in the Java programming language. Encapsulation draws the demarcation line
between conventional structured Programming and object-oriented Programming.
The data of an object is always private to the object in strict object-oriented design. The
data should not be accessible directly outside the object. The access can be controlled if
you use encapsulation as you can force programs to retrieve or modify data only through
the interface of the object.
Can you think of any way in which data hiding is different from an approach of structured
programming? Data can always be hidden inside functions. You only need to keep that
data local to the function. However, soon you face a problem if you want to make the data
of one function to be available to other functions. In a structured program you can do this
by making the data global to the program, so that any function can access it. Seemingly,
you can use another level of scope. One of this is to have your data global to those
functions that need it, but at the same time prevent other functions from gaining access.
This is exactly what is done by Encapsulation. The encapsulated data members in an
object are global to the methods of an object and yet they are not global variables. They
are local to the object.
A well-established use of encapsulation in software design and development is the
separation of an interface from an implementation. Interface is viewed as the visible
external aspect of the software that must be understood to manipulate the software. The
implementation is viewed as the hidden intrinsic aspect of the software that is only
relevant to the implementers.

© SQL Star International Ltd. 2009 5


OOP Core Concepts

Inheritance
Inheritance enables you to create a class that is similar to a previously defined class.
Despite being the replica, the new class can possess its own properties.
Vehicle

Fig. 2: Inheritance diagram

The Fig. 2 can help you understand inheritance in an easy way. See how Car, Bus and
Truck inherit some characteristics or features from super class ‘Vehicle’.
In other words it is inheritance by which they derive some property from their parent
object.
Take the case of a car-simulation program. Assume that, for a regular car, you have a
class. However, now you want to create a car with a high-speed passing gear. You would
have needed to modify the existing code considerably to do this in a traditional program.
Moreover, this probably would have resulted in bugs into the code. This is where an
object-oriented approach helps, as you can create a new class by inheritance. All the data
and methods from tested base classes are inherited by this new class. The level of
inheritance can be controlled using access modifiers i.e. public, private and protected
keywords. So now, you only need to test the new code that was added to the derived
class.

Polymorphism
Polymorphism is another major feature of object-oriented programming. New objects that
perform the same functions as the base object and also perform with one or more of these
functions in a different way can be created by using polymorphism. Take a close look at
the following figure Fig. 5. Here, you may have a shape class, derived into three different
functionality with the same method draw()
• One draws a circle on the screen.
• One draws triangle on the screen.
• Another draws square on the screen.

© SQL Star International Ltd. 2009


6
OOP Core Concepts

Fig. 5: Polymorphism diagram

All methods have the same name (i.e. draw()) but accomplish the drawing in a different
way.

Try it out

1. How can you differentiate Abstraction from Encapsulation?


2. “Abstraction leads to encapsulation.”
or
“Encapsulation leads to Abstraction.”
Which of the following statement is true?

3. What is the relationship between data hiding and encapsulation?

Implementing Corner stones of OOP


Let us take up a simple case study to consolidate our understanding on various concepts
discussed above related to OOP.
As shown in Fig. 6 below, the class Dog consists of features shared by all dogs, such as
breed and eye color (properties) etc, and the ability to bark and sit (behaviors or methods)
etc. The Rayne object is an instance of the Dog class. We are going to use this case to
implement the concept of “Class”,“Object” and “Method”.

© SQL Star International Ltd. 2009 7


OOP Core Concepts

Fig. 6: The Dog class

Class
The abstract characteristics of something (object), including its characteristics (its
attributes, fields or properties) and its behaviors (the actions it can perform, or methods,
operations or features) are defined by a ‘Class’. Modularity and structure in an object-
oriented computer program is provided by use of classes. You can identify a class if you
are familiar with the problem domain (characteristics of the class should make sense in the
given context.) Note that, code for a class should be self-contained (using encapsulation).
Properties and methods, defined by a class are collectively called members of that class.
Object
They are basic run-time entities in an object-oriented system. It is a particular instance of
a class. The class of Dog defines all possible dogs by listing the characteristics and
behaviors they can have; the object “Rayne” is one particular dog, with particular
versions of the characteristics. A Dog has fur; Rayne has brown-and-white fur. State
defines the set of values of attributes of a particular object. An object consists of state and
behavior that is defined in its class.
Method
It is an object's ability to perform some task. Rayne, being a Dog, has the ability to bark.
So bark() is one of Rayne’s methods. She may have other methods as well, for example
sit() or shake() or come(). Within the program, using a method usually affects only one
particular object; all Dogs can bark, but you need only one particular dog to do the
barking.

© SQL Star International Ltd. 2009


8
OOP Core Concepts

Fig. 7: Methods within the Dog class

Inheritance
As you have probably observed, the more specialized versions of a class is called
‘subclasses’. ‘Subclasses’ inherit attributes and behaviors from their parent classes. They
are also capable of having their own attributes and behaviors.
For example, the class Dog might have sub-classes called Bulldog, French Spaniel, and
GoldenRetriever(different dog breeds). In this case, Rayne would be an instance of the
GoldenRetriever subclass. Suppose the Dog class defines a method called bark() and a
property called Color. Each of its sub-classes (Bulldog, French Spaniel, and
GoldenRetriever) will inherit these members, meaning that the programmer only needs to
write the code for them once.

Each subclass can alter its inherited features. For example, the GoldenRetriever class
might specify that the default Color for a GoldenRetriever is possibly reddish. The French
Spaniel subclass might specify that the bark() method produces a high pitch by default.
Subclasses can also add new members. The French Spaniel subclass could add a method
called tremble(). So an individual French spaniel instance would use a high-pitched bark()
from the French Spaniel subclass, which in turn inherited the usual bark() from Dog. The
French spaniel object would also have the tremble() method, but “Panther” would not,
because he is a “Bulldog”, not a French Spaniel. In fact, inheritance is an ‘is-a’
relationship: “Panther” is a “Bulldog”. A “Bulldog” is a “Dog”. Thus, Panther inherits the
methods of both Bulldog and Dog.

© SQL Star International Ltd. 2009 9


OOP Core Concepts

Encapsulation
Encapsulation conceals the functional details of a class from other objects that send
messages to it. In a strict object-oriented design, an object's data is always private to the
object. Other parts of a program should never have direct access to that data. With
encapsulation, you can control access to data, forcing programs to retrieve or modify data
only through an interface provided by that object.
For example, the Dog class has a bark() method. The code for the bark() method defines
exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and
volume). You, the Panther's master, however, do not need to know exactly how he barks.
Encapsulation is achieved by specifying which classes may use the members of an object.
The result is that each object exposes to any class a certain interface — those members
accessible to that class. Members are often specified as public, protected or private,
determining whether they are available to all classes, sub-classes or only the defining
class(See: Table below).
A well-established use of encapsulation in software design and development is the
separation of an interface from an implementation. Interface is the visible external aspect
of the software that must be understood to manipulate the software.

Abstraction
What is abstraction? Abstraction talks about simplifying complex reality by modeling
classes appropriate to the problem. Appropriation also includes working at the most
appropriate level of inheritance for a given aspect of the problem.

For example, Panther the Dog may be treated as a Dog much of the time, a Bulldog when
necessary to access Bulldog-specific attributes or behaviors, and as an Animal (the parent
class of Dog) when counting Animals in the city.

You can achieve abstraction through Composition. Consider the example of the Car.
Objects like an Engine, a Gearbox, a Steering wheel and other components are used to
build a class Car. Now, you do not need to know how do the different components work
internally. To make a Car class you only need to know how to interface with them. Here
interface provides the way to send and receive messages to and from them, or make
different objects composing the class interact with each other.

Polymorphism

You are allowed by polymorphism to treat derived class members just like the members of
their parent classes. In object-oriented programming, polymorphism is known as the
ability of objects (belonging to different data types) to respond to method calls of the
same name, each one according to an appropriate type-specific behavior. You can
abstractly apply a method or an operator like +, -, or * in many different situations. For
instance, a dog may elicit a bark() if it is commanded to speak(). A pig, if it is commanded
to speak() might elicit an oink(). Both of them inherit speak() from Animal. However, their
derived class methods override the methods of the parent class. This is Overriding
Polymorphism.

The use of one method signature, or one operator such as ‘+’, to perform several different
functions depending on the implementation is called Overloading Polymorphism. You might

© SQL Star International Ltd. 2009


10
OOP Core Concepts

use ‘+’ operator to perform integer addition, float addition, list concatenation, or string
concatenation. Then any two subclasses of number, such as integer and double, are
expected to be added together properly in an Object Oriented Programming language. The
concatenation operator, ‘+’, should be overloaded by the language so that it can work in
this way. Code readability is improved in this way. Most OOP languages support at least
some level of overloading polymorphism, though their implementation varies from
language to language. Parametric Polymorphism is supported by many Object Oriented
Programming Languages. Here the code can be used transparently with any number of
new types since it is written without the mention of any specific type. Can you think of any
example? Pointers are examples of simple polymorphic routines, which can be used with
many different types of objects.

Some OOP Terminologies


Terms Brief description
Object A software development model that uses abstraction with objects. This
orientation model also uses encapsulated classes, communication via messages,
object lifetime, class hierarchies, and polymorphism.
abstraction Representation of a complex real-world situation, in a simplified model is
possible through the abstraction mechanism.
encapsulation Hiding of all the internal details of object from the outside world is
known as encapsulation. Encapsulation is achieved by putting definitions
or attributes and methods within a class definition.
Inheritance Mechanism allowing one class (subclass) to share the attributes and
behaviors of another class (superclass). Can call it as is-a relationship
between classes. The attributes and behaviors of the superclass are
inherited by the derived class. This usually extends or modifies those
attributes and behaviors.
Polymorphism A characteristic of inheritance by which the required behavior of
subclasses is ensured.
attribute Holds state information of an object. A class definition describes the
attributes and operations (methods) of a class irrespective of whether
the attribute is a simple ON/OFF boolean variable, or a complex
structure like an object.
behavior Activity of an object that is visible to the outside world. It includes an
object’s response to message. This is done by changing its internal or
returning state information to other objects.
method It is an operation or service that is performed upon an object, defined as
part of the declaration of a class, and used to implement object
behavior. Member function, operation, and service are synonymous to
method.
state It reflects current values of all the attributes of a given object.
constructor A special method that is executed automatically whenever an object of
the class is created. Due to this fact, it is generally used for performing
initialization. Note that, for complex objects this method can be a
significant activity, which can invoke the constructors of other objects as
well.
instance This is a specific object. It is an instantiation of a class, has a unique

© SQL Star International Ltd. 2009 11


OOP Core Concepts

identity, specific attributes and behaviors. Note that instance and object
are often used interchangeably.
instantiation Instantiating a class creates a new instance / object of that class.
reference All objects in Java are accessed by reference, as it is a data element
whose value is an address. Note that any object variable will not be the
object itself, but is actually a reference to such an object.
subclass A subclass is derived from and is a specialization of the generalized
superclass. It is derived from an associated superclass in an inheritance
hierarchy.
superclass A superclass (parent class or base class are the other names for this) is
a more generalized class in an inheritance hierarchy. A subclass will be
derived from a superclass.
single Subclass contains single inheritance at the time. It is derived from a
inheritance single superclass.
multiple Java allows multiple-inheritance only through interfaces i.e. A subclass
inheritance that is derived from a superclass can implement an interface
class Also known as static attributes, class attributes of a class are shared by
attribute all instances of the class. Only one copy will exists for each class
attribute in the class and they will be accessible without creation of any
instance of the class.
class method Known also as static method, this method can operate only on class
attributes and is defined in the class. Can be used without the creation of
any instance of the class.
instance Attribute of a class, which is associated with a particular instance of the
attribute class. Each instance has their own copies of instance attributes.
instance The most common type of method defined by a class and operating on
method instance attributes. Note that this method is used only with its
associated instance of the class.

Visibility of Members
The ability of one class to see and use the resources of another class is known as visibility
of members. Various programming language features like Java's public, protected, and
private access specifiers control visibility.

Public As the name suggests, any other class can access the public items of a
Visibility class. Because their attributes and operations are visible to the whole
world.
Private As the name suggests, only the members of the given class can view the
Visibility private attributes and operations.
Protected Only the class and its subclasses can view the Protected attributes and
Visibility operations.

Try it out

A Car inherits the property of Vehicle class. If you have written the code for
Vehicle class in which you want it to be accessed only within Car class, then
what specifier is used?

© SQL Star International Ltd. 2009


12
OOP Core Concepts

Summary

In this chapter, we have learned:


• The OOP Core Concepts are Class, Object, Abstraction, Encapsulation, Inheritance
and Polymorphism
• A class is a template for multiple objects with similar features. Common features of
a particular set of objects are embodied by the class.
• Objects have state and behavior. The state of an object is stored in fields (referred
as variables in some other programming languages). Internal state of an object is
manipulated by methods and serves as the primary mechanism for object-to-object
communication.
• Abstraction is a process that reduces the information content of a concept. It is
typically done to retain only the information which is relevant for a particular
purpose. Abstraction has four major attributes: Coherence, Conciseness, Identity
and Completeness.
• Encapsulation is a process by which you can hide data fields and methods inside
the object from rest of the world.
• Inheritance enables you to create a class that is similar to a previously defined
class.
• New objects that perform the same functions as the base object and also perform
with one or more of these functions in a different way can be created by using
polymorphism.
• The cornerstones of OOP have been explained through an example.
• Some of the OOP terminologies include Object orientation, abstraction,
encapsulation, Inheritance etc.
• The ability of one class to see and use the resources of another class is known as
visibility of members. There are three kinds of visibilities. They are- public visibility,
private visibility and protected visibility.

© SQL Star International Ltd. 2009 13


Explaining JavaTM Technology

Chapter 3

Explaining JavaTM Technology


SDLC Process
Understand the features of Java Technology
Major characteristics of Java programming language
Java Technology Product Groups
Java 2 Platform Standard Edition Documentation
Setting up a Java environment
Writing your first java Program
Testing the sample program
Various java tools

© SQL Star International Ltd. 2008


Explaining JavaTM Technology

Objective

After completing this chapter, you will be able to:

• Describe the process of SDLC

• Understand the Java Technology Features

• Understand Java Technology Product Groups

• Access online API Documentation

• Setup a Java Development Environment

• Write your first Java Program

• Gain understanding on various java tools

© SQL Star International Ltd. 2008


2
Explaining JavaTM Technology

Introduction
We have discussed various concepts of Object Oriented Programming Structure. The base
of the OOP is an object. We have talked about classes. Then, we have discussed the four
corner stones of Object Oriented Programming Structure such as Abstraction,
Encapsulation, Inheritance, and Polymorphism. We have studied an example to
understand the features of OOP better. We have looked into some of the OOP
terminologies. In this chapter, we will discuss about stages of a Software development life
cycle. We will learn various features of Java technology. We will then proceed with Java
technology products provided by Sun Microsystems.

SDLC (Software Development Life Cycle) Process


While developing a new product, you need to follow a range of industry-accepted set of
stages. The PLC or product life cycle represents these stages. In total, they are
represented in seven stages:
• In the first stage, identify problems, opportunities and objectives.
• In the second stage, determine the information requirements.
• In the third stage, analyze the system needs.
• In the fourth stage, design the recommended system.
• In the fifth stage, develop and document the software.
• In the sixth stage, do the testing and documentation for the software.
• In the seventh and final stage, implement the system and evaluate it.

Identifying problems, opportunities and objectives


Problems
These are undesirable situations that prevent the organization from completely achieving
its purpose, goals and/or objectives.
Examples: Long delays in customer order processing.
Opportunity
Chance to improve the organization even in the presence of specific problems.
Examples: Cost cutting ideas
Objective
Specifies main motive behind business setups.
Examples: maximizing profits, best quality products etc.
Directive
A requirement imposed by management, government or some external influence.
Example: Reporting requirements at specific time periods.

© SQL Star International Ltd. 2008 3


Explaining JavaTM Technology

Determining Information Requirements


The System related environment (existing one) must be studied carefully. This gives an
opportunity to view the current system in terms of Objectives and Contribution to the
Organization's overall goal.
Answer the following:

• Who will use the system?

• What information system users need to carry out their jobs?

• What activity will be performed?

• Where the system will run (surrounding environment)?

• How frequently the system is needed?

• How different system procedures are performed (information flows/


conversions/ storage)?

Analyzing system needs


• Analysis is the process of investigating a problem that you want to solve
with your product.
• System requirements associated with the new system are determined.
• This phase realizes all the alternative ways to implement the proposed
system (Considering existing constraints) and feasibility associated with other
alternatives.
Following figure (Fig 1) illustrates the Analysis Stage in SDLC:

Fig 1: Analysis Stage

© SQL Star International Ltd. 2008


4
Explaining JavaTM Technology

Answer the following:

• What is the new data requirement from the users? Can any redundant
data or useless data be rejected?

• Exact specifications of system data (numeric/text etc.) in terms of


system's data dictionary.

• What Validation criteria exist to check the input data validity?

• What type of decisions are involved (structure or unstructured) in


system processes (information conversions)?
♦ Exact specifications of structured decision.
♦ Specification of multi-criteria decisions (using trade-offs and weighting
methods).

Designing the recommended system


• This phase specifies details of the new system operations.
• System design specifications will be used by developers to construct the
system accordingly.
• Design specifications cover:
¾ Logical (technology independent)
¾ Physical (technology dependent) aspects of system operation.
Infrastructure Design
• Specification of design strategies concerning:
¾ Man power source (outsourcing or hiring)
¾ Software source (packaged or custom built)
• Specification of hardware, network and database platforms in use.
• Specification of any international design standards relevant with quality,
completeness, usability, performance of the product.
Input (Data Entry) design
• Design of policies, procedures & validation
• Design tests for accurate data entry
Interface Design
• Layout design (field organization, coloring etc.) of input forms or screens for
accurate, easy to use & effective data entry
• Layout design for system output data like reports etc
Database Design
Storage type for system's data:

© SQL Star International Ltd. 2008 5


Explaining JavaTM Technology

• File based (sequential, direct, indexed-sequential)


• DBMS based (hierarchical, networked, relational, object oriented)
• Details of system's database schema
Security Design
Policies (security/backup) to make the data source secure against:
• External exposures (hackers)
• Catastrophic failures (virus attack, physical damage etc.)
Program Design
• Name of program modules required.
• Detail specifications for each program module (program specification
packets):
¾ I/O requirements
¾ Processing details (Program flow chart)
¾ Module interaction details (structure chart)
¾ Library routines (pre-built modules) available
Integration Design
• Details of integrating the new system functionality with the existing
systems.
Following figure (Fig 2) illustrates the Design stage in SDLC:

Fig 2: Design Stage

© SQL Star International Ltd. 2008


6
Explaining JavaTM Technology

Developing and documenting software


• This phase targets a functional system that meets the system design
specifications.
• Phase involves:
¾ Program coding
¾ Selection of a suitable language platform (Visual Basic, Visual C++, Java
etc.)
• Packaged software installation & configuration:
¾ Development of Integration interfaces (With existing systems)
¾ Program demonstrations and user feedback collection.
• Code walkthroughs (explanation sessions) for the programmer teams
• Documentation:
¾ Online user help / Readme files / FAQ for usage and troubleshooting
¾ Programmer's manual for understanding the code working and future
extensions
Following figure (Fig 3) illustrates the Development Stage in SDLC:

Fig 3: Development Stage

Testing & Maintaining the System


This phase includes:
1. System modules will be tested thoroughly for existence of any bug
(Undesirable / erroneous working)
2. A system support (maintenance) plan will be created.
System Testing
• Testing of individual component’s working
• Testing of integrated working of the whole system

© SQL Star International Ltd. 2008 7


Explaining JavaTM Technology

Testing is performed on sample data and then with real time data (extracted from the
existing system).
System maintenance plan includes plans for:
¾ User technical support
¾ Handling unanticipated problems
¾ Technical training
Fixing of system bugs:

• Bugs slipped in the testing phase are fixed at this stage.


Recovering the system:

• System crash may result due to hardware or software failure or human


error.
Following figure (Fig 4) illustrates the Testing Stage in SDLC:

Fig 4: Testing Stage

Implementing and evaluating the system


The phase works for a smooth transition to the new system.
The phase involves planning for:
System Conversion
¾ Direct cutover approach
¾ Parallel conversion approach
¾ Phased conversion approach
User Training
¾ This phase also includes an audit activity (system evaluation) to ensure
the quality of the system.
Following figure (Fig 5) illustrates the Implementing Stage in SDLC:

© SQL Star International Ltd. 2008


8
Explaining JavaTM Technology

Fig 5: Implementing Stage

Understand the features of Java Technology


The Java Programming Language originated in 1991 as part of a research project to
develop a programming language that would bridge the gap between many consumer
devices, like Video cassette recorders (VCRs) and televisions. A team of highly skilled
software developers under the supervision of James Gosling wanted to create a platform
independent programming language enabling consumer devices with different central
processing units (CPUs) to share same software enhancements.
This programming language could not be a great success in the market. Due to this reason
the team was in search of a new path where their programming language could be useful.
During that period, World Wide Web (WWW) was becoming popular and the team
recognized that the language developed by them was perfect for developing Web
multimedia components to enhance the Web pages. Its platform independent feature was
also helpful to write a resource once and access from heterogeneous platform. The team
enhanced the programming language and came up with Java. After that, Java
Programming Language started being used as an Internet Programming Language.

Major characteristics of Java programming language

• Simple

• Robust

• Portable

• Interpreted

• Purely Object Oriented

• Platform-independent

• Multithreaded

• Secure

• Distributed

© SQL Star International Ltd. 2008 9


Explaining JavaTM Technology

• High Performance

• Dynamic

Simple:
The Simplicity of Java is enhanced by its similarities to 'C' and C++. Java has simplified
C++ programming by adding features beyond those found in C++ and by removing some
of the features that make C++ a complicated and difficult language to master.
The Java Programming Language is simple because the designers removed some of the
complex programming constructs found in other popular programming languages like
direct manipulation of memory addresses using Pointers, Operator Overloading, etc.
It consists of only a few primitive data types. It is interpreted. The runtime environment
provides automatic memory allocation.
The Java programming language allows programmers to manipulate objects using object
references.
Java also uses Garbage Collector for automatic memory management, which has following
advantages:

• No Dangling Pointers

• No Memory Leaks
No use of Header Files unlike C and C++.
The language is small, so it is easy to become fluent in. The language is interpreted so the
compile-run-link cycle is much shorter. The runtime environment provides automatic
memory allocation and so there is less for the programmer to think about.

Robust:
Designers of Java anticipated it to be used to solve some very complex programming
problems. Writing a program that can run on a variety of operating systems with a variety
of processors is not a simple task. To do it successfully, you need all the help that your
programming language can offer. With this in mind, data type issues and problems are
resolved at compile time.
Memory management has been simplified in Java in two ways. Firstly, Java does not
support direct pointer manipulation or arithmetic. This makes it impossible for a Java
program to overwrite memory or corrupt data. Secondly, Java uses runtime garbage
collection instead of explicit freeing of memory.
The Java Programming Language is a Robust Language. Robust means all the data type
issues and problems are handled and resolved at compile-time. This reduces possibilities
of runtime errors. Also assignment issues are taken care of at runtime,.
Memory management has been simplified in terms of:
y No support for direct pointer manipulation
y Provided with runtime automatic garbage collection for implicitly freeing memory.
y

© SQL Star International Ltd. 2008


10
Explaining JavaTM Technology

Portable:
In addition to being architecture-neutral, Java code is also portable. It was an important
design goal of Java that it be portable so that as new architectures (due to hardware,
operating system, or both) are developed, the Java environment could be ported to them.
In Java, all primitive types (integer, long, float, double, and so on) are of defined sizes,
regardless of the machine or operating system on which the program is run. This is in
direct contrast to languages like C and C++ that leave the sizes of primitive types up to
the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.
Following figure, (Fig 6) shows the Java runtime environment portable features:

Fig 6: Java Runtime Environment

Interpreted:
Because Java is interpreted, once the Java interpreter has been ported to a specific
machine, that machine can instantly run Java applications. As an example of the
usefulness of this, imagine a hypothetical chip manufacturer, etc. that has just finished its
newest CPU chip. This new chip named the Zintium, serves as the foundation of a new line
of computers. Once Etnal ports the java interpreter to work on the Zintium, the new
machine will be able to run all of the Java development utilities – the compiler, the

© SQL Star International Ltd. 2008 11


Explaining JavaTM Technology

debugger, and so on. Contrast this with a traditional language. If Etnal wants to release a
C++ compiler with its new computer it must port, or create from scratch, the compiler, the
debugger, the runtime library, and so on. Another advantage is that the time-consuming
edit-compile-link-test cycle is broken. Without the compile and link steps, working in an
interpreted environment is a much simpler edit-test cycle. Without having to wait for
lengthy compiles and links, Java promotes prototyping and easier debugging.
Moreover, each and every system will be having the Java Virtual Machine, which will be
working like interpreter. The job of the Java Interpreter is to convert the Java Bytecode to
its corresponding platform specific code and execute it to provide the output. The Java
Virtual Machine is also responsible for implementing security using ClassLoader and
SecurityManager classes.

Purely Object Oriented:


In its approach to Object-orientation, Java follows more closely along the lines of
languages such as SmallTalk than C++. Except for its primitive data types, everything in
Java is an object.
Java is a Pure Object Oriented programming language, because any code you write within
a Java program has to be written within a class. Other than this, the main goal of the Java
Programmer is to create objects, pieces of autonomous code that can interact with other
objects to solve a problem. This feature makes the Java Programming Language loosely
coupled.
Procedural programming stresses the sequence of coding steps required to solve a
problem, while OOP stresses on creation of objects and interaction between them.
Following figure (Fig 7) illustrates OOP’s focus on Object and object orientation.

Fig 7. Object-Oriented

Platform Independent:
Programs written in C and C++ create object codes on compilation. The object code keeps
information about the platform in which it is compiled. So object code created in one
platform cannot be executed in another platform; it can be executed only in the platform
where it is created.
Programs written in Java Programming Language, when compiled get converted to a
Bytecode format that can be accessed from any platform that has Java Virtual Machine
(JVM). In order to execute the Bytecode the platform needs a Java Virtual Machine to be

© SQL Star International Ltd. 2008


12
Explaining JavaTM Technology

installed which will interpret the Bytecode to its corresponding platform dependent code.
As the Bytecode depends on JVM and not on the platform, it makes Java Language
platform independent.

Multithreaded:
What is multithreaded programming? It is the practice of executing software in a fashion
that enables two or more activities to be performed in parallel within the same application.
This is accomplished by having each activity execute in its own thread.
Threads are separate tasks running within a program and they share memory space and
resources with each other.
For example, if effectively used, they can prevent the user interface from being tied up
while the program is performing a lengthy operation because both these activities will be
running in separate threads.
Writing a computer program that only does a single thing at a time is an artificial
constraint that we have lived with in most programming languages. With Java, we no
longer have to live with this limitation. Support for multiple, synchronized threads is built
directly into the Java language and runtime environment.
Synchronized threads are extremely useful in creating distributed, network-aware
applications. Such an application may be communicating with a remote server in one
thread while interacting with a user in a different thread.
The Java Programming Language supports multithreaded programming i.e. performing
several tasks at a time, such as querying a database on one hand while displaying a user
interface on the other hand. Multithreading allows Java technology program to be very
efficient in its use of system resources. Within a single program of Java we can perform
multiple tasks at a single point of time.
Multithreading is:

• Executing software so that two or more activities can be performed in


parallel within the same application.

• Accomplished by having each activity perform in its own thread.


Threads are separate tasks running within a program.
Following figure (Fig 8) illustrates the Multithreaded features in Java program:

© SQL Star International Ltd. 2008 13


Explaining JavaTM Technology

Fig 8: Multithreaded Features in Java

Secure:
Closely related to Java's robustness is its focus on security. As Java, does not use pointers
to directly reference memory locations, as seen in C and C++, Java has a great deal of
control over the code that exists within the Java environment.
It was anticipated that Java applications would run on the Internet and that they could
dynamically incorporate or execute code found at remote locations on the Internet.
Because of this, the developers of Java hypothesized the existence of a hostile Java
compiler that would generate Java byte code with the intent of bypassing Java's runtime
security. This led to the concept of a byte-code verifier. The byte-code verifier examines
all incoming code to ensure that the code plays by the rules and is safe to execute. In
addition to other properties, the byte code verifier ensures the following:

• No pointers are forged

• No illegal object casts are performed.

• All parameters passed to functions are of the proper types.

• Rules regarding private, protected, and public class membership are


followed.
Java Technology programs are secure because the Java programming language, with the
environment in which Java Technology programs run, uses security measures (using
ClassLoader and SecurityManager classes) to protect programs from attacks.
If a Java application is to be able to dynamically download code from a non-trusted source
on the Internet and run it alongside applications that might contain confidential
information, protection has to extend very deep. The Java security model wraps three
layers of protection around imported classes, as shown in figure given below:

© SQL Star International Ltd. 2008


14
Explaining JavaTM Technology

Following figure (Fig 9) illustrates Security features in Java program:

Fig 9: The Java Security Model

Distributed:
Java Programming Language supports Distributed Computing or Distributed Network
Technologies using Remote Method Invocation (RMI), Common Object Request Broker
Architecture (CORBA), and Universal Resource Locator (URL). The application designed
and developed through the said technologies can be distributed among multiple Remote

systems and work as a single unit for the end users.


Following figure (Fig 10) illustrates the Distributed model in Java program:
Fig 10: The Java Distributed Model

High Performance:
For all but the simplest or most infrequently used applications, performance is always a
consideration. It is no surprise, then, to discover that achieving high performance was one
of the initial design goals of the Java developers. A Java application will not achieve the
performance of a fully compiled language such as C or C++. However, for most
applications, including graphics-intensive ones commonly found on the World Wide Web,
the performance of Java is more than adequate. For some applications, there may be no
visible difference in performance between C++ and Java.
Many Java Developers have discovered that, although a C program will outperform a Java
program in many cases, the additional development time and effort do not justify the
minimal performance gains. Of course, because we are not all programming in assembly

© SQL Star International Ltd. 2008 15


Explaining JavaTM Technology

language, there must be some amount of performance we are willing to trade for faster
development.

Dynamic:
Because it is interpreted, Java is an extremely dynamic language. At runtime, the Java
environment can extend itself by linking classes that may be located on remote servers on
a network (for example, the Internet). This is tremendous advantage over a language like
C++ that links classes prior to runtime.
In C++, every time member variables or functions are added to a class, it is necessary to
recompile that class and then all additional code that references that class. Of course, the
problem is intensified by the fact that you need to remember to recompile the files that
reference the changed class.
Java addresses this problem by deferring it to runtime. At runtime, the Java interpreter
performs name resolution while linking in the necessary classes. The Java interpreter is
also responsible for determining the placement of objects in memory. These are the two
features of definition of a class used by other classes. Because name lookup and resolution
are performed only the first time a name is encountered, only minimal performance
overhead is added.
At runtime, the Java environment can extend itself by linking classes that may be located
on remote servers on a network.

Try it out

1. What is the difference between platform independence and Architecture-


neutral characteristics in Java?

2. What is portability?

Java Technology Product Groups


Sun Microsystems provides a complete line of Java technology products ranging from kits
that create Java Technology programs to emulation (testing) environments for consumer
devices, such as cellular phones.
Java Technology is having three different groups of products, which are as follows:

JavaTM 2 Platform, Standard Edition (J2SETM) – J2SE supports development


of applets and applications that run within Web browsers and on desktop computers,
respectively. For example, you can use the J2SE software Developer's Kit (SDK) to create
a word processing program, create a chat server, and create any stand-alone application
having all the GUI features for your personal computer.

JavaTM Platform, Enterprise Edition (J2EETM) – J2EE supports development


of large enterprise level, server side and client-side distributed applications. For examples,
you can use the J2EE SDK to create a web shopping (eCommerce) application for a retail
company's web site.

JavaTM Platform, Micro Edition (J2METM) – J2ME supports development of


applications that can run on resource-constrained consumer devices. For example, you can

© SQL Star International Ltd. 2008


16
Explaining JavaTM Technology

use the J2ME SDK to create a game that runs on a cellular phone.

The following figure Fig 11 identifies the Java Technology Product groups:

Fig 11: The Java Technology Product Groups:

Java 2 Platform Standard Edition Documentation


What are contents of the on-line Java 2 Platform Standard Edition Documentation? API
specifications, feature descriptions, developer guides, reference pages for JDK tools and
utilities, demos, and links to related information are contained in this documentation. This
documentation is available in a download bundle that can be installed on your machine.
Go to http://java.sun.com/javase/downloads/ to download the latest bundle.
Go to

http://java.sun.com/javase/
6/docs/api/ to access the documentation online.

Note that while accessing the documentation, you will be provided access to many
different Java documentation pages. Find the link under "API & Language Documentation"
called Java 2 Platform API Specification. Once you click on it you will be landed on the first
page, which will look like:

© SQL Star International Ltd. 2008 17


Explaining JavaTM Technology

Fig 12: Java 6 API Documentation

Setting up a Java Environment


Programs can be written and run on various types of operating systems (Windows, UNIX,
Linux etc) with the help of the Java programming language. The only criterion is that a
Java runtime environment needs to be installed.

From where can you download?


The version of Java you require can be downloaded from the website of SUN
Microsystems(http://java.sun.com/javase/downloads/). Download the JAVA Software
Developer’s Kit (SDK) if you want to write, compile and run your own Java programs. You
need to download only the Java Runtime Environment (JRE) if you need to run an already
compiled Java program. One thing to note is that, you should download the one, which is
most suitable for your OS.

Setting up Java
How to set up Java? You will find a host of instructions along with the download installer.
Follow these to install Java (SDK). In windows, the default installation directory of Java
Software is located at "C:\Program Files\Java\jdk1.6.0\” which is often referred as Java
Home(i.e the environment variable JAVA_HOME).
Now, by running the already installed Java executable, you will be able to run the Java
program. It is convenient to add the location of this file to the path variable of the
operating system. If you do not do this, you will need to refer to the absolute location of
Java explicitly.

Setting up JAVA_HOME
• If you are using the Windows 2000/XP, you can set JAVA_HOME easily, as
follows: Right-click ‘My Computer’ icon on your desktop, select
‘Properties’, Click the ‘Advanced’ tab, Click the button ‘Environment

© SQL Star International Ltd. 2008


18
Explaining JavaTM Technology

variables'. Refer to ‘System Variables’ area. Click on ‘New’ button. Specify ‘Variable
Name’ as ‘JAVA_HOME’ and its value as path to the folder where you have installed
JDK.

Setting up the path


• If you are using the Windows 2000/XP, you can set path easily, as follows:
Right-click ‘My Computer’ icon on your desktop, select ‘Properties’, Click the
‘Advanced’ tab, Click the button ‘Environment variables'. Refer to ‘System
Variables’ area. Locate ‘Path’ variable from the list and click on it. Now click on
‘Edit’ button. You will see the current value of path variable e.g.
C:\WINDOWS\SYSTEM32. You need to alter this value so that the path to the Java
executable is also contained in it. Consider the case when you install Java in
JAVA_HOME and your path is currently set to C:\WINDOWS\SYSTEM32. You will
need to change the path to read C:\WINDOWS\SYSTEM32;<JAVA_HOME>\bin after
this. These changes will be reflected when a new command prompt is opened and
you will also be allowed to run java programs by typing "java". Note that you will
also be able to run the "javac" to compile stuff if SDK has been installed by you.
• If you are using Windows 95/98/ME, you might find that your path variable is
stored in a different place. First, you need to edit the c:\autoexec.bat file. Then add
SET PATH=%PATH%; <JAVA_HOME>\bin at the end.
• If you are using Linux, UNIX, Solaris, FreeBSD, you need to set their PATH
variable in order to point to the location where Java binaries have been installed
(by default java will be available at /usr/lib/java/jdk_1.6.0 folder). If you face any
trouble while doing this, you can refer to your shell documentation. Consider the
following example. Suppose you want to use bash as your shell. In order to do this,
add export PATH=<JAVA_HOME>:$PATH to the end of your .bashrc.

Setting up the classpath


After setting up the path, Java needs to be told where the compiled classes can be found
at runtime. To include at least the current working directory (.), you will need to set the
following classpath:
Eg: SET CLASSPATH=%CLASSPATH%;.
Other directories that might contain compiled class files may also be contained in the
classpath. If you use classes that are contained inside a .jar file, the full path and name of
this file in the classpath (i.e. not just the name of the directory it is contained within)
needs to be specified.
Now you are ready with your java environment.

Writing your first java Program


Let us study a sample program to begin with. When executed, this program will display a
message "Hello World!" on the system output device (the computer console):
/**
* This class defines a program that displays a message on the console.
* Author :: SQL Star.*/

© SQL Star International Ltd. 2008 19


Explaining JavaTM Technology

public class App {


//main method
public static void main(String[] args) {
//Display message
System.out.println("Hello World!");
}
}

Try it out

Write a simple Java program to display a message “ Good Morning”. Take the help of
the statements shown in the above program.

Testing the sample program


How do you test this sample program? It is better to have a folder where you can store
your programs e.g. C:\test. You need to create such folder in C drive. Open any text editor
(e.g. EditPlus, Notepad, etc.) and a Command Prompt window. Now follow these steps:
1. First, you need to write the source code as shown above. So type the code shown
earlier in your text editor.
2. Now save this source file. Save it in the C:\test folder as "App.java". Note that the
.java filename must be same as the class name including capitalization.
3. In the Command Prompt window, change directory to your test folder.
4. Use the javac App.java command in the Command Prompt window to compile the
"App.java" source file.
javac App.java
5. As a result of compilation, a .class file is created from the .java file e.g. in this case,
it will be ‘App.class’
6. Enter the java App command in the Command Prompt to run the "App.class"
bytecode file.
java App

Program analysis:
Let us analyze this sample program line by line.
Studying this sample program line-by-line will get you started you on the path to learn
Java. Sections that follow after this, will help you analyze the sample program. For now, it
is not important that you understand everything completely. Through constant usage, you
will eventually know what it all means.
Comments in Java
• Comments in Java are used only for the purpose of documentation and are ignored
by the compiler at the time of bytecode generation.
• The following three comments techniques are supported:

© SQL Star International Ltd. 2008


20
Explaining JavaTM Technology

1. Javadoc comment: Everything between /** and */ is treated as a javadoc


comment.
2. Single-line comment: Begin with // and continues till end of the line.
3. Multi-line comment: Everything between /* and */ is treated as a comment.
• If a program is documented properly, it can help other programmers to understand
what each section of the code is doing.
• Comments make programs easier to maintain. Good programmers document well
enough that a person not familiar with the program can read the comments to
know what each section of code is doing.
The program's class
• You must define every Java program as a class. Consider the statement
public class App
This a class header, which declares that a class named App is to be defined and that it
is to be publicly available for access from other places. Note that, you always need to
make the class public so that the program’s class can be found and used by the JVM.

• Note that public and class have special meaning and they are Java
keywords. The programmer can decide the class name while staying within
the restrictions of rules defined for Java identifiers.

• The name of the class has to be the same as the name of the source file.
The class, if named App, must reside within a file named App.java
Statement blocks

• These are modules of code that consist of one or more statements.

• Statement blocks begin and end with opening and closing braces - "{" and
"}"

• One statement block can be nested entirely within another statement block.
In the sample program the block for the main method is nested within the
block for the App class.
The main method

• Except applets, this is a required method in all other Java programs.

• When the Java Virtual Machine starts processing the class, it searches for
this method and executes it.

• The application processing in a small program is defined by this method. For


larger programs, this method is the highest-level module and other methods
are called by it to perform detailed processing.

• This method should have a method header coded like the following:
public static void main(String[] args)

© SQL Star International Ltd. 2008 21


Explaining JavaTM Technology

This states a few things:


1. The method has public access.
2. It is a class (static) method that is not to be associated with any objects of the class.
3. It does not return a value to the caller (void).
4. It has the name main, and
5. It receives an array of String references (String[]) named args as parameters.
Note that, while coding this header, your only flexibility exists in naming the array. Your
sample program will run just as fine if the method is re-coded as public static void
main(String[] x).

Try it out

State whether True or False:


“// “ can be used for multiline comments.

Writing to the system output device (the console):


• When it is open, the system output device might be referenced by the identifier
System.out. Here out is a public reference to a PrintStream that is defined
within the System class.

• println is a public method of PrintStream object that accepts a parameter of type


String and copies it to the output device. The String is coded as a String literal
enclosed within quotation marks in the sample program.

Compiler requirements:
• A semicolon ";" suggests end of every Java statement.

• The "white space" characters –i.e. spaces, tabs, and the use of the return key etc
are ignored by the compiler. The "white space" is, however, used liberally
sometimes so that it becomes easier to write, read and maintain the code.

Do Not write code like this:

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


System.out.println("Hello World!");}}
Even though it compiles and runs just fine. Try it and see!

Various java tools


Tools offered by the Java Software Development Kit are used to create and build
applications. The tools are as follows:

© SQL Star International Ltd. 2008


22
Explaining JavaTM Technology

Tool Name Brief Description

javac The javac is the compiler for Java programming language.

For Java applications, the launcher is java. A single launcher is used in


java
this release for both development and deployment.

javadoc javadoc, as the name suggests, is the API documentation generator.

You can use the appletviewer to run and debug applets without a web
appletviewer
browser.

jar jar lets you manage the Java Archive (JAR) files.

jdb jdb is the Java Debugger.

javah is the C header and stub generator and is used to write native
javah
methods.

javap javap is the class file disassembler.

extcheck extcheck is the utility to detect Jar conflicts.

rmic Generate stubs and skeletons for remote objects.

rmiregistry Remote object registry service.

keytool Manage keystores and certificates.

jarsigner Generate and verify JAR signatures.

policytool GUI tool for managing policy files.

© SQL Star International Ltd. 2008 23


Explaining JavaTM Technology

Summary

In this chapter, we have learned:


• The various stages in PLC are: Analysis, Design, Development, Testing
and Implementation.

• Major characteristics of Java Programming Language are: Simple, Robust,


Portable, Interpreted, Purely Object Oriented, Platform-independent, Multithreaded,
Secure, Distributed, High Performance and Dynamic.
• The three main product groups of Java Technology Product Groups are J2SE,
J2EE and J2ME.
• The way to set path and classpath of JDK in different environment.
• Compiling and running your first Java Program Application.
• Various tools like javac, java, jar etc

© SQL Star International Ltd. 2008


24
Explaining JavaTM Technology

Exercise

1. ___ is the process of investigating a problem that you want to solve with your
product.
2. Design specifications cover ___ and ____ aspects of the system operation.
3. Layout designs like reports for system output data is called ___ design.
4. The phase that targets a functional system, which meets the system design
specifications with program coding is called ____ .
5. Testing of individual components working and integrated working of the whole
system is called ____ testing.
6. The Java Programming Language originated in the year ___ as part of a research
project to develop a programming language, that would bridge the gap between
many consumer devices, like Video cassette recorders (VCRs) and televisions.
7. Java is portable because the ____ itself is written in Java.
8. ____ group of Java supports development of applets and applications that run
within Web browsers and on desktop computers, respectively.

True/False

1. In Java, all primitive types (integer, long, float, double, and so on) are of
undefined sizes, regardless of the machine or operating system on which the
program is run.
2. Implementing software so that two or more activities can be performed in
parallel within the same application is called Distributing.

© SQL Star International Ltd. 2008 25

Você também pode gostar