Tải bản đầy đủ - 0 (trang)
Chapter 1. What Can Java Do for Me?

Chapter 1. What Can Java Do for Me?

Tải bản đầy đủ - 0trang

WhatJavaDoesforYou:SoftwarePortability

Whatismeantby"applicationsthatareindependentofall

hardwareandoperatingsystems?"Itmeansyoucancompilea

Javaprogramonanysystemandruntheresultingbinary

executablefileonthesameoranyothersystemonaMacintosh,

onWindows98,NT,2K,XP,onSolaris,Linux,BSDoranyofthe

varietiesofUnix,onIBM'smainframeoperatingsystems,oncell

phones,PersonalDigitalAssistants(PDAs),embedded

processors,andevenonsmartcards(creditcardswitha

microprocessorandmemory),asshowninFigure1-1.



Figure1-1.Future-proofsoftware:YourJava

applicationrunsoneverysystem.Nomore

"requiresWindowsXP"or"LinuxPPConly",or

"compiledforMacOSXversion10.5";just"built

withJava,"andyou'redone.



[Viewfullsizeimage]



Youwillevenbeabletorunonfutureoperatingsystem

releases,likeMicrosoft'sLonghorn.Javawillbeportedtoall

futureoperatingsystemsofsignificance.It'salsoafastwayfor

newhardwaretogetsoftwareapplicationsthatwillrunonit.

JavaunlockssoftwarefrombeingcoupledtoanyspecificOS

andhardwareplatform.ThisnewflexibilityhasmadeJavavery

popularwithusers,ITdepartments,andsoftwarevendors.All

threebenefitenormouslyfromsoftwareportability.



WhyPortabilityMatters

Youmightthinkthatsoftwareportabilitydoesnotaffectyou:

yourapplicationsoftwarerunsfineonyourPCtodayandthat's

allyouuse.Andthat'strue,rightupuntilthetimeyouwantto

consideranewordifferentsystem.

Sayyou'reinthemarkettobuyanewdesktopsystem,anda

friendshowsyouthevideo-editing,music,virusresistance,and

digitalpicturecapabilitiesofhisAppleMacintosh.Youconsider

switchingtoaMac.SwitchingGUIsisano-brainerGUIsalldo

essentiallythesamethings,anditonlytakesadayortwoto

re-trainyourfingers.Theproblemistheapps.Youarefaced

withthe"choice"ofwalkingawayfromyourinvestmentinyour

existingPC-onlysoftware,orbuyingyetanotherWindowsPC

thathassomecompatibilitywithyourprevioussystem.Youcan

easilyswitchhardwarefromDelltoH-PorIBM,butthere'sa

softwarebarriertoswitchingfromWindowstosomethingwith

fewersecurityproblems,likeLinuxorMacOS.You'vebeen

lockedin.

WhenyourapplicationprogramsarewritteninJava,youcan

upgradeOSandapplicationsindependently.YoucantryLinux

andstilluseyourfamiliarapplications.Youcanmoveyour

existingJavaprogramstoanynewsystem,andcarryonusing

them.Thisiswhysoftwareportabilitymatterstohomeusers.

Forbusinesses,theproblemisworseandfarmoreexpensive.

Evenifyourwholeorganizationhasstandardizedon,say,

MicrosoftWindowsXP,therehavebeennumerousreleasesover

justthelastdecadeandabit:MS-DOS,Win3.1,Win3.11,

Win95A,Win95B,Win98,98SE,ME,NT3.1,NT3.5,NT3.51,

NT4,2K,multipleservicepacksandrequiredhot-fixes,XP,and

Longhornonthehorizon.Theseplatformshavesubtleand

differentincompatibilitiesamongthem.Evenapplications

runningonasingleplatformhavelimitedinteroperability.Older



versionsofMicrosoftOfficecannotreadfilesproducedby

defaultfromthelatestMicrosoftOffice,evenwhenthefiles

don'tuseanyofthenewfeatures.

Thisisdonedeliberately,toforceupgrades.Ifevenoneperson

inanofficeupgrades,everyonehasto(orriskbeingcutoff

fromreadingnewfiles).

Softwareportabilityisallabout"future-proofing"yoursoftware

investment.RewriteitinJava,andthat'sthelastportyou'll

everneedtodo.PortabilityistheHolyGrailofthesoftware

industry.Ithaslongbeensought,butneverbeforeattained.

Javabringstheindustryclosertotruesoftwareportabilitythan

anyprevioussystemhas.



Softwareportabilityforofficeapplications

ThereistodayanexcellentalternativetocostlyandincompatibleMSOffice

updates.YoucandownloadthefreeOpenOffice.orgsoftwareanduseitinsteadof

MSOffice.

MSOfficeProfessionalEdition2003costs$499intheUSAforthebasic

productforonecomputer.OpenOffice.orghasthesamelookandfeatures,andis

freeforanynumberofcomputers.OpenOffice.orgcanreadandsavefilesinMS

Officeformats.Youcanevengetthesourcecode.Overtwentymillionusers

havedownloadedit,andyoucangetyourcopyat:

www.openoffice.org



ThereareOpenOffice.orgversionsavailableforLinux,Windows,

MacOS,andSolaris,inmanydifferentnationallanguages.

OpenOffice.orgisnotwritteninJava,soitneedsanexecutable

foreachplatform.OpenOffice.org(likeJava)isbasedonsource

codemadefreelyavailablefromSun.Thereisaprogrammers

guideandSDKat

http://www.openoffice.org/dev_docs/source/sdk/



Javaandjobs

Softwareportabilityhasawonderfulside-effect:skills

portabilityforprogrammers.Manycompaniestodayareoutsourcingprogrammingjobstocountrieswithlowdirectlabor

costs.It'sashort-termcost-savingthatlooksgoodonpaper,

untilyoulookatthewiderimplications.

ThebeneficiariesofjobsexportedfromtheWestareAsian

countrieswithpoorperformanceintheannualglobalsurveyof

corruption(seewww.transparency.org).It'sariskylong-term

bettomovestrategicexpertisetocountriesthatcombine



widespreadcorruption,unprovenbusinessprivacyand

intellectualpropertylaws,withscantfreemarketexperience,

andnoeffectiveenvironmentalorworkplaceregulation.The

biggerpictureneedstobethoughtthroughwhenchoosingto

exportjobsandassetsfromourhomeeconomies.Aspeople

withastakeinthecomputerindustry,wehaveadutytomake

ourviews(whatevertheyare)knowntopoliticians.

Lookingatthisanotherway,China(anationof1.3billion)has

alreadystandardizedonLinux,andIndia(1billionpeople)is

reviewingit.Javaofferstheonlyviablewaytocreatesoftware

targetedatboththeWestandatemergingmarkets.

Ifyou'reaprogrammerintheUSAorWesternEuropeaffected

byjobsmovingoffshore,Javaisabigplusforyourcareer.

EmployersusedtoadvertiseforveryspecifichardwareandOS

experience("musthave2yearsofMVSonOS/390")andignore

otherresumes.Today,yourJavaexperiencegainedonanyOS

isdirectlytransferabletootherhardwareandjobs.

Javaisindemandbyemployers.AnApril2004reviewofoneof

theUS'slargestjobsitesreflectedthesehiringneeds.

Microsoft'sC#wasmentionedinabout1400postings,while

C++wasarequirementinabout4000postings.That'swhat

youwouldexpect.C++ismuchmorewidespreadthanC#,and

runsonmanymorecomputers.ButJavawasasurprise:more

than6800postingssoughtJavaskills.Moreemployerswanted

JavaexperiencethanthosewhowantedC++andC#combined.

Thisisjustananecdotaldatapoint,butitisconsistentwith

othersurveys.TheSoftwareDevelopmentTimespaperreported

inDecember2003thatnearlythree-quartersofenterprise

softwaredevelopmentmanagersareusingJavaandanother

11%plantostartinthenextyear.Investingsomeofyourtime

inJavaisgoodforyourcareer.



JavaandMicrosoft



JavaportabilityposesarealthreattoMicrosoft'smonopoly.

Softwarethatcanrunonanyoperatingsystemhasalarger

marketthansoftwarethatislimitedtoWindowsonly.Overtime

ISVswillmovetheirproductsawayfromWindows-onlyto

JavaunlessJavacansomehowbespoiledorbroken.

Itisunfortunateforyou,me,andallcomputerusersthat

MicrosoftusesitsmonopolytotrytoundermineJava.Atfirst,

MicrosoftintroduceddeliberateincompatibilitiesintotheJava

productitlicensedfromSun.Microsoftpaid$20MtoSunto

settletheresultingcourtcase.InApril2004,MicrosoftpaidSun

afurther$1.9billiontosettleSun'slitigationoverother

monopolyabuse.

ThecurrentMicrosoftplanistopushtheC#language,whichis

Microsoft'sbarelydifferentcopyofJava.ButthecoreC#

librarieswillbeonlyeverbeavailableonWindows(there'san

opensourceefforttoduplicatesomeC#librariesonLinux,but

fewbelieveitwillleadanywhere).TheC#initiativewilllastonly

untilRedmondwantstopushtheNextIncompatibleBigThing.

Javaisshapedbythecomputerindustryasawhole,andwillbe

arounduntilindustryreachesconsensusthatthereissomething

bettertoreplaceJava.



LanguageandLibraries

Let'sspendaminutetoreviewsomesoftwaretermsthatare

oftentakenforgranted.Ifyouarealreadyfamiliarwiththis,

justskipaheaduntilyoureachsomethingnew.Theterminology

isspelledoutindetailheretogiveasolidbasisforthematerial

thatfollowsintherestofthebook.



Whatalanguageis

Whenpeopletalkabouta"programminglanguage",theymean

thingslike:

Howthelanguagedescribesdata,

Thestatementsthatworkondata,and

Thewaysthetwocanbeputtogether.Thesetofrules

describinghowyoucanputtogetherprogramsinthe

languageiscalledagrammar.Thegrammarfora

programminglanguageiswritteninmathematicallanguage,

anditdefineshowexpressionsareformed,what

statementslooklike,andsoon.We'llstayawayfrom

mathematicsandexplainthingsinEnglish.

Javaisaprogramminglanguageinthesamepartofthe

languagesfamilytreeasC++,Pascal,orBasic.Javaadopts

ideasfromnon-mainstreamlanguageslikeSmalltalkandLisp,

too.Javaisastronglytypedlanguage,meaningthatthe

compilerstrictlychecksoperationsandwillonlyallowthosethat

arevalidforthattypeofoperand(youcan'tmultiplytwo

characterstrings,butyoumayappendthem)Javaisobjectoriented,meaningthatthedatadeclarationsareveryclosely



tiedtothestatementsthatoperateonthedata.Object-oriented

meansmorethanjusttyingdatatostatements,andweexpand

onthatinchapters2and5.

Statementsaregroupedintowhatotherlanguagescall

functions,procedures,orsubroutines.Inanobject-oriented

language,wecallthefunctionsmethodsastheyarethemethod

orwaytoprocesssomedata.Methodscancallothermethods

andcanberecursive(callthemselves).Programexecution

beginsinamethodwiththespecialnamemain().Statements

inJavalooksimilartostatementsinmanyotherhigh-level

languages.HerearesomeexamplesofJavastatements:



y=y+1;

if(isLeapYear(y))//thisisacomment

febDays=29;

elsefebDays=28;



AlthoughJavaaddssomenewthings,itisequallynotablefor

whatisleftout.ThedesignerofC++oncewrote,"WithinC++,

thereisamuchsmallerandcleanerlanguagestrugglingtoget

out,"(BjarneStroustrup,TheDesignandEvolutionofC++,

Addison-Wesley,1994:207).Ofthepeoplewhoagreewiththat

propheticstatement,manythinkthatthenameofthatsmaller



andcleanerlanguageisJava.

Javahaseightbasicorprimitivedatatypes,suchasintegers,

characters,andfloating-pointnumbers.Alldataisrepresented

asoneoftheseeightbuilt-inelementarytypes,orasanobject

orarraymadeupofthesetypes.Thesizeofeachtypeislaid

downinthelanguageandisthesameonallplatforms.Hereare

someotherJavalanguagefeaturesthatwillbecoveredinlater

chapters:

Threads.Threadsletasingleprogramdomorethanone

thingatonce,justastimesharingletsacomputersystem

runmorethanoneprogramatonce.

Exceptions.Exceptionshelpaprogrammerdealwitherror

conditionswhenmostconvenient,insteadofclutteringup

themainflowofcontrolwithlotsofcheckinganderrorhandlingcode.

Garbagecollection.Withgarbagecollection,therun-time

library,nottheprogrammer,managestheuseofdynamic

storageandreclaims(frees)memorythatisnolongerin

useinaprogram.

Aprogramminglanguagetypicallyhasaspecification,whichis

aweightydocumentsayingwhattheexpressions,statements,

andtheirvariousgroupingsactuallymean.Thatis,what

changesinmemoryorcontrolflowwilloccurwhenan

expressionisevaluatedorastatementisexecuted.Thisis

termedthesemanticsofthelanguage.Thefirsthalfofthis

book,uptoChapter15,explainsthefeaturesandmeaning

(semantics)oftheJavalanguage.Don'tworrythechaptersare

shortandwellorganized.

SunhaspublishedaJavaLanguageSpecification(JLS).Itis

writtenmostlyforanaudienceofcompilerimplementors,andis



notintendedasatutorialforprogrammers(that'swhatthis

bookisfor).ButitcanbefuntodipintotheJLSanywaywhen

youwanttoplaylanguagelawyerorresolveatrickyquestion,

andyoucanfinditonlineat

http://java.sun.com/docs/books/jls/index.html.



Whatalibraryis

Earlyinthehistoryofprogramming,peoplerealizedthatsome

routineswereneededoverandoveragainindifferent

programs.Itmakessensetomovefrequentlyreusedcodeinto

aseparatefileorlibrarythatallprogramscanshare.Thekind

ofcodethatbelongsinalibraryarethingslikecodetoopena

file,orreadinablockofbytes,orgetthecurrenttimestamp

fromtheoperatingsystem.

Alibraryisnotanexecutableprograminitsownright.It

containsexecutablecodethatisbroughtintoyourprogram's

addressspace,whenyourprogramcallsaroutineinthelibrary.

Theworkoffindingtherightlibraryandloadingitscodeinto

yourprocessmemoryatrun-timeiscalleddynamiclinkingand

it'sanimportantfeatureofJava."Dynamic"incompiler

terminologyjustmeans"isdoneatrun-time",andcontrasts

with"static"meaning"doneatcompiletime".

Theentiresetofroutinesinalibrary(theroutinenames,what

theycanreturn,andtheparametertypes)isknownasthe

ApplicationProgrammingInterface,orAPI.Modernlanguages

checkthatthecallstoalibraryareconsistentwiththeAPIof

thelibraryimplementation.Thecheckingneedstobedone

twice:atcompiletimetocatchanymismatchesasearlyas

possible,andatrun-timetoconfirmthatnothinghaschanged.

Sothecompilerandtherun-timeenvironmentbothneedto

knowwheretofindtheapplicationlibraries.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 1. What Can Java Do for Me?

Tải bản đầy đủ ngay(0 tr)

×