Wednesday, September 24, 2008

Employment to Physically handicaps

One of the MNC company(Tetra Soft Pvt. Ltd.,) in Hyderabad is offering an employment for Physical Handicaps on the event of their annual day.



Eligibility: Any graduation-Passed out in 2007-2008.





If you know any buddy, Please convey them and send the resume yugandhar_poola@rediffmail.com or shazari@capgemini.com by 24/09/08.



Lets us help them to get in to IT industry.





Regards,

Yugandhar Poola

GID 54324|HCU Mainframe|Bangalore, India

Mobile: 91-9886660485

Satyam Computer Services

Wednesday, September 17, 2008

mc database

B. Mobile Databases
The conventional database model is changing fast [1][3].
Mobile devices are now capable of complex processing tasks
and have significant storage capability. As a result a new
approach of storing databases on every single machine, part of
a network is gaining significance. The concept of one central
autonomous database is thus fading fast, with the new notion of
local databases at each machine gaining prominence. Mobile
Hosts can now become machines for data processing and native
storage. Thus the physical location of databases is changing.
Frequent disconnection in mobile devices results in two
approaches. The first one believes that a MH will be offline for
only a very short period as it changes regions, while the other
supports the fact that a mobile user may be offline for a long
time and only comes online briefly. This can be a major design
consideration for any application designed for such devices.
The fundamental notion here is that a mobile user must be able
to work with his own local copy of the database even if his or
her connection to the network is broken. It is essential to handle
both cases maintaining user transparency at all times. For
example we may initially have a permanent connection to the
network, however as battery power runs low we can switch to
the other approach where the MH comes online only
intermittently for very brief periods only when needed or more
generally to perform an amalgam of network related tasks
simultaneously. Thus of significant concern is the limited use
of broadcasts or any other connectivity resource in-order to
make optimum use of available battery power.
Identification of a particular MH(the source of the database
under consideration) is also difficult. How does one locate the
MH in question? This is further complicated by the fact that
MHs move all the time, showing up intermittently in various
places, to further complicate things service areas(BH regions)
are not always contiguous [2][5] and may even be overlapping,
figure 2. Moreover a MH may not always move in a straight
line. As soon as an MH enters a new region the new region
manager(BH of the new region) detects a foreign entity and
asks it to identify itself. Upon receiving details the new BH
contacts the home BH or old BH of the MH and asks it whether
or not the mobile entity is what it claims to be(though this is
time consuming it is important from the safety point of view).
After credentials are established the MH may now work in its
new region, moreover the old BH may also transfer any
transactions started by the particular MH to the new BH. It
however may only return results(if the transactions are not
location dependent) to the new BH. One of the approaches is
chosen depending upon context.
Another, more severe problem is how does an MH find out
which BH it has to communicate with. Consider the case shown
in figure 2, when the MH moves it may come into an
overlapped region, how does the MH now decide what BH to
communicate with. This problem may be solved with a flurry of
messages between the concerned BHs and MH. This problem is
generally another major design consideration however it still is
a key aspect of research in this area.
As with all new approaches, significant problems and
complications result in such a system. Apart from conventional
difficulties a mobile database system may suffer from other
problems. Some of them are –
• Failure of sites
• Loss of messages
• Failure of communication links
• Network partition
Moreover the process of executing queries and supporting
concurrent execution of transactions becomes extremely
complex. Further, distributed (mobile) databases may be
categorized as either heterogeneous or homogeneous databases
depending upon the schema type they support. It is not
uncommon to have whole distributed systems designed with
only fixed schema sets, significantly more interesting(and
complex) is designing distributed systems that allow different
schema sets in the underlying databases at different sites on the
network. We tackle several of these issues in the following
sections.
C. Multidatabase System
A multidatabase system [6] is the term used to refer to a
collection of physically separated, but logically integrated
group of databases. That is, it is an approach wherein different
databases are combined together by an application software
layer to give the illusion of one integrated database to the user.
The additional layer is thus completely portable and pluggable
[7]. These different databases, called local databases generally
have different hardware and software implementations. In fact
it is generally economically viable to maintain local database
schema (also the hardware and software) and hence the need to
maintain local autonomy. MDASs are multidatabase systems
capable of large-scale operation over a wireless medium.
D. Transactions and Concurrency
The fundamental notion governing all database activity is a set
of four properties known commonly as the ACID properties
[8]. These properties take a whole new meaning in the
distributed sense. Mobile transactions are completely different
from conventional flat transactions. Mobile transactions must
be defined adequately as they are often unable to follow the
ACID model(sometimes a more complex strategy like a
modeling based on trees is adopted). Properties of transactions
and hosts on the move must be considered at all points giving
due consideration to an excellent recovery approach(generally
detailed logs). In this effect a proper requirement analysis is a
must[1]. The difficulties and security concerns with mobile
transactions must be well understood. Also search costs and
overhead to locate the correct MH is another important
parameter. Transactions thus take a lot longer to complete in
mobile environments, where a transaction may be defined as a
collection of queries geographically distributed, and arranged
so as to obtain location specific results. Thus there is a need to
temporarily deviate from the ACID properties when it comes to
mobile transactions. A general transaction may be of the
following type-
begin_transaction( ) {
if(lock_table_success) {
//statements of the transaction
select * from table_account;

//do some work

transaction_successful = true;
//transaction code ends
}
if (transaction_successful)
commit_work( );
else
rollback_work( );
Concurrency related to transactions demonstrates the fact
that more that one transaction can execute simultaneously such
that none of them is aware of the presence of others. Moreover
the database(s) must remain in a consistent state when these
transactions finish, however temporary inconsistency may be
allowed for a transaction to complete its work. Concurrency of
transactions increases design complexity however, performance
benefit realized as a result is enormous. Mobile and Distributed
systems however represent even higher levels of complexity.
Transactions become long lived and concurrency becomes
harder to achieve. A number of approaches to solve these
problems in massively heterogeneous systems have been
devised. These range from relatively simple locking and graph
based protocols to complex distributed algorithms [8][9].
Transactions take a lot longer to finish in mobile systems; apart
from this communication failures etc. may cause problems
[2][10][11][12]. A detailed approach to handling transactions in
a massively distributed system is discussed in a subsequent
section.
E. Deadlocks
The problem of deadlocks though of important consequence is
generally ignored by centralized systems as such. This is
generally because deadlocks are a rare occurrence in these
systems and the overhead associated with handling deadlocks
can be significant. The situation in the distributed context is
different though. As an analogy consider a peer-to-peer
database system, where each node can generate queries that are
both local and global. A system of simply 200 nodes with 10
queries per node can create a significant number of
transactions. As is obvious competition for resources is
immense and the problem of deadlocks takes center stage.
Theory calls for a formal definition of deadlocks, this section
talks about it. A system is in a deadlock state if there exists a
set of transactions {T0,T1,…..,Tn} such that every transaction in
the set is waiting for another transaction in the set[8]. In a
multiprogramming environment, analogous to the mobile
database model, several processes may compete for a finite
number of resources. Such a situation can lead to a deadlock
where processes or transactions are blocked, waiting
indefinitely for a resource that is held by another blocked
process. Deadlock detection and avoidance forms an important
part of any distributed system. Techniques for deadlock
management are essential to see the efficient working of any
such system. A number of algorithms to handle deadlocks are
available [8][13][14][15], both in the distributed and
centralized sense.
II. System Architecture
We have devised a system that is capable of operation in large
scale distributed(mobile) environments. The approach
considers all aspects of such a system, problems faced by the
various aspects and implementations after rigorous
performance testing. Our main focus was to design a system
capable of extending commercially available centralized
databases to operate safely under the rigors imposed by largescale
distribution. We have opted for the mobile database
model where in each node or machine has its own local copy of
a database. Databases present may even have different schema.
Each node is capable of submitting queries or transactions to
any other node currently registered. The approach is fully
distributed with only an initial registration with a MainServer
needed. For this purpose any host may act as a server after
being chosen by a simple election algorithm (when the system
is started initially). We have thus eliminated the need for
central transaction managers, resource managers, etc, which
(we feel) only act as centralized bottlenecks when such a large
system is to be considered. All nodes have their own
concurrency control and log maintenance for effective
restoration from failure. A fully distributed approach is thus
maintained. A host after initial registration with the acting
server is capable of complete autonomous operation. It simply
needs to import a list of current hosts which can be easily done
with the button. It is then possible to address and
communicate (work with the database of) any host currently on
the network. Even the central MainServer is expendable and is
only implemented as we need some mechanism to have node
details. In this effect a simple distribution list may be cycled
through the network to provide the hosts with necessary
information. We have however opted for the server based
approach. The architecture of this system is shown below in
figure 3.
The presented model is in fact similar to a multidatabase
system[6], like most multidatabase systems, local autonomy is
maintained even after joining the global system with the
fundamental difference lying in the fact that our approach is
fully distributed and there is no global layer to control the
systems’ working.
File Handler
Stable Storage
Transaction Processing System
User Interface
System Manager
Connections Manager
Run-Time Storage
Log Files
Local
Database
and
Database
Software
Transaction and Query
Manager (local)
Transaction Coordinator
Concurrency Manager
Lock Manager
Deadlock Handler
Recovery Manager
Transaction
Submitter
Update Manager
Figure 3. System Structure
Complete local autonomy also brings with it a surcharge, the
fact that a global transaction may starve if a local user does not
give it time to run. The user may do this inadvertently as most
user based transactions are long lived. For this purpose a
option is provided and the user is encouraged to
commit her work periodically thus creating what amounts to
sagas, where the user’s work is committed and global
transactions are given a chance to spawn from that point. Longlived
global transactions may also have explicit commit points
to provide effective scheduling of transactions.
A. Local Database and stable storage
The proposed model is built upon the bottom up strategy, i.e.
databases are already present and are not modified in anyway to
join the system. This approach is necessary as most
organizations and people already have data base management
systems of their choice installed and configured. These
databases are stored on disk and more often than not have
different schema, policies and data structures, usually
signifying the many different commercially available databases.
Log files [8] are maintained for all operations to effectively
resume operation after a failure has occurred. It is assumed that
all writes to disk are persistent and survive failures. Every node
upon initial startup checks whether this is the first time on the
network, if not the recovery manager routine is called taking a
due look at previous transactions and system shutdown. A
typical log file has the following contents.
!#LOG_FILE$4522#!
!#INFILE$172.16.4.3$1111transactionList.txt#!
!#COMMIT_POINTS$5#!
!#COMMIT_1$done#!
!#COMMIT_2$done#!
!#COMMIT_3$done#!
!#COMMIT_4$done#!
!#COMMIT_5$fail#!
!#LOG_FILE$END#!
The above log file is for transaction id 4522 at this node. The
second line shows the name of the file in which the transaction
list is stored, this is made to match the submitter id and the
transaction id at that node. This approach gives us an efficient
name scheme and a method to submit back transaction results
to the corresponding nodes along with support for transaction
status queries. The transactions branch into sub transactions at
commit points and the status of each sub transaction is stored.
This gives a means to speed up recovery. For example in the
above case the transaction manager is called by the recovery
manager and it is able to go to the last(5th ) part of the particular
transaction straight away. Moreover a master(summary) log file
is also maintained to speed up the recovery process and only go
into details of the necessary transactions(for example, the ones
that were not completed).
!#LOG_FILE$MASTER#!
!#
<4522>$<172.16.4.3>$<172.16.5.34>
~~STATUS~~
fail
#!
!#
<4523>$<172.16.5.34>$<172.16.5.34>
~~STATUS~~
done
#!
!#LOG_FILE$END#!
The above master file shows two transactions, the first is a
global submitted transaction, the second is a local
transaction(note the two ids are the same). The first transaction
has not completed. The recovery manager calls the
corresponding file(the one shown previously), here the control
is transferred to the transaction manager sending it straight to
the last(5th )part of transaction 4522. Thus an efficient
mechanism for keeping the transactions and their sub
transactions running has been put in place.
B. Network Connections
LAN(including wireless) communication hardware typically
offers non reliable multicasts and unicasts. Other problems
arise due to packet loss or packet overtaking inside switches
and network cards. The presented model is implemented
completely with UDP and supports timeouts and
retransmissions as and when necessary. Unique threads are
created for each communication session and each host to create
a safe and efficient network environment. Threads are further
grouped into Thread Pools to logically integrate and simplify
thread monitoring and to provide the best possible performance.
UDP was chosen simply because it entails the least overhead.
Since wireless communication is susceptible to
eavesdropping (as radio signals can move through walls)
security is given prime concern. All communication is
encrypted with a unique key hard coded into the
application(this of course can be changed to add key based
security features).
C. User Interface
The GUI is simple to use with onscreen help. Users may
submit, through it local and global transactions. Global
transactions can also be spread over more than one site.
Effective monitoring of all activity is done and visible on
screen. The user may also initiate status detection if she feels
her transactions’ results are long overdue. Working in the
background is the update manager (which may be disabled).
This is responsible for keeping up to date information about
nodes on the network and may be modified for use as a means
of background message passing between hosts thus leaving
scope for improvement and addition of(in the near future)
automatic handling of tasks by nodes.
D. Transaction Processing System
In the mobile database environment it is essential for users at
various sites to be able to access databases at others sites. In
effect, a database stored at one host has to cater to simultaneous
needs of many other hosts, while maintaining its autonomy.
This approach is of extreme importance in applications such as
banking. This is, in fact one of the key growth areas for MCommerce.
The real time fast access of databases has several
advantages of improved efficiency, better application
performance(lesser waiting time for users), etc. It however,
also comes with a host of new problems.
A number of security issues arise pertaining to simultaneous
data access and database modification by more than one
transaction at a time. In fact most transactions in these cases
span over multiple sites and need sub transaction management
(sagas and nested sagas). Another issue is local autonomy of a
site. Whether or not, to allow global entities to control
transaction processing is another issue. If allowed local
autonomy is often jeopardized, if not then external transactions
may have to wait for a long time before being executed. This
leads to indefinite delays, unnecessary aborts and hidden
deadlocks[6]. In fact tradeoffs of some kind must be made,
generally a proper transaction-processing scheme is
implemented and maintained across all sites to make sure the
ACID properties are always satisfied.
It is a design consideration in our model and fundamental to
its operation that a host does not treat a global transaction as if
it were special. Once submitted a transaction is totally
dependent on the host for its completion. This approach is
consistent with our decision of maintaining local autonomy.
Once completed, results are sent back to the originating host.
To maintain the ACID properties transactions must be
completed as a whole or aborted with compensating
transactions whenever needed. Moreover, before a successful
commit, the changes made by a transaction are visible only to
itself. This approach prevents cascading rollbacks incase the
transaction aborts. However, to speed up operation, since most
transactions are long lived, explicit commit points may be
specified so as to generate sagas, and handle many transaction
operations in parallel. The submitter of the transaction must
specify explicit commit points and the transaction effectively
branches at this point to have its partial work committed.
Global transactions however may not give immediate results; in
fact the transactions are stored locally and only when
completed are they submitted to the desired host(s). This
approach is consistent with minimum communication usage so
as to provide optimum usage of battery power for mobile hosts.
Once the transaction is processed the results are sent back to the
submitter.
Transactions are moved around using a fixed format. Strings
of data(queries) are stored as files mapped as trees logically,
where the root node is always a string of the form:
!#$$#!
This string enables us to distinguish transactions from one
another, recover from failures and handle re-submissions in
case of network loss or delay. The remaining nodes contain
strings of the query statements that make up the transaction.
Consider the transaction fragment given below.
select * from table_1;
insert into table_1 values(23, “rookie”);
commit;
select * from table_1;
select * from 172.16.3.2#table_45;
insert into 172.16.3.2#table_45 values (34, 34,
“veteran”);
commit;
This amounts to the following(logically), figure 4.
!#<4522>$<172.16.4.3>$<172.16.5.34>#!
select * from table_1;
insert into table_1
values(23, “rookie”);
commit;
select * from table_1;
select * from
172.16.3.2#table_45;
insert into
172.16.3.2#table_45 values
(34, 34, “veteran”);
commit;
Transaction subpart
Transaction subpart
Figure 4. Nested Transactions
Thus as can be seen from the figure above the transactions
divide themselves at commit points specified by users thus
amounting to sagas. This approach is extremely efficient in
increasing system throughput as global transactions or other
submitted transactions’ parts are given a chance to run, as the
previous work has been committed. The sub-transactions are
often executed independently from one another and parts of
transactions may be restored or rolled back depending upon
context. Moreover it is also possible to send of sub-transactions
to other hosts in an efficient manner. Such conventions and
corresponding naming methods are adopted for results to be
sent back to the designated hosts as well.
When a transaction has completed its work it must be made
permanent. Local transactions are committed at user discretion.
Global transaction queries are committed at the sites they are
sent to and any results generated are stored as a file and
forwarded to the respective submitter. Under this scheme, the
transactions are executed independently at each site. Logs are
maintained to implement this regardless of failures. However in
case of a failure of a transaction at one site it becomes the
responsibility of a manual operator to make sure that the
required work is done at that site, particularly since partial
commits are allowed and sub-transactions may have been
committed at other sites. Transactions once committed cannot
be rolled back. If possible a compensating transaction may be
generated otherwise manual intervention is needed. The
‘OPTIMISM’ model however guarantees delivery of the
necessary alerts and messages to the concerned hosts. Incase of
failure before a commit the work of a transaction is rolled back
automatically. Local transactions may also be rolled back at
user discretion. When a transaction is rolled back no other
transaction is effected since the work done by a transaction is
visible only to itself before a commit.
A unique feature of this model is the fact that heterogeneous
databases and schema are supported. Different databases
having different relations(tables) may be used remotely to
generate transactions and submit results. A user at a particular
site simply needs to specify the name of the concerned site
where the database is located and she is provided all the details
of that sites schema. This may then be kept in mind to generate
transactions as required. Caching is used along with this form
of explicit querying in order to maximize performance. Apart
from explicit queries a thesaurus [16] is also maintained at the
MainServer(shown in figure 5). This is updated periodically
and also by explicit messages from hosts regarding their
schema changes. The central thesaurus is however a central
point of failure and this hinders our distributed approach.
However it is possible to replicate the thesaurus at various
hosts, moreover the additional feature of explicit queries
eradicates the central point of failure. The thesaurus can be
used when a transaction is to span numerous sites and by a
single message to the thesaurus it is possible to get information
about the different schema present on the entire system. This
can be extremely effective in decreasing the network
congestion and transaction generation time and eventually its
round trip execution time.
Apart from transactions the mobile hosts also move around
the network. The result of which is that the MH may show up
anywhere on the network under any BH. It is the responsibility
of the BH to recognize this MH and register it by contacting its
previous region’s BH[17]. When a mobile entity moves to a
new region, it must be assigned a new IP[18]. In fact any
change in the attachment point of a MH should be completely
transparent to the protocols and applications running on the
stationary hosts. Any mobile communication framework can
handle this mobility of a client. We have used the PMADE [17]
framework for this purpose. The ‘OPTIMISM” model
effectively deals with movement both of the MH and
transactions. It is possible for an MH on the move to generate
transactions that need to be distributed at other nodes in other
regions. A unique naming scheme based on Figure 4 is used to
identify the transactions and results coming in from other nodes
effectively. The PMADE framework ensures delivery of
messages to the designated MHs even if they move to other
regions by suitably maintaining system state information and
adding appropriate message headers for re-routing of message
packets.
Frequent disconnection is also effectively handled (the
problem arises since wireless networks are at best sporadic).
The user may continue to work on the local copy of the
database, while global transactions to be submitted or results of
previous global transactions are simply queued and sent of to
their respective destinations as soon a network connection is
available. Thus work queues are maintained and due
consideration is also given to make minimum use of broadcasts
to save battery power.
D.1 Transaction Coordinator
The transaction coordinator is responsible for managing the
various transactions on a node. It is designed to distinguish the
sub-transactions from one another and sort out the incoming
results. It often adds or retracts the necessary information
to/from the outgoing/incoming message stream to effectively
manage the various global and local transactions.
D.2 Transaction and Query Manager
This part of the transaction processing system is responsible for
the actual execution of queries at a node. It is in effect the
interface to the underlying database. It deals with the execution
of a scheduler-selected transaction.
MH
MH
GLOBAL THESAURUS
maintains
universal
schema sets
Local
Database
Thesaurus
queries or
automatic
updates
Thesaurus reply:
172.16.3.2
!#
@table_44$varchar$
integer@
@table_45$integer$
integer$
varchar@
#!
Cache
TPS
Local
Database
TPS
Cache
Direct query
to node
Schema Query Reply:
!#
@Account_Info$varchar$
integer$integer@
#!
Figure 5. Managing Heterogeneity of Databases, support for different
schema sets
D.3 Concurrency Manager
Probably the most essential part of the design is the
concurrency manager. It is the main arm responsible for
transaction concurrency while maintaining isolation and
consistency. It is designed with deadlock prevention (soon to be
integrated with a full fledged detection and resolution
algorithm) in mind and keeps the system in a safe state so as to
avoid degradation of system performance. Stable storage logs
and database information is also controlled through the
concurrency manager. All information is subject to locks and
may only be accessed on a rotational basis.
The resource that all transactions compete for is the
underlying database. The concurrency manager resolves the
simultaneous work of many transactions by keeping in mind a
number of factors particularly kind of transaction, etc.
maintaining queues and executing transactions in parallel.
Local transactions are however given preference over global
transactions; this again is consistent with the notion of local
autonomy.

Sunday, September 14, 2008

Love soldier

Melinda looked at her self in the mirror and she could not recognize the person she saw. A frail woman with deep sunken eyes, too petite for her long oversized clothes with tiny sprouts of prickly hair, stared back at her. Tears welled up in her eyes and started their usual course down her bony cheek.


Her thoughts darted back to the gorgeous woman who used to look back at her and greet her with a million dollar smile, every time she looked into the mirror. The Mirror woman, she knew, was a college beauty queen, full of confidence and exuberance. Her lovely face with golden curls dangling on her rosy cheeks caused many a heart to flutter. That was when she first met Alex, the man of her dreams. They have been a couple ever since and now they dreamed of growing old together.


As Alex came to her mind, Melinda felt an excruciating pain stab her heart.




‘I can’t do this to Alex! He deserves better. I can’t let him waste away his life because of me’ she thought.




Alex was a man any girl would dream of having as her husband.Charming, elegant and successful, he stood by Melinda all through the ordeal...The ordeal of having Mastectomy and then the Six weeks of Chemotherapy that she had to undergo. The last One year was emotionally draining for Melinda. She still remembers the day when she went to the Cancer Hospital with Alex for the Biopsy report of the lump that she accidentally found in her breast. Their fears came true and she was diagnosed with Breast cancer that was eating away into the tissues and the doctors told her that she needed to undergo the entire breast removal or Mastectomy.




Melinda sat their petrified in the doctor’s chambers. All her dreams came shattering down like a pack of cards .Alex gave her a hug and told her that he would be there for her and that they would fight Cancer together.




The Mastectomy left a scar across her chest and the grueling chemotherapy of six weeks that followed the surgery left her hairless, weak and the gloomy fear that she might not be able to become a mother ever as the Chemotherapy causes fertility issues and early onset of menopause.




As her worrying thoughts engulfed her, Alex stepped into the room with his usual sunshine smile and a bouquet of fresh flowers and his shining completely bald head, which he sported to support Melinda.




‘How is my beautiful princess doing today?’ he asked giving her a kiss.




‘Alex, don’t call me beautiful! I am not whom you fell in love with!’ said Melinda with pain.




Alex stood there disturbed looking at Melinda.




‘I can’t do this to you Alex! I think we should break our relationship. You know what cancer has done to me...dont you? You deserve someone gorgeous...some one who will raise a family with you…You deserve the best Alex!’ said Melinda controlling her tears...




‘No!…Don’t you ever say this to me!!’ said Alex looking aghast.




Melinda exposed her uneven chest with a large scar on it and said, “now ...tell me...Do I still look beautiful to you?…Like the Gorgeous Melinda you fell in love with?’




Tears welled up in Alex’s eyes as he came up to her and covered her with his embrace.




‘You know, what that scar reminds me of? The scar reminds me of how hard you fought cancer for our love. How hard you fought this battle for US and our dream of growing old together…You are my LOVE SOLDIER. And you won the battle. And you know what? You not only the most beautiful woman in the world but also the bravest!’ said Alex in a choked voice with tears now coursing down his cheeks.




‘Now, Will you marry me my beautiful Love soldier?’ Alex asked with a smile.




Melinda stood transfixed and was unable to speak. Bursting into a cascade of tears she embraced Alex saying,’ with you by my side in the journey of life, I know I can fight any number of battles and come out victorious! I’m Your Love soldier till death do us part!!!’

Grandma's magic potions

Grandma's magic potions


My sweet granny was an enthusiastic lady.Married early, in the long gone days of Child marriages,she could study only up to the 5th grade but her zeal to acquire knowledge,be financially independent like a today’s woman and help others like her grandpa drove her to make ‘magic potions’As a young girl she often saw her grandpa make potions that healed many and quickly learnt how to recognize forest herbs and from then on till her last days she made remarkable curatives.Be it a medicine for a tummy ache or herbal oil to make your hair grow lustrous and long,she made them all.Granny had great memory and would often go to the nearby woods taking me along and got me acquainted to the world of herbs.



"Look!! that’s a brahmi..good for the hair and brain



That’s the neela herb!!…this is Naga bala and this is vidarikanda.for strength and skin glow"..she pointed them out to me.



She meticulously collected the exotic herbs and grew some in our garden too .Some she would buy from the local Herb store and then add,mix,boil,strain..she would make her magic potions and oils.These potions actually worked wonders and she soon had a good number of people buying her granny hair oil though it failed to grow hair on baldies
I remember once when a centipede bit me on my leg ‘ouch’in the middle of the night .With no docs available at that time,my granny came to the rescue.She mixed and boiled some ‘magic potion’ and uttered a few mantras into it.she then made me drink it.After that she brought a candle near the bite and made it feel the warmth of the candle…continuously uttering the divine mantras…and lo presto!!! I could see some liquid bubbling out of the bite…
That’s the poison..its come out and now you will be ok’,she said…and yes I was!!



Sometimes her remedies made me roll in laughter like the one in which a lady came to her complaining of her flat chest and she told granny that she wanted a bootylicious figure,



Well…granny never says NO to anyone..so she got to work peering through her ancient herbal books ,collecting herbs…mix,boil and then the ‘magic potion’ was ready…of course it didn’t work but atleast she tried!



Be it stories about the Bharadwaj bird that supposedly has the sanjeevani booti of youth in her nest or the leaves that help turn metal into gold..she told them with such conviction that I actually believed them..may be they really exist…

The Flower that taught me-never lose HOPE.

One day I noticed a tiny plant that was feeding on the moist walls of a deep dark well. An iron mesh covered the mouth of the well and the plant was trapped and I felt pity for it.



A few days later I noticed that the plant bloomed a lovely yellow flower and felt even more bad for it as the flower was a part of a covered well and it would never feel the entire warmth of the sun or the kiss of a butterfly….it’s beauty trapped and it’s existence unknown to the beautiful world outside….a hopeless condition....one of nature’s lovely creations that was wasting away in a deep well..
A few days later I was stunned to see the tiny plant emerge out of the deep dark well...out of the mesh and bloom it’s lovely yellow flower for the nature to see.


It smiled at me and seemed to tell me,

‘I made it...You were wrong!!!’



That day the Spirit of the tiny flower taught me that-



Even if you are in the deepest and darkest conditions of your life and things look hopeless,never lose HOPE.



Even if the world says you won’t make it...don’t listen.



Even if obstacles and meshes block your progress, never stop…Keep growing till you reach your goal…You will find your way out eventually!



If so much will and strength is hidden in a tiny flower,what can you say about the colossal Human spirit?



So Friends, Never Give up and Keep growing…You will be surprised at the enormous potential that is sequestrated in you...Awaken your Human spirit!!!

Friday, September 12, 2008

Clever Maths

Clever Maths

Long ago, a mathematician used to cheat people. Once
he borrowed
Rs.4000/- from a rich man. After a few days, he
borrowed Rs.2000/- from the same man.

Many days passed, the mathematician did not return the
money to the rich man. The rich man went to the
mathematician and asked to return the money.

But to his great surprise, the mathematician replied
that there is no
need to pay the debt.

"See here, friend" said the mathematician " the sum of
4000 and 2000 is equal to
zero, so I do not have any balance to pay".

The rich man took the matter to the court. When the
judge came to know
this, he was astonished. He asked the mathematician to
prove that sum of 4000 and 2000 is zero, and not 6000.

The Clever mathematician agreed. He said:

let a == 4000, b == 2000 and

a + b == c

Multiply both sides by a + b

(a + b) (a + b ) == c (a + b)

a*a + ab + ba + b*b == ca + cb

a*a + ab - ca == cb - b*b - ba

a( a + b -c) == -b(b + a - c)

so a == - b

a + b == 0

Hence 4000 + 2000 = 0........... .

coincidence

Scary coincidence or careful planning


This is actually really freaky!! (Mainly the end part, but read it all first)

1) New York City has 11 letters
2) Afghanistan has 11 letters.
3) Ramsin Yuseb (The terrorist who threatened to destroy the Twin Towers in 1993) has 11 letters.
4) George W Bush has 11 letters.

This could be a mere coincidence, but this gets more interesting:
1) New York is the 11th state.
2) The first plane crashing against the Twin Towers was flight number 11.
3) Flight 11 was carrying 92 passengers. 9 + 2 = 11
4) Flight 77 which also hit Twin Towers, was carrying 65 passengers. 6+5 = 11
5) The tragedy was on September 11, or 9/11 as it is now known. 9 + 1+ 1 = 11
6) The date is equal to the US emergency services telephone number 911. 9 +1 + 1 = 11

Sheer coincidence..?! Read on and make up your own mind:
1) The total number of victims inside all the hi-jacked planes was 254. 2 + 5 + 4 = 11.
2) September 11 is day number 254 of the calendar year. Again 2 + 5 + 4 = 11.
3) The Madrid bombing took place on 3/11/2004. 3 + 1 + 1 + 2 + 4 = 11.
4) The tragedy of Madrid happened 911 days after the Twin Towers incident.

Now this is where things get totally eerie:
The most recognized symbol for the US, after the Stars & Stripes, is the Eagle. The following verse is taken from the Quran, the Islamic holy book:
"For it is written that a son of Arabia would awaken a fearsome Eagle. The wrath of the Eagle would be felt throughout the lands of Allah while some of the people trembled in despair still more rejoiced: for the wrath of the Eagle cleansed the lands of Allah and there was peace."
That verse is number 9.11 of the Quran.
Unconvinced about all of this still ..?!
Try this and see how you feel
afterwards, it made my hair stand on end:
Open Microsoft Word and do the following:
1. Type in capitals Q33 NY. This is the flight number of the first plane to hit one of the Twin Towers.
*
2. Highlight the Q33 NY.
3. Change the font size to 48.
4. Change the actual font to the WINGDINGS

The Mechanics of love- Why do we love those we do?

For eons this illusive emotion called love has held the human race spell bound with its magical charm. The thinkers among us have long tried to find the answers to why we love the people we do, with varying degrees of success. However, the one thing that we are absolutely sure about is that it is not Cupid’s doing. Unless of course he has kept abreast of the latest medical research and decided to dip his arrows in phenyl ethylamine before shooting them.

Scientists have also done extensive research on love. They have discovered what they describe as a love map in the human brain. According to them it is these “love maps” that determine our choice of partners and also the kind of relationship we have.

The foundation for this map is laid down in early childhood, as the human brain records in great detail an individuals experiences and preferences. You will be surprised to know that the most minute (and sometimes considered insignificant) details are stored. For instance the kinds of details stored are information like hair colour, physique, gait, eye colour, personality type. We are attracted to people who fit into this mental image. It is believed that a human child has a clear idea of the kind of mate he would desire by the time he is eight years old.

Since our parents were the first loves of our lives, our relationship with them is the first influence on our love map. The mother’s relationship with her children has greater impact on the child’s love map as she spends a lot of time with them. This is especially true in the case of a male child as, his relationship with his mother will determine his ideas about and relationship with women. If the relationship is warm and friendly, the boy will grow up to be a caring and responsible partner. Instability in the mother son relationship results in a feeling of insecurity. This in turn can get manifested as a permanent fear of commitment, low self-esteem and a persistent feeling of not being appreciated enough.

Similarly, a father’s relationship with his daughter influences her general feelings about men and to some extent about herself. A loving and caring father gives his daughter the gift of unquestionable self-worth. On the other hand a cold and critical father or the absence of a father adversely impacts the self confidence of the child.

One look at the matrimonial column gives an impression that the looks of a person is of the first things that is taken into consideration when trying to find a mate (by either sexes). The science of falling in love however negates this. According to research findings intelligence and kindness play a very important role in our choices , with the latter gaining priority over the former.

When looking for a marriage partner our choices are guided by two factors- social similarities and complementary needs. For instance a very conservative person is attracted to a person with a more liberal mentality from a similar social background.

The love map also influences the physical choice of the person. Now the question may arise that if every person is equipped with this all seemingly flawless choice enabler known as the love map, the why do people have to deal with painful situations such as divorce and separation. Well, there are a couple of logical reason for this. Firstly, besides the love map our choice of mate is guided by other factors such as social and financial status. Secondly, love needs to be nurtured even when the best choices are made. The minute it is taken for granted weeds begin to grow around it. So, take care of love and watch it blossom!



Note: This is not my original piece. This nice article was available on net which I am sharing with you all.

Hanuman Chalisa

Hanuman Chalisa


JAI HANUMAN GYAN GUN SAGAR JAI KAPISH TUHI LOK UJAGAR"



Shree Guru Charan Saroj Raj, Nij Man Mukar Sudhari,
Barnau Raghuvar Bimal Jasu, Jo dayaku Phal Chari

With the dust of Guru's Lotus feet, I clean the mirror of my mind and then
narrate the sacred glory of Sri Ram Chandra, The Supereme among the Raghu
dynasty. The giver of the four attainments of life.

Budhi heen Tanu Janike, Sumirow, Pavan Kumar,
Bal Buddhi Vidya Dehu Mohi, Harahu Kalesh Bikaar

Knowing myself to be ignorent, I urge you, O Hanuman, The son of Pavan! O
Lord! kindly Bestow on me strength, wisdom and knowledge, removing all my
miseries and blemishes.

Jai Hanuman Gyan Guna Sagar
Jai Kipis Tihun Lok Ujgaar

Victory of Thee, O Hanuman, Ocean of wisdom and virtue, victory to the Lord of
monkeys who is well known in all the three worlds

Ramdoot Atulit Bal Dhamaa,
Anjani Putra Pavansut naamaa.

You, the Divine messager of Ram and repository of immeasurable strength, are also
known as Anjaniputra and known as the son of the wind - Pavanputra.

Mahebeer Bikram Bajrangi,
Kumati Nivaar Sumati Ke Sangi.

Oh Hanumanji! You are valiant and brave, with a body like lightening. You are the
dispeller of darkness of evil thoughts and companion of good sense and wisdom.

Kanchan Baran Biraaj Subesaa,
Kanan kundal kunchit kesa.

Shri Hanumanji's physique is golden coloured. His dress is pretty, wearing
'Kundals' ear-rings and his hairs are long and curly.

Hath Bajra Aur Dhvaja Birjai,
Kandhe Moonj Janeu saage.

Shri Hanumanji is holding in one hand a lighting bolt and in the other a banner
with sacred thread across his shoulder.

Shankar Suvna Kesari Nandan,
Tej Pratap Maha Jag Vandan.

Oh Hanumanji! You are the emanation of 'SHIVA' and you delight Shri Keshri.
Being ever effulgent, you and hold vast sway over the universe. The entire
world proptiates. You are adorable of all.

Vidyavaan Guni Ati Chatur,
Ram Kaj Karibe Ko Atur

Oh! Shri Hanumanji! You are the repository learning, virtuous, very wise and
highly keen to do the work of Shri Ram,
Prabhu Charittra Sunibe Ko Rasiya,
Ram Lakhan Sita man basyia.

You are intensely greedy for listening to the naration of Lord Ram's lifestory and
revel on its enjoyment. You ever dwell in the hearts of Shri Ram-Sita and Shri
Lakshman.
Sukshma roop Dhari Siyahi Dikhwana,
Bikat roop Dhari Lank Jarawa

You appeared beofre Sita in a diminutive form and spoke to her, while you
assumed an awesome form and struck terror by setting Lanka on fire.

Bhim roop Dhari Asur Sanhare,
Ramchandra Ke kaaj Savare.

He, with his terrible form, killed demons in Lanka and performed all acts of Shri
Ram.
Laye Sajivan Lakhan Jiyaye,
Shri Raghubir harashi ur laye.

When Hanumanji made Lakshman alive after bringing 'Sanjivni herb' Shri Ram
took him in his deep embrace, his heart full of joy.

Raghupati Kinhi Bahut Badaai,
Tum Mama Priya Bharat Sam Bahi.

Shri Ram lustily extolled Hanumanji's excellence and remarked, "you are as dear
to me as my own brother Bharat"

Sahastra Badan Tumharo Jas Gaave,
Asa kahi Shripati Kanth Laagave.

Shri Ram embraced Hanumanji saying:
"Let the thousand - tongued sheshnaag sing your glories"

Sankadik Brahmadi Muneesa,
Narad Sarad Sahit Aheesa

Sanak and the sages, saints. Lord Brahma, the great hermits Narad and
Goddess Saraswati along with Sheshnag the cosmic serpent, fail to sing the
glories of Hanumanji exactly

Jam Kuber Digpal Jahan Te,
Kabi Kabid Kahin Sake Kahan Te

What to talk of denizens of the earth like poets and scholars ones etc even Gods
like Yamraj, Kuber, and Digpal fail to narrate Hanman's greatness in toto.

Tum Upkar Sugrivahi Keenha,
Ram Miali Rajpad Deenha

Hanumanji! You rendered a great service for Sugriva, It were you who united
him with SHRI RAM and installed him on the Royal Throne.

Tumharo Mantro Bibhishan Maana,
Lankeshwar Bhaye Sab Jag Jaana.

By heeding your advice. Vibhushan became Lord of Lanka, which is known all
over the universe.

Juug Sahastra Jojan Par Bhaanu,
Leelyo Taahi Madhur Phal Jaanu

Hanumanji gulped, the SUN at distance of sixteen thousand miles considering
it to be a sweet fruit.

Prabhu Mudrika Meli Mukha Maaheen,
Jaladhi Langhi Gaye Acharaj Naheen.

Carrying the Lord's ring in his mouth, he went across the ocean. There is no
wonder in that.

Durgam Kaaj Jagat Ke Jeete,
Sugam Anugrah Tumhre Te Te.

Oh Hanumanji! all the difficult tasks in the world are rendered easiest by your
grace.
Ram Duware Tum Rakhavare,
Hot Na Aagya Bin Paisare.

Oh Hanumanji! You are the sentinel at the door of Ram's mercy mansion or His
divine abode. No one may enter without your permission.

Sab Sukh Lahen Tumhari Sarna,
Tum Rakshak Kaahu Ko Darnaa.

By your grace one can enjoy all happiness and one need not have any fear under
your protection.

Aapan Tej Samharo Aapei,
Tanau Lok Hank Te Kanpei

When you roar all the three worlds tremble and only you can control your might.

Bhoot Pisaach Nikat Nahi Avei,
Mahabir Jab Naam Sunavei.

Great Brave on. Hanumanji's name keeps all the Ghosts, Demons & evils spirits
away from his devotees.

Nasei Rog Hare Sab Peera,
Japat Niranter Hanumant Beera

On reciting Hanumanji's holy name regularly all the maladies perish the entire
pain disappears.

Sankat Te Hanuman Chhudavei,
Man Kram Bachan Dhyan Jo Lavei.

Those who rembember Hanumanji in thought, word and deed are well guarded
against their odds in life.

Sub Par Ram Tapasvee Raaja,
Tinke Kaaj Sakal Tum Saaja

Oh Hanumanji! You are the caretaker of even Lord Rama, who has been hailed as
the Supreme Lord and the Monarch of all those devoted in penances.

Aur Manorath Jo Koi Lave,
Soi Amit Jivan Phal Pave.

Oh Hanumanji! You fulfill the desires of those who come to you and bestow
the eternal nectar the highest fruit of life.

Charo Juung Partap = Tumhara,
Hai Parsiddha Jagat Ujiyara.

Oh Hanumanji! You magnificent glory is acclaimed far and wide all through the
four ages and your fame is radianlty noted all over the cosmos.

Sadho Sant Ke Tum Rakhvare,
Asur Nikandan Ram Dulare.

Oh Hanumanji! You are the saviour and the guardian angel of saints and sages
and destroy all the Demons, you are the seraphic darling of Shri Ram.

Ashta Siddhi Nau Nidhi Ke Data,
Asa Bar Din Janki Mata.

Hanumanji has been blessed with mother Janki to grant to any one any YOGIC
power of eight Sidhis and Nava Nidhis as per choice.

Ram Rasayan Tumhare Pasa,
Sadaa Raho Raghupati Ke Dasa.

Oh Hanumanji! You hold the essence of devotion to RAM, always remaining His
Servant.

Tumhare Bhajan Ramko Pavei.
Janam Janam Ke Dukh Bisravei.

Oh Hanumanji! through devotion to you, one comes to RAM and becames free
from suffering of several lives.

Anta Kaal Raghubar Pur Jai,
Jahan Janma Hari Bhakta Kahai.

After death he enters the eternal abode of Sri Ram and remains a devotee of
him, whenever, taking new birth on earth.

Aur Devata Chitt Na Dharai,
Hanumant Sei Sarva Sukh Karai

You need not hold any other demigod in mind. Hanumanji alone will give all
happiness.

Sankat Kate Mitey Sab Peera,
Jo Sumirei Hanumant Balbeera

Oh Powerful Hanumanji! You end the sufferings and remove all the pain from
those who remember you.

Jai Jai Jai Hanuman Gosai
Kripa Karahu Gurudev Ki Naiee

Hail-Hail-Hail-Lord Hanumanji! I beseech you Honour to bless me in the
capacity of my supreme 'GURU' (teacher).

Jo Sat Baar Paath Kar Koi,
Chhutahi Bandi Maha Sukh Hoi.

One who recites this Hanuman Chalisa one hundred times daily for one hundred
days becames free from the bondage of life and death and ejoys the highest
bliss at last.

Jo Yah Padhe Hanuman Chalisa,
Hoy Siddhi Sakhi Gaurisa

As Lord Shankar witnesses, all those who recite Hanuman Chalisa regularly are
sure to be benedicted

Tulsidas Sada Hari Chera,
Keeje Nath Hriday Mah Dera.

Tulsidas always the servant of Lord prays. "Oh my Lord! You enshrine within my
heart.!

Chopai

Pavan Tanay Sankat Haran, Mangal Murti Roop.
Ram Lakhan Sita Sahit, Hriday Basahu Sur Bhoop.

O Shri Hanuman, The Son of Pavan, Saviour The Embodiment of
blessings, reside in my heart together with Shri Ram, Laxman and Sita

Once upon a time....

Once upon a time....

There was a rich King who had 4 wives.
He loved the 4th wife the most and adorned her with rich robes and treated her to the finest of delicacies. He gave her nothing but the best.


He also loved the 3rd wife very much and was always showing her off to neighboring kingdoms. However, he feared that one day she would leave him for another.


He also loved his 2nd wife. She was his confidante and was always kind, considerate and patient with him. Whenever the King faced a problem, he could confide in her to help him get through the difficult times
The King's 1st wife was a very loyal partner and had made great contributions in maintaining his wealth and kingdom. However, he did not love the first wife and although she loved him deeply, he hardly took notice of her.


One day, the King fell ill and he knew his time was short.
He thought of his luxurious life and pondered, "I now have 4 wives with me, but when I die, I'll be all alone.

Thus, he asked the 4th wife, "I have loved you the most, endowed you with the finest clothing and showered great care over you. Now that I'm dying, will you follow me and keep me company?"



"No way!" replied the 4th wife and she walked away without another word.


Her answer cut like a sharp knife right into his heart.


The sad King then asked the 3rd wife, "I have loved you all my life. Now that I'm dying, will you follow me and keep me company?"



"No!" replied the 3rd wife. "Life is too good!
When you die, I'm going to remarry!"


His heart sank and turned cold.


He then asked the 2nd wife, "I have always turned to you for help and you've always been there for me. When I die, will you follow me? And keep me company?"


"I'm sorry, I can't help you out this time!" replied the 2nd wife. "At the very most, I can only send you to your grave."

Her answer came like a bolt of thunder and the King was devastated.


Then a voice called out:

"I'll leave with you and follow you no matter where you go." The King looked up and there was his first wife. She was so skinny, she suffered from malnutrition.

Greatly grieved, the King said, "I should have taken much better care of you when I had the chance!"


In Truth, we all have 4 wives in our lives ...

Our 4th wife is our body. No matter how much time and effort we lavish in making it look good, it'll leave us when we die.


Our 3rd wife is our possessions, status and wealth.
When we die, it will all go to others.


Our 2nd wife is ourfriends. No matter how much they have been there for us, the furthest they can stay by us is up to the grave.

And our 1st wife is our Parents,


Often neglected in pursuit of wealth, power and pleasures of the ego. However, our Parents are the only thing that will follow us and guide wherever we go.

So Love them at our best ..... They need and Love you most!!!
You are their greatest gift

Let them Smile and cherish...

ICE

ICE


Recently, the concept of "ICE" is catching up quickly. It is simple, yet an important method of contact during emergency situations.

As cell phones are carried by majority of the population, all you need to do is store the number of a contact person or persons who should be contacted at during emergency as "ICE" (meaning In Case of Emergency).

The idea was thought up by a paramedic who found that when they went to the scenes of accidents, there were always mobile phones with patients, but they didn't know which numbers to call.

He therefore thought that it would be a good idea if there was a nationally recognized name for this purpose.

Following a disaster in London, the East Anglican Ambulance Service has launched a national "In case of Emergency (ICE)" campaign.

In an emergency situation, Emergency Services personnel and hospital staff would then be able to quickly contact your next of kin, by simply dialing the number stored as "ICE".

Please forward this. It won't take too many "forwards" before everybody will know about this.

It really could save your life, or put a loved one's mind at rest.

For more than one contact name simply enter ICE1, ICE2 and ICE3 etc. A great idea that will make a difference !

CELLPHONE COULD DO

THINGS YOU NEVER KNEW YOUR CELLPHONE COULD DO

There are a few things that can be done in times of grave emergencies.

Your mobile phone can actually be a life saver or an emergency tool for

survival. Check out the things that you can do with it: -


1

EMERGENCY


* The Emergency Number worldwide for **Mobile** is 112 ...* If you find

yourself out of coverage area of your mobile network and there is an

emergency, dial 112 and the mobile will search any existing network to

establish the emergency number for you, and interestingly this number 112

can be dialed even if the keypad is locked. **Try it out.**

2

Have you locked your keys in the car? Does you car have remote keysThis may come in handy someday. Good reason to own a cell phone:

If you lock your keys in the car and the spare keys are at home, call

someone at home on their cell phone from your cell phone.

Hold your cell phone about a foot from your car door and have the person

at your home press the unlock button, holding it near the mobile phone on

their end. Your car will unlock. Saves someone from having to drive your

keys to you. Distance is no object. You could be hundreds of miles away,

and if you can reach someone who has the other "remote" for your car, you

can unlock the doors (or the trunk).

Editor's Note: *It works fine! We tried it out and it unlocked our car over a cell phone!"*
3

Hidden Battery power
Imagine your cell battery is very low , you are expecting an important call

and you don't have a charger. Nokia instrument comes with a reserve

battery. To activate, press the keys *3370# Your cell will restart with

this reserve and the instrument will show a 50% increase in battery. This

reserve will get charged when you charge your cell next time.

AND


4

How to disable a STOLEN mobile phone?




To check your Mobile phone's serial number, key in the following digits on your phone:

* # 0 6 #

A 15 digit code will appear on the screen. This number is unique to your

handset. Write it down and keep it somewhere safe. when your phone get

stolen, you can phone your service provider and give them this code. They

will then be able to block your handset so even if the thief changes the

SIM card, your phone will be totally useless.

You probably won't get your phone back, but at least you know that whoever stole it can't use/sell it either.

If everybody does this, there would be no point in people stealing mobile phones.



HOPE YOU ENJOY USING YOUR MOBILE

rearrange the letters:

DILIP VENGSARKAR
When you rearrange the letters:
SPARKLING DRIVE

BARA THEDA
When you rearrange the letters:
ARAB DEATH

PRINCESS DIANA
When you rearrange the letters:
END IS A CAR SPIN

MONICA LEWINSKY
When you rearrange the letters:
NICE SILKY WOMAN

DORMITORY:
When you rearrange the letters:
DIRTY ROOM

PRESBYTERIAN:
When you rearrange the letters:
BEST IN PRAYER

ASTRONOMER:
When you rearrange the letters:
MOON STARER

DESPERATION: When you rearrange the letters:
A ROPE ENDS IT

THE EYES:
When you rearrange the letters:
THEY SEE

GEORGE BUSH:
When you rearrange the letters:
HE BUGS GORE

THE MORSE CODE :
When you rearrange the letters:
HERE COME DOTS

SLOT MACHINES:
When you rearrange the letters:
CASH LOST IN ME

ANIMOSITY:
When you rearrange the letters:
IS NO AMITY

ELECTION RESULTS:
When you rearrange the letters:
LIES - LET'S RECOUNT

SNOOZE ALARMS:
When you rearrange the letters:
ALAS! NO MORE Z 'S

A DECIMAL POINT:
When you rearrange the letters:
IM A DOT IN PLACE

THE EARTHQUAKES:
When you rearrange the letters:
THAT QUEER SHAKE

ELEVEN PLUS TWO:
When you rearrange the letters:
TWELVE PLUS ONE

AND FOR THE GRAND FINALE:

MOTHER-IN-LAW:
When you rearrange the letters:
WOMAN HITLER

arrays in java

Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index. Arrays offer a convenient means of grouping related
information.
Note If you are familiar with C/C++, be careful. Arrays in Java work differently than
they do in those languages.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array,
you first must create an array variable of the desired type. The general form of a onedimensional
array declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of
each element that comprises the array. Thus, the base type for the array determines
what type of data the array will hold. For example, the following declares an array named
month_days with the type "array of int":
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no
array actually exists. In fact, the value of month_days is set to null, which represents an
array with no value. To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days. new is a special operator that
allocates memory.
You will look more closely at new in a later chapter, but you need to use it now to allocate
memory for arrays. The general form of new as it applies to one-dimensional arrays
appears as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and array-var is the array variable that is linked to the array. That
is, to use new to allocate an array, you must specify the type and number of elements to
allocate. The elements in the array allocated by new will automatically be initialized to
zero. This example allocates a 12-element array of integers and links them to
month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further,
all elements in the array will be initialized to zero.
Let's review: Obtaining an array is a two-step process. First, you must declare a variable
of the desired array type. Second, you must allocate the memory that will hold the array,
using new, and assign it to the array variable. Thus, in Java all arrays are dynamically
allocated. If the concept of dynamic allocation is unfamiliar to you, don't worry. It will be
described at length later in this book.
Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets. All array indexes start at zero. For example,
this statement assigns the value 28 to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Putting together all the pieces, here is a program that creates an array of the number of
days in each month.
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
When you run this program, it prints the number of days in April. As mentioned, Java
array indexes start with zero, so the number of days in April is month_days[3] or 30.
It is possible to combine the declaration of the array variable with the allocation of the
array itself, as shown here:
int month_days[] = new int[12];
This is the way that you will normally see it done in professionally written Java programs.
Arrays can be initialized when they are declared. The process is much the same as that
used to initialize the simple types. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the values of the array
elements. The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new. For example, to
store the number of days in each month, the following code creates an initialized array of
integers:
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
When you run this program, you see the same output as that generated by the previous
version.
Java strictly checks to make sure you do not accidentally try to store or reference values
outside of the range of the array. The Java run-time system will check to be sure that all
array indexes are in the correct range. (In this regard, Java is fundamentally different
from C/C++, which provide no run-time boundary checks.) For example, the run-time
system will check the value of each index into month_days to make sure that it is
between 0 and 11 inclusive. If you try to access elements outside the range of the array
(negative numbers or numbers greater than the length of the array), you will cause a runtime
error.
Here is one more example that uses a one-dimensional array. It finds the average of a
set of numbers.
// Average an array of values.
fclass Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will see, there
are a couple of subtle differences. To declare a multidimensional array variable, specify
each additional index using another set of square brackets. For example, the following
declares a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int. Conceptually, this array will look like the one shown in Figure
The following program numbers each element in the array from left to right, top to bottom,
and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
separately. For example, this following code allocates memory for the first dimension of
twoD when it is declared. It allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this
situation, there may be in others. For example, when you allocate dimensions manually,
you do not need to allocate the same number of elements for each dimension. As stated
earlier, since multidimensional arrays are actually arrays of arrays, the length of each
array is under your control. For example, the following program creates a twodimensional
array in which the sizes of the second dimension are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; jtwoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; jSystem.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
1 2
3 4 5
6 7 8 9
The array created by this program looks like this:
The use of uneven (or, irregular) multidimensional arrays is not recommended for most
applications, because it runs contrary to what people expect to find when a
multidimensional array is encountered. However, it can be used effectively in some
situations. For example, if you need a very large two-dimensional array that is sparsely
populated (that is, one in which not all of the elements will be used), then an irregular
array might be a perfect solution.
It is possible to initialize multidimensional arrays. To do so, simply enclose each
dimension's initializer within its own set of curly braces. The following program creates a
matrix where each element contains the product of the row and column indexes. Also
notice that you can use expressions as well as literal values inside of array initializers.
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0
As you can see, each row in the array is initialized as specified in the initialization lists.
Let's look at one more example that uses a multidimensional array. The following
program creates a 3 by 4 by 5, three-dimensional array. It then loads each element with
the product of its indexes. Finally, it displays these products.
// Demonstrate a three-dimensional array.
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
This program generates the following output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array
variable. For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form is included mostly as a convenience.
A Few Words About Strings
As you may have noticed, in the preceding discussion of data types and arrays there has
been no mention of strings or a string data type. This is not because Java does not
support such a type—it does. It is just that Java's string type, called String, is not a
simple type. Nor is it simply an array of characters (as are strings in C/C++). Rather,
String defines an object, and a full description of it requires an understanding of several
object-related features. As such, it will be covered later in this book, after objects are
described. However, so that you can use simple strings in example programs, the
following brief introduction is in order.
The String type is used to declare string variables. You can also declare arrays of
strings. A quoted string constant can be assigned to a String variable. A variable of type
String can be assigned to another variable of type String. You can use an object of type
String as an argument to println( ). For example, consider the following fragment:
String str = "this is a test";
System.out.println(str);
Here, str is an object of type String. It is assigned the string "this is a test". This string is
displayed by the println( ) statement.
As you will see later, String objects have many special features and attributes that make
them quite powerful and easy to use. However, for the next few chapters, you will be using
them only in their simplest form.
A Note to C/C++ Programmers About Pointers
If you are an experienced C/C++ programmer, then you know that these languages provide
support for pointers. However, no mention of pointers has been made in this chapter. The
reason for this is simple: Java does not support or allow pointers. (Or more properly, Java
does not support pointers that can be accessed and/or modified by the programmer.) Java
cannot allow pointers, because doing so would allow Java applets to breach the firewall
between the Java execution environment and the host computer. (Remember, a pointer
can be given any address in memory—even addresses that might be outside the Java runtime
system.) Since C/C++ make extensive use of pointers, you might be thinking that their
loss is a significant disadvantage to Java. However, this is not true. Java is designed in
such a way that as long as you stay within the confines of the execution environment, you
will never need to use a pointer, nor would there be any benefit in using one. For tips on
converting C/C++ code to Java, including pointers, see Chapter 28.
The operands of the arithmetic operators must be of a numeric type. You cannot use
them on boolean types, but you can use them on char types, since the char type in Java
is, essentially, a subset of int.

Saturday, September 6, 2008

java I unit

Object-Oriented Programming
Object-oriented programming is at the core of Java. In fact, all Java programs are objectoriented
—this isn't an option the way that it is in C++, for example. OOP is so integral to
Java that you must understand its basic principles before you can write even simple Java
programs. Therefore, this chapter begins with a discussion of the theoretical aspects of
OOP.
Two Paradigms
As you know, all computer programs consist of two elements: code and data.
Furthermore, a program can be conceptually organized around its code or around its
data. That is, some programs are written around "what is happening" and others are
written around "who is being affected." These are the two paradigms that govern how a
program is constructed. The first way is called the process-oriented model. This approach
characterizes a program as a series of linear steps (that is, code). The process-oriented
model can be thought of as code acting on data. Procedural languages such as C employ
this model to considerable success. However, as mentioned in Chapter 1, problems with
this approach appear as programs grow larger and more complex.
To manage increasing complexity, the second approach, called object-oriented
programming, was conceived. Object-oriented programming organizes a program around
its data (that is, objects) and a set of well-defined interfaces to that data. An objectoriented
program can be characterized as data controlling access to code. As you will
see, by switching the controlling entity to data, you can achieve several organizational
benefits.
Abstraction
An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction. For example, people do not think of a car as a set of tens
of thousands of individual parts. They think of it as a well-defined object with its own
unique behavior. This abstraction allows people to use a car to drive to the grocery store
without being overwhelmed by the complexity of the parts that form the car. They can
ignore the details of how the engine, transmission, and braking systems work. Instead
they are free to utilize the object as a whole.
A powerful way to manage abstraction is through the use of hierarchical classifications.
This allows you to layer the semantics of complex systems, breaking them into more
manageable pieces. From the outside, the car is a single object. Once inside, you see
that the car consists of several subsystems: steering, brakes, sound system, seat belts,
heating, cellular phone, and so on. In turn, each of these subsystems is made up of more
specialized units. For instance, the sound system consists of a radio, a CD player, and/or
a tape player. The point is that you manage the complexity of the car (or any other
complex system) through the use of hierarchical abstractions.
Hierarchical abstractions of complex systems can also be applied to computer programs.
The data from a traditional process-oriented program can be transformed by abstraction
into its component objects. A sequence of process steps can become a collection of
messages between these objects. Thus, each of these objects describes its own unique
behavior. You can treat these objects as concrete entities that respond to messages
telling them to do something. This is the essence of object-oriented programming.
Object-oriented concepts form the heart of Java just as they form the basis for human
understanding. It is important that you understand how these concepts translate into
programs. As you will see, object-oriented programming is a powerful and natural
paradigm for creating programs that survive the inevitable changes accompanying the life
cycle of any major software project, including conception, growth, and aging. For
example, once you have well-defined objects and clean, reliable interfaces to those
objects, you can gracefully decommission or replace parts of an older system without
fear.
The Three OOP Principles
All object-oriented programming languages provide mechanisms that help you implement
the object-oriented model. They are encapsulation, inheritance, and polymorphism. Let's
take a look at these concepts now.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about
encapsulation is as a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper. Access to the code and
data inside the wrapper is tightly controlled through a well-defined interface. To relate this
to the real world, consider the automatic transmission on an automobile. It encapsulates
hundreds of bits of information about your engine, such as how much you are
accelerating, the pitch of the surface you are on, and the position of the shift lever. You,
as the user, have only one method of affecting this complex encapsulation: by moving the
gear-shift lever. You can't affect the transmission by using the turn signal or windshield
wipers, for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface
to the transmission. Further, what occurs inside the transmission does not affect objects
outside the transmission. For example, shifting gears does not turn on the headlights!
Because an automatic transmission is encapsulated, dozens of car manufacturers can
implement one in any way they please. However, from the driver's point of view, they all
work the same. This same idea can be applied to programming. The power of
encapsulated code is that everyone knows how to access it and thus can use it
regardless of the implementation details—and without fear of unexpected side effects.
In Java the basis of encapsulation is the class. Although the class will be examined in
great detail later in this book, the following brief discussion will be helpful now. A class
defines the structure and behavior (data and code) that will be shared by a set of objects.
Each object of a given class contains the structure and behavior defined by the class, as
if it were stamped out by a mold in the shape of the class. For this reason, objects are
sometimes referred to as instances of a class. Thus, a class is a logical construct; an
object has physical reality.
When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class. Specifically, the data
defined by the class are referred to as member variables or instance variables. The code
that operates on that data is referred to as member methods or just methods. (If you are
familiar with C/C++, it may help to know that what a Java programmer calls a method, a
C/C++ programmer calls a function.) In properly written Java programs, the methods
define how the member variables can be used. This means that the behavior and
interface of a class are defined by the methods that operate on its instance data.
Since the purpose of a class is to encapsulate complexity, there are mechanisms for
hiding the complexity of the implementation inside the class. Each method or variable in a
class may be marked private or public. The public interface of a class represents
everything that external users of the class need to know, or may know. The private
methods and data can only be accessed by code that is a member of the class.
Therefore, any other code that is not a member of the class cannot access a private
method or variable. Since the private members of a class may only be accessed by other
parts of your program through the class' public methods, you can ensure that no
improper actions take place. Of course, this means that the public interface should be
carefully designed not to expose too much of the inner workings of a class (see Figure 2-
1).
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification. As
mentioned earlier, most knowledge is made manageable by hierarchical (that is, topdown)
classifications. For example, a Golden Retriever is part of the classification dog,
which in turn is part of the mammal class, which is under the larger class animal. Without
the use of hierarchies, each object would need to define all of its characteristics explicitly.
However, by use of inheritance, an object need only define those qualities that make it
unique within its class. It can inherit its general attributes from its parent. Thus, it is the
inheritance mechanism that makes it possible for one object to be a specific instance of a
more general case. Let's take a closer look at this process.
Most people naturally view the world as made up of objects that are related to each other
in a hierarchical way, such as animals, mammals, and dogs. If you wanted to describe
animals in an abstract way, you would say they have some attributes, such as size,
intelligence, and type of skeletal system. Animals also have certain behavioral aspects;
they eat, breathe, and sleep. This description of attributes and behavior is the class
definition for animals.
If you wanted to describe a more specific class of animals, such as mammals, they would
have more specific attributes, such as type of teeth, and mammary glands. This is known
as a subclass of animals, where animals are referred to as mammals' superclass.
Since mammals are simply more precisely specified animals, they inherit all of the
attributes from animals. A deeply inherited subclass inherits all of the attributes from each
of its ancestors in the class hierarchy.
Inheritance interacts with encapsulation as well. If a given class encapsulates some
attributes, then any subclass will have the same attributes plus any that it adds as part of
its specialization (see Figure 2-2). This is a key concept which lets object-oriented
programs grow in complexity linearly rather than geometrically. A new subclass inherits
all of the attributes of all of its ancestors. It does not have unpredictable interactions with
the majority of the rest of the code in the system.
Polymorphism
Polymorphism (from the Greek, meaning "many forms") is a feature that allows one
interface to be used for a general class of actions. The specific action is determined by
the exact nature of the situation. Consider a stack (which is a last-in, first-out list). You
might have a program that requires three types of stacks. One stack is used for integer
values, one for floating-point values, and one for characters. The algorithm that
implements each stack is the same, even though the data being stored differs. In a non–
object-oriented language, you would be required to create three different sets of stack
routines, with each set using different names. However, because of polymorphism, in
Java you can specify a general set of stack routines that all share the same names.
More generally, the concept of polymorphism is often expressed by the phrase "one
interface, multiple methods." This means that it is possible to design a generic interface
to a group of related activities. This helps reduce complexity by allowing the same
interface to be used to specify a general class of action. It is the compiler's job to select
the specific action (that is, method) as it applies to each situation. You, the programmer,
do not need to make this selection manually. You need only remember and utilize the
general interface.
Extending the dog analogy, a dog's sense of smell is polymorphic. If the dog smells a cat,
it will bark and run after it. If the dog smells its food, it will salivate and run to its bowl. The
same sense of smell is at work in both situations. The difference is what is being smelled,
that is, the type of data being operated upon by the dog's nose! This same general
concept can be implemented in Java as it applies to methods within a Java program.
Polymorphism, Encapsulation, and Inheritance Work Together
When properly applied, polymorphism, encapsulation, and inheritance combine to
produce a programming environment that supports the development of far more robust
and scaleable programs than does the process-oriented model. A well-designed
hierarchy of classes is the basis for reusing the code in which you have invested time and
effort developing and testing. Encapsulation allows you to migrate your implementations
over time without breaking the code that depends on the public interface of your classes.
Polymorphism allows you to create clean, sensible, readable, and resilient code.
Of the two real-world examples, the automobile more completely illustrates the power of
object-oriented design. Dogs are fun to think about from an inheritance standpoint, but
cars are more like programs. All drivers rely on inheritance to drive different types
(subclasses) of vehicles. Whether the vehicle is a school bus, a Mercedes sedan, a
Porsche, or the family minivan, drivers can all more or less find and operate the steering
wheel, the brakes, and the accelerator. After a bit of gear grinding, most people can even
manage the difference between a stick shift and an automatic, because they
fundamentally understand their common superclass, the transmission.
People interface with encapsulated features on cars all the time. The brake and gas
pedals hide an incredible array of complexity with an interface so simple you can operate
them with your feet! The implementation of the engine, the style of brakes, and the size of
the tires have no effect on how you interface with the class definition of the pedals.
The final attribute, polymorphism, is clearly reflected in the ability of car manufacturers to
offer a wide array of options on basically the same vehicle. For example, you can get an
antilock braking system or traditional brakes, power or rack-and-pinion steering, 4-, 6-, or
8-cylinder engines. Either way, you will still press the break pedal to stop, turn the
steering wheel to change direction, and press the accelerator when you want to move.
The same interface can be used to control a number of different implementations.
As you can see, it is through the application of encapsulation, inheritance, and
polymorphism that the individual parts are transformed into the object known as a car.
The same is also true of computer programs. By the application of object-oriented
principles, the various parts of a complex program can be brought together to form a
cohesive, robust, maintainable whole.
As mentioned at the start of this section, every Java program is object-oriented. Or, put
more precisely, every Java program involves encapsulation, inheritance, and
polymorphism. Although the short example programs shown in the rest of this chapter and
in the next few chapters may not seem to exhibit all of these features, they are
nevertheless present. As you will see, many of the features supplied by Java are part of its
built-in class libraries, which do make extensive use of encapsulation, inheritance, and
polymorphism.
A First Simple Program
Now that the basic object-oriented underpinning of Java has been discussed, let's look at
some actual Java programs. Let's start by compiling and running the short sample
program shown here. As you will see, this involves a little more work than you might
imagine.
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
Note
The descriptions that follow use the standard JDK (Java Developer's Kit),
which is available from Sun Microsystems. If you are using a different Java
development environment, then you may need to follow a different procedure
for compiling and executing Java programs. In this case, consult your
compiler's user manuals for details.
Entering the Program
For most computer languages, the name of the file that holds the source code to a
program is arbitrary. However, this is not the case with Java. The first thing that you must
learn about Java is that the name you give to a source file is very important. For this
example, the name of the source file should be Example.java. Let's see why.
In Java, a source file is officially called a compilation unit. It is a text file that contains one
or more class definitions. The Java compiler requires that a source file use the .java
filename extension. Notice that the file extension is four characters long. As you might
guess, your operating system must be capable of supporting long filenames. This means
that DOS and Windows 3.1 are not capable of supporting Java (at least at this time).
However, Windows 95/98 and Windows NT work just fine.
As you can see by looking at the program, the name of the class defined by the program
is also Example. This is not a coincidence. In Java, all code must reside inside a class.
By convention, the name of that class should match the name of the file that holds the
program. You should also make sure that the capitalization of the filename matches the
class name. The reason for this is that Java is case-sensitive. At this point, the
convention that filenames correspond to class names may seem arbitrary. However, this
convention makes it easier to maintain and organize your programs.
Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the name of
the source file on the command line, as shown here:
C:\\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode
version of the program. As discussed earlier, the Java bytecode is the intermediate
representation of your program that contains instructions the Java interpreter will
execute. Thus, the output of javac is not code that can be directly executed.
To actually run the program, you must use the Java interpreter, called java. To do so,
pass the class name Example as a command-line argument, as shown here:
C:\\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
When Java source code is compiled, each individual class is put into its own output file
named after the class and using the .class extension. This is why it is a good idea to give
your Java source files the same name as the class they contain—the name of the source
file will match the name of the .class file. When you execute the Java interpreter as just
shown, you are actually specifying the name of the class that you want the interpreter to
execute. It will automatically search for a file by that name that has the .class extension.
If it finds the file, it will execute the code contained in the specified class.
A Closer Look at the First Sample Program
Although Example.java is quite short, it includes several key features which are common
to all Java programs. Let's closely examine each part of the program.
The program begins with the following lines:
/*
This is a simple Java program.
Call this file "Example.java".
*/
This is a comment. Like most other programming languages, Java lets you enter a
remark into a program's source file. The contents of a comment are ignored by the
compiler. Instead, a comment describes or explains the operation of the program to
anyone who is reading its source code. In this case, the comment describes the program
and reminds you that the source file should be called Example.java. Of course, in real
applications, comments generally explain how some part of the program works or what a
specific feature does.
Java supports three styles of comments. The one shown at the top of the program is
called a multiline comment. This type of comment must begin with /* and end with */.
Anything between these two comment symbols is ignored by the compiler. As the name
suggests, a multiline comment may be several lines long.
The next line of code in the program is shown here:
class Example {
This line uses the keyword class to declare that a new class is being defined. Example
is an identifier that is the name of the class. The entire class definition, including all of its
members, will be between the opening curly brace ({) and the closing curly brace (}). The
use of the curly braces in Java is identical to the way they are used in C and C++. For the
moment, don't worry too much about the details of a class except to note that in Java, all
program activity occurs within one. This is one reason why all Java programs are (at least
a little bit) object-oriented.
The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
This is the second type of comment supported by Java. A single-line comment begins
with a // and ends at the end of the line. As a general rule, programmers use multiline
comments for longer remarks and single-line comments for brief, line-by-line descriptions.
The next line of code is shown here:
public static void main(String args[]) {
This line begins the main( ) method. As the comment preceding it suggests, this is the
line at which the program will begin executing. All Java applications begin execution by
calling main( ). (This is just like C/C++.) The exact meaning of each part of this line
cannot be given now, since it involves a detailed understanding of Java's approach to
encapsulation. However, since most of the examples in the first part of this book will use
this line of code, let's take a brief look at each part now.
The public keyword is an access specifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then that
member may be accessed by code outside the class in which it is declared. (The
opposite of public is private, which prevents a member from being used by code defined
outside of its class.) In this case, main( ) must be declared as public, since it must be
called by code outside of its class when the program is started. The keyword static
allows main( ) to be called without having to instantiate a particular instance of the class.
This is necessary since main( ) is called by the Java interpreter before any objects are
made. The keyword void simply tells the compiler that main( ) does not return a value.
As you will see, methods may also return values. If all this seems a bit confusing, don't
worry. All of these concepts will be discussed in detail in subsequent chapters.
As stated, main( ) is the method called when a Java application begins. Keep in mind
that Java is case-sensitive. Thus, Main is different from main. It is important to
understand that the Java compiler will compile classes that do not contain a main( )
method. But the Java interpreter has no way to run these classes. So, if you had typed
Main instead of main, the compiler would still compile your program. However, the Java
interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified
within the set of parentheses that follow the name of the method. These variables are
called parameters. If there are no parameters required for a given method, you still need
to include the empty parentheses. In main( ), there is only one parameter, albeit a
complicated one. String args[ ] declares a parameter named args, which is an array of
instances of the class String. (Arrays are collections of similar objects.) Objects of type
String store character strings. In this case, args receives any command-line arguments
present when the program is executed. This program does not make use of this
information, but other programs shown later in this book will.
The last character on the line is the {. This signals the start of main( )'s body. All of the
code that comprises a method will occur between the method's opening curly brace and
its closing curly brace.
One other point: main( ) is simply a starting place for the interpreter. A complex program
will have dozens of classes, only one of which will need to have a main( ) method to get
things started. When you begin creating applets—Java programs that are embedded in
Web browsers—you won't use main( ) at all, since the Web browser uses a different
means of starting the execution of applets.
The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("This is a simple Java program.");
This line outputs the string "This is a simple Java program." followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method. In this case,
println( ) displays the string which is passed to it. As you will see, println( ) can be used
to display other types of information, too. The line begins with System.out. While too
complicated to explain in detail at this time, briefly, System is a predefined class that
provides access to the system, and out is the output stream that is connected to the
console.
As you have probably guessed, console output (and input) is not used frequently in real
Java programs and applets. Since most modern computing environments are windowed
and graphical in nature, console I/O is used mostly for simple, utility programs and for
demonstration programs. Later in this book, you will learn other ways to generate output
using Java. But for now, we will continue to use the console I/O methods.
Notice that the println( ) statement ends with a semicolon. All statements in Java end
with a semicolon. The reason that the other lines in the program do not end in a
semicolon is that they are not, technically, statements.
The first } in the program ends main( ), and the last } ends the Example class definition.



Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred. This article is a companion piece to this month's Design Techniques installment, which discusses how to use exceptions appropriately in your programs and designs. Look to this companion article for a tutorial on the nuts and bolts of what exceptions are and how they work in the Java language and virtual machine.
When a method encounters an abnormal condition (an exception condition) that it can't handle itself, it may throw an exception. Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem that can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem will be dealt with. Exceptions are caught by handlers positioned along the thread's method invocation stack. If the calling method isn't prepared to catch the exception, it throws the exception up to its calling method, and so on. If one of the threads of your program throws an exception that isn't caught by any method along the method invocation stack, that thread will expire. When you program in Java, you must position catchers (the exception handlers) strategically, so your program will catch and handle all exceptions from which you want your program to recover.
Exception classes
In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. A small part of this family is shown in Figure 1.
As you can see in Figure 1, Throwable has two direct subclasses, Exception and Error. Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread. Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.
Figure 1. A partial view of the Throwable family
In addition to throwing objects whose classes are declared in java.lang, you can throw objects of your own design. To create your own class of throwable objects, you need only declare it as a subclass of some member of the Throwable family. In general, however, the throwable classes you define should extend class Exception. They should be "exceptions." The reasoning behind this rule will be explained later in this article.
Whether you use an existing exception class from java.lang or create one of your own depends upon the situation. In some cases, a class from java.lang will do just fine. For example, if one of your methods is invoked with an invalid argument, you could throw IllegalArgumentException, a subclass of RuntimeException in java.lang.
·