You are on page 1of 8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

C#VersusJava
SourceCodeAccompaniesThisArticle.DownloadItNow.

csharpj.txt

MicrosoftdescribesC#("Csharp")asa"simple,modern,objectoriented,andtypesafeprogramminglanguagederivedfromCand
C++."ThatstatementwouldapplyequallywelltoJava.Infact,aftercomparingthetwolanguages,it'sobviousthatprerelease
descriptionsofC#resembleJavamorethanC++.AsExample1illustrates,thelanguagefeaturesandsyntaxaresimilar.Example1(a)is
thecanonical"HelloWorld"programinJava,whileExample1(b)istheprograminC#.
February01,2001
URL:http://www.drdobbs.com/windows/cversusjava/184404487

Dowereallyneedanotherlanguage?
MarcisaprojectleaderdevelopingrealtimestockmarketapplicationsatILXSystems.Hecanbecontactedatme133@columbia.edu.
MicrosoftdescribesC#("Csharp")asa"simple,modern,objectoriented,andtypesafeprogramminglanguagederivedfromCandC++."Thatstatement
wouldapplyequallywelltoJava.Infact,aftercomparingthetwolanguages,it'sobviousthatprereleasedescriptionsofC#resembleJavamorethanC++.
AsExample1illustrates,thelanguagefeaturesandsyntaxaresimilar.Example1(a)isthecanonical"HelloWorld"programinJava,whileExample1(b)
istheprograminC#.
Buttheresemblancegoesbeyondsyntax,keywords,anddelimiters.ItalsoincludesfeaturesthatJavaandC#holdincommon,suchas:
Automaticgarbagecollection.
Reflectionfortypeinformationdiscovery.
Sourcecodeiscompiledtoanintermediatebytecode.
JustinTime(JIT)compilationcompilesbytecodeintonativecode.
Everythingmustbeinaclassnoglobalfunctionsordata.
Nomultipleinheritance,althoughyoucanimplementmultipleinterfaces.
AllclassesderivefromObject.
Securityforrestrictingaccesstoresources.
Exceptionsforerrorhandling.
Packages/namespacesforpreventingtypecollision.
Codecommentsasdocumentation.
Arraysareboundschecked.
GUI,networking,andthreadingsupport.
Nouninitializedvariables.
Nopointers.
Noheaderfiles.

C#:TheEvolutionofVisualJ++
WhydoesMicrosoftthinkweneedanotherlanguage?WhenMicrosoftintroducedVisualJ++inOctober1996,itthrewlotsofresourcesintotheproject.
TheireffortsproducedthefastestJVMonthemarketandtheWindowsFoundationClasses(WFC),asetofJavaclassesthatwrappedtheWin32API.Not
coincidentally,AndersHejlsberg,theprojectleaderforWFC(andmostfamousastheauthorofTurboPascal),isthechiefarchitectforC#.
MicrosoftdecidedtomakechangestoJavatointegrateitmorecloselywithWindows.SomeofthechangesinterfacingseamlesslywithCOM,refusing
tosupportRMIandJNI,andaddingdelegatescausedittobreakcompliancewiththeJavaStandard.Consequently,SunMicrosystemssuedMicrosoft
inOctober1997forviolatingitsJavalicenseagreement.ThisdoomedMicrosoft'sfuturedevelopmentofJavaandVisualJ++.However,Microsoft
decidedtotakeitsadvancesintheJavalanguage,Javacompiler,andJVMandmorphthemintoanevenmoreambitiousprojectMicrosoft.NET.

Microsoft.NET
http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

1/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

Theterm"Microsoft.NET"issimilarto"WindowsDNA"inthatitreferstomanythings:abusinessstrategy,developmentmodel,marketingpitch,
developmentplatform,andlanguageruntime.ButwhereasDNAismoreofa"bestpractice"approachtodevelopment,attheheartof.NETisthe
CommonLanguageRuntime(CLR),asetofoperatingsystemservicesandanexecutionenginethatprovidesruntimesupportfor.NETprograms.You
canthinkoftheCommonLanguageRuntimeasfulfillingthesameroleastheJavavirtualmachine.
ProgramswritteninC#arecompiledintoanintermediatelanguagecalled"MSIL,"theequivalenttoJavabytecodeorVisualBasicpcode.Anylanguage
thatcanbecompiledtoMSILcantakeadvantageoftheCLRfeaturessuchasgarbagecollection,reflection,metadata,versioning,events,andsecurity,to
nameafew.Inaddition,aclasswritteninonelanguagecanactuallyinheritfromaclasswritteninanotherlanguageandoverrideitsmethods.
AlthoughthisarticleisaboutC#,keepinmindthattheclasslibrariesandtheCLRfeaturesareusablebyanylanguagethathasanMSILcompiler.
Initially,MicrosoftwillprovideMSILcompilersforC#,VisualBasic,JScript,andManagedC++.Thirdpartyvendorshavealsodeveloped.NET
compilersforanumberoflanguages,including:Java(Rational),Eiffel(InteractiveSoftwareEngineeringandMonashUniversity),Perl(ActiveState),
Python(ActiveState),Scheme(NorthwesternUniversity),Smalltalk(QuasarKnowledgeSystems),Cobol(Fujitsu),ComponentPascal(Queensland
UniversityofTechnology),APL(Dyalog),StandardML(MicrosoftResearchCambridge),Mercury(UniversityofMelbourne),andOberon(ETH
Zentrum).
It'sinterestingthatMicrosoftispushingcrosslanguagedevelopmentwhileSun/Javapushescrossplatformdevelopment.
However,bothapproacheshavetheirshareofproblems.Writingcomponentsinmultiplelanguagesalwaysentailssomeinteroperabilityproblems.
Moreover,thereisalwaystheproblemofwhattodowhenyourSchemeprogrammermovesontogreenerpastures.Crossplatformdevelopmenthasalso
neverbeenflawless,asJavaprogrammerswellknow,especiallyintheareasofGUIsandthreading.

C#SimilaritiestoJava
Inadditiontosharinganumberoffeatures,mostofthekeywordsinJavahavetheirC#counterpart.Somekeywordsareidenticalforexample,new,bool,
this,break,static,class,throw,virtual,andnull.ThisisexpectedsincethesekeywordsarederivedfromC++.Interestingly,manykeywordsinJavathat
donothavedirectC++equivalentssuchassuper,import,package,synchronized,andfinal,havedifferentnamesinC#(base,using,namespace,lock,
andsealed,respectively).Table1summarizessomeofthekeywordsandfeaturesthatexistinbothlanguages,butlookslightlydifferentinC#.

TheObjectClass
AnothergoodexampleofcosmeticdifferencesistheSystem.ObjectclassinC#,whichhastheexactsamemethodsasthejava.lang.ObjectclassinJava
excepttheyarespelleddifferently.TheclonemethodinJavaiscalledMemberwiseCloneinC#,JavaequalsisEqualsinC#,finalizeisFinalize,getClass
isgetType,hashCodeisGetHashCode,andtoStringisToString.
Merecoincidence?Well,accordingtoAndersHejlsberginarecentinterview,"C#isnotaJavaclone"("DeepInsideC#:AnInterviewwithMicrosoft
ChiefArchitectAndersHejlsberg,"byJohnOsborn,http://windows.oreilly.com/news/hejlsberg_0800.html).Right,it'saMemberwiseClone.

AccessModifiers
C#specifiesaccessmodifiersinlineaspartofthememberdefinitionjustlikeJavadoes,insteadofinablocklikeC++.Themodifierspublicandprivate
havetheexactsamemeaningsinallthreelanguages.However,"protectedaccess"inJavaiscalled"protectedinternal"inC#,and"packageaccess"in
Javaiscalled"internal"inC#.C#'sprotectedmodifiergivesaccesstoanysubclass,evenifitisnotinthesameprogram.Anotherdifferenceisthat
packageaccessisthedefaultforJavawhileprivateisthedefaultforC#.

Exceptions
SimilartoJava,tryblocksinC#supportthefinallyclause.ThereisnothrowsclauseinC#,soeffectively,allexceptionsareunchecked.Youaren'tforced
tohandleanyexceptions.TheopinionatMicrosoft,accordingtooneemployee,isthatforcingdeveloperstohandleexceptionsdoesmoreharmthan
good.Thisleadstomanycatch(Exceptione)exceptionhandlersthatdon'tdoanythinguseful.
Thisisanunfortunatedecisionbecausethethrowsclausemakesitobviouswhichexceptionscanbethrownbyamethodandarepartofthemethod's
contract.Otherwise,youareforcedtoreadthecalledmethod'ssourcecodetoknowwhichexceptionscanbethrown.

C#ImprovementsOverJava
SinceC#andJavalookandactalikeinmanyways,whybotherusingC#atall?Asyoumightexpectfromasuccessorlanguage,C#makesimprovements
overJavainsomeareas.Inadditiontoaddinginnovativefeatures,C#hasasimplifiedsyntaxforthingssuchasiteration,events,andtreatingprimitive
typeslikeobjects,whichreducestheamountofcodeyouneedtowrite.

Reflection,Metadata,AndCustomAttributes
JavaandC#compilersbothemitmetadatawiththeclassbytecodestosupportreflection.Reflectionprovidestheabilitytoobtaintypeinformation
dynamicallyandmakesitpossiblefortheruntimesystemtoautomaticallyprovideimplementationsforruntimetypeidentification,dynamicmethod
invocation,serialization,marshaling,andscriptingsupport.
MicrosofthasextendedthenotionofmetadatawithCustomAttributes,whichletyoumarkupaclass,method,methodparameter,andjustaboutanything
else,withextrainformationthatcanbeaccessedatruntime.Whencompiled,theattributesarecombinedwiththeEXE/DLLitself,soitisnotpossiblefor
themtobeoutofsyncwiththecode.AttributeseliminatetheneedtomaintainseparateIDLfilesandtypelibraries.TheC#compilersupportsattributes
forinteroperatingwithlegacyCOMobjects(Internettimeindeed!)andtheWin32APIs,objectserialization,conditionalcodeexecution,anddeprecating
programentities.
AnexampleofwhereattributesareusefulisspecifyingtheXMLschematousewhenserializingaclass(seeListingOne).Asyoucansee,theclassis
markedupdirectlywithbracketedattributestoindicatewhatXMLnodeandattributenamestousewhenserializingordeserializinganAlbumobject.
ListingTwoisaprogramthatcreatesanAlbumandserializesit.ListingThreeistheresultingXMLfile.(ThecommandlineforgettingtheXML
serializationexampletocompileusingtheprereleaseC#compileriscsc.exe/r:System.Xml.dll/r:System.dll/r:System.Xml.Serialization.dllAlbums.cs.)

Versioning
VersioningisafeaturethatismuchneededintheWindowsandJavadevelopmentspace.Windowsdevelopersareaccustomedto"DLLHell,"where
http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

2/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

mismatchedversionsofDLLscancauseallkindsofapplicationproblems.JavadevelopersarealsofamiliarwithdeprecatedAPIsandincompatible
versionsofserializedobjects.
.NETpromisestofixtheseproblemsbylettingyouspecifyversiondependenciesbetweencomponentsandbysupportingsidebysideexecutionof
multipleversionsofacomponent.ThisissimilartotheversioningcapabilitiesspecifiedintheJavaProductVersioningSpecification,exceptthat
compiletime,installationtime,andruntimeenforcementisbuiltin.

Assertions
Assertionsareusefulforsanitycheckingandenforcingthepreconditions,postconditions,andinvariantsofDesignByContract.Theyoftencatchbugs
introducedbyfaultydesign/logic,incorrectassumptions,integration,andcodemaintenance.AssertionsarenotsupportedinJava,althoughtheJava
CommunityProcessisworkingonit.ListingFourdemonstratesassertionsinC#,andFigure1showstheassertiondialogthatappears.Itliststhefilename
andlinenumberwheretheassertionoccurred,thegeneralanddetailederrormessages,andthestacktrace.

refandoutParameters
Youcanpassparametersbyreferenceorspecifythattheyareoutputparametersbyusingthereforoutmodifiers.SinceJavaonlyallowspassbyvalue,
youhavetoperformsillytrickstogetthesameeffect,suchasusingreturnvalues,passinginaoneelementarray,orputtingobjectsinsidewrapper
classes.Anexampleofpassbyreferenceis:voidswap(reflongn1,reflongn2).

VirtualMethods
Bydefault,allmethodsinJavaarevirtualandcanbeoverriddenbyaderivedclass.InC#,asinC++,methodsmustbeexplicitlydeclaredvirtual.A
commonerrorinJavaandC++whenoverridingmethodsiswhensomeoneinadvertentlymodifiesthesignatureofthebaseclassmethod.Becausethe
signaturesdon'tmatch,thederivedclassmethodhidesinsteadofoverridingthebaseclassmethod.C#turnsthisintoacompiletimeerrorbyrequiring
thatthederivedclassusetheoverridekeywordtooverrideavirtualmethod.Inaddition,acompiletimewarningisgivenifamethodinthederivedclass
hidesamethodinthebaseclass.Inthiscase,youcanusethenewkeywordtoremovethewarning.

enums
JavadoesnotimplementC/C++styleenumsbecauseitsdesignersclaimthatenumsarenotobjectoriented.Faceit,enumsarealotmoretypesafethan
Javastaticfinalintconstants.enumsarenotonlypresentinC#,theyaretypesafe,canhavethe++,,<,and>operatorsappliedtothem,andcanbe
convertedtoandfromastring.

decimalDataTypes
C#decimaldatatypesare128bitsandhaveagreaterprecisionandsmallerrangethanfloatingpointtypes.Theyareparticularlyusefulforfinancial
applications.

switchStatements
Bydefault,caselabelsinaC#switchstatementdonotfallthroughtothenextcaselabel.Inadditiontobeingabletospecifyanintegerintheswitchand
casestatements,youcanalsospecifyastring.

C#SyntacticSugar
Amethodisjustafunctioninwhichthefirstargumentisapointertotheobject.Insteadofcallingfoo(object,x,y),C++/Java/C#allowyoutowrite
object.foo(x,y).Thisisanexampleofhowsyntacticsugarmakesobjectorienteddevelopmenteasier.C#providessomesugarofitsowntomake
componentorienteddevelopmenteasier.

DelegatesandEvents
DelegatesareasignificantinnovationforC#.Theyareobjectorientedfunctionpointersthatcanreferencestaticorinstancemethods.Theyprovidea
typesafemechanismforimplementingcallbackfunctionsandevents.C#supportssinglecast,multicast,synchronous,andasynchronousdelegates.
JavaprovidesforeventsbyusingtheJavaBeanseventmodelandadapterclasses.EventhandlinginC#issimplerandonlyrequiresyoutoimplement
individualmethodsinsteadofentireinterfaces.DelegateswerefirstintroducedasanonstandardfeatureofVisualJ++,muchtothedismayofSun
Microsystems,whichderideddelegatesasbeing"notobjectoriented."ForSun'sdelegatesargument,seehttp://www.javasoft.com/docs/white/
delegates.html,andhttp://msdn.microsoft.com/visualj/technical/articles/delegates/truth.aspforMicrosoft'srebuttal.(Someevenconjecturethatthe
delegatesissuewastheturningpointthatleadtotheJavalawsuit.)
Theeventkeywordintroducesadelegateintoyourclassthatletsyoufireevents.ListingFiveisasampleC#programthatusesaneventtonotifya
StockTrackerwhenthepriceofastockchanges.

ValueTypes
ValuetypesinC#(long,int,char)canbetreatedjustlikereferencetypeswithoutrequiringspecialwrapperclassesasinJava(java.lang.Long,for
example).Thecompilerimplicitlyconvertsvaluetypesintoobjects(andviceversa)ondemandthroughaprocesscalled"boxingandunboxing."
However,thisincursnooverheadifthevaluetypeisnevertreatedlikeanobject.ThisallowsC#developerstoviewtheworldasaunifiedtypesystemin
whichalldatatypesderivefromobject.Example2showsexamplesofhoweachlanguageletsyoutreatprimitivetypesasobjects.

Properties
Forourpurposes,propertiesandfieldsrefertotwodifferentconcepts.Afieldisaclassdatamember(longsize,forexample),whereasapropertyisapair
ofgetterandsetteraccessmethodsthatprovideaccesstoafieldorcalculatetheneededvalues.PropertiesinC#aresimilartoJavaBeanspropertiesin
thataccesstothemiscontrolledthroughaccessmethods.However,inC#,propertiesaredirectlysupportedbythelanguageinsteadofrelyingon
reflectionandnamingconventions,asinJavaBeans.Thisleadstoacleanandconcisesyntaxthatmakesdatahidingabreeze.Example3illustrateshow
theNamepropertyisimplementedusingthenamefieldinbothJavaandC#.
http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

3/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

TheadvantagesoftheC#propertystyleisthatthegetter/settermethodsarelocatedinthesameblockofcodeandhaveamoreintuitivesyntaxbecause
propertiesareaccessedexactlylikenormalfields.JavaBeanspropertiesalsolooklikenormalfieldswhenaccessedfromscriptsorinavisualdesigntool,
butnotwhenaccessingthemfromJavacode.

foreachStyleIterationSyntax
TheforeachstatementinC#(borrowedfromVisualBasic)letsyoueasilyenumerateoverclassesthatsupporttheEnumerableinterface,whichincludes
arraysandcollections.Thiseliminatestheneedtowritefor(inti=0i<ary.length++i)andthegetIterator/hasNext/nexttriadasyouhavetoinJavaand
C++.ListingSixdemonstratesiterationinJava,whileListingSevendemonstratesforeachstyleiterationinC#.

StringFormatting
AgreatexampleofC#syntacticsugarisstringformatting.JavaprovidestheMessageFormatclasstoallowprintfstyleformatting.ThesyntaxinC#is
muchcleanerbecauseyoucanpassavariablenumberofparameterstothefunction.Example4showsoffthestringformattingfeaturesandvariable
parametersofC#.BothexamplesoutputError:Filenotfound.(Code2).

OperatorOverloadingandCastOperators
Operatoroverloadingallowsyoutoredefinethesemanticsofoperators(+,,+=,==,andsoon)foragiventype.Whenusedproperly,operator
overloadingcanprovideanintuitivesyntaxfortreatinguserdefinedtypeslikeprimitivetypes.C#providestheoperatorkeywordforthispurpose.
Inadditiontooperatoroverloading,C#letsyoudefinecastoperators.Forexample,aclasscalledFractioncanprovideacastoperatorthatconvertsa
Fractionintoadouble.

C#PerformanceImprovements
SeveralC#featuresresultinperformanceimprovementsoverJava.Theseinclude:
Neverinterpreted.TheadventofJustinTime(JIT)compilersmeansthatJavabytecodesareusuallycompileddirectlyintonativecodebytheJVM
insteadofbeinginterpreted.OnedifferencewiththeCommonLanguageRuntimeisthatthebytecodeisneverinterpreted,itisalwaysJITed.
MicrosofthasaproventrackrecordforwritingthefastestJVM,soyoucanexpecttheirMSILJITertobefast.
NativeplatformsupportforWin32andCOMisanimprovementovertheperformanceofJ/DirectandtheJavaNativeInterface.
Thestackallocoperationissimilartonew,exceptthatitallocatesmemoryforanarrayonthestackinsteadoftheheap.Stackallocationismuch
fasterthanheapallocationandisnotsubjecttogarbagecollection.
Astructdatatypeisexactlylikeanobject,exceptthatstructsarevaluetypesinsteadofreferencetypesanddonotsupportinheritance.Theycanbe
allocatedonthestackjustlikeprimitivetypesanddonotrequiretheextravtableoverhead.Usestructstorepresentsimpletypes,suchasPoint,
Rect,Fraction,andsoon.Theylosetheireffectivenesswhentheirsizegoesabove16bytes.
CodeinC#canbemarkedunsafetoallowittohavedirectmemoryaccessandpreventthegarbagecollectorfrominterfering.

What'sNottoLike?
NeitherJavanorC#supportgenerictypes(templates).However,aproposalhasbeensubmittedtotheJavaCommunityProcess,andMicrosoftResearch
atCambridgeissaidtobedevelopingasolutionfor.NET.
LikeJ/Direct,theP/InvokeclasslibraryprovidestheabilityforC#totalktonativeWin32APIsandDLLs.Whilethisisaboonforinteroperability,it
requireswritingC#functionprototypesthathavethesamesignaturesastheAPIfunctions.Forexample,handles(HWND,forexample)areapproximated
usingaC#intandpointersareapproximatedwithrefparameters.Thistechniqueispronetosignaturemismatchesthatcancauseunpredictablebehavior
andcrashes.
SimilartoP/Invoke,COMInteropprovideswrapperclassesforallowingC#touseCOMobjectsandviceversa.Unfortunately,certaintypesofCOM
interfacesarenot100percentcompatiblewithwrappers,whichcausesanimpedancemismatch.

Conclusion
C#isJavawithsomeniftyfeatures,innovations,syntacticsugar,andperformanceenhancementsthrownin.C#'selegance,simplicity,andpower
promisestodeliverWindowsC++developersfromthepitsofboilerplateCOMcodeandmemoryviolationstothelandofRAD.ForJavaprogrammers,
C#picksupwhereJavaleavesoffbyprovidingahighperformance,componentorientedlanguagethatintegratestightlywithWindows.Let'shopeC#is
asmuchfunasJavaistoworkwith.
DDJ
ListingOne
usingSystem.NewXml;
usingSystem.Xml.Serialization;
[XmlRoot("album",Namespace="music")]
publicclassAlbum{
[XmlElement("artist")]
publicstringartist;
[XmlElement("title")]
publicstringtitle;
[XmlArray("songs"),XmlArrayItem("song")]
publicstring[]songs;
}

BacktoArticle
ListingTwo

http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

4/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

usingSystem.Xml.Serialization;
usingSystem.IO;
classTestAlbum
{
publicstaticvoidMain(){
Albumalbum=newAlbum();
album.artist="Sasha";
album.title="Xpander";
album.songs=newstring[5];
album.songs[0]="XpanderEdit";
album.songs[1]="Xpander";
album.songs[2]="Belfunk";
album.songs[3]="Rabbitweed";
album.songs[4]="Baja";
//Serializetheobjecttoafile
FileStreamfs=newFileStream("Album.xml",FileMode.Create);
XmlSerializerserializer=newXmlSerializer(typeof(Album));
serializer.Serialize(fs,album);
}
}

BacktoArticle
ListingThree
<?xmlversion="1.0"?>
<albumxmlns:xsi=http://www.w3.org/1999/XMLSchemainstance
xmlns="music">
<artist>Sasha</artist>
<title>Xpander</title>
<songs>
<song>XpanderEdit</song>
<song>Xpander</song>
<song>Belfunk</song>
<song>Rabbitweed</song>
<song>Baja</song>
</songs>
</album>

BacktoArticle
ListingFour
usingSystem.Diagnostics;
classConfigFile{
boolisFileOpen;
publicvoidOpen(stringstrFile){
//Preconditions
Debug.Assert(!isFileOpen,"Configfilealreadyopen.",
"YoucanonlycallOpen()once.");
Debug.Assert(strFile.Length>0);
isFileOpen=true;
//...
}
publicstaticvoidMain(){
ConfigFilefile=newConfigFile();
file.Open("Joe.xml");
file.Open("Joe.xml");//Causesanassertion!
}
}

BacktoArticle
ListingFive
usingSystem;
delegatevoidPriceDecreasedDelegate(stringname,longnewPrice);
//Calledwhenthepricedrops
delegatevoidPriceIncreasedDelegate(stringname,longnewPrice);
//Calledwhenthepriceincreases
classStock{
//Holdsthepriceofastock
publicStock(stringstockName,longstartPrice){
name=stockName;
price=startPrice;
}
publiclongPrice{
get{returnprice;}
set{
if(value>price&&
Fire_OnPriceIncreased!=null){
Fire_OnPriceIncreased(name,value);//Informlisteners
}elseif(value<price&&
Fire_OnPriceDecreased!=null){
Fire_OnPriceDecreased(name,value);//Informlisteners
}
price=value;//Updatetheprice
}
}
//DATA
stringname;
longprice;
publiceventPriceDecreasedDelegateFire_OnPriceDecreased=null;
publiceventPriceIncreasedDelegateFire_OnPriceIncreased=null;

http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

5/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

}
classStockTracker{
//Outputsamessagewhenthestockpricechanges
publicStockTracker(Stockstock){
//ConnecttheStockeventstooureventhandlers
stock.Fire_OnPriceDecreased+=
newPriceDecreasedDelegate(OnPriceDecreased);
stock.Fire_OnPriceIncreased+=
newPriceIncreasedDelegate(OnPriceIncreased);
}
//Signatureofeventhandlermustmatchthe
//PriceDecreasedDelegatedelegatedeclaration
privatevoidOnPriceDecreased(stringname,longval){
Console.WriteLine("Priceof{0}droppedto{1}!",name,val);
}
privatevoidOnPriceIncreased(stringname,longval){
Console.WriteLine("Priceof{0}roseto{1}!",name,val);
}
}
classStockTester{
//Testtheevents
publicstaticvoidMain(){
Stockibm=newStock("IBM",100);
StockTrackertracker=newStockTracker(ibm);
//Updatethestockprice
ibm.Price=125;//Outputs"PriceofIBMroseto125!"
ibm.Price=90;//Outputs"PriceofIBMdroppedto90!"
}
}

BacktoArticle
ListingSix
importjava.util.*;
classIterate{
publicstaticvoidmain(String[]args){
//Enumeratecommandlineargsarray
for(inti=0;i<args.length;++i)
System.out.println(args[i]);
//Createalinkedlist
LinkedListlist=newLinkedList();
list.add("CubeFarm");
list.add("Sasha&Digweed");
//Enumeratethelist
ListIteratorit=list.listIterator(0);
while(it.hasNext())
System.out.println(it.next());
}
}

BacktoArticle
ListingSeven
usingSystem.Collections;
classIterate{
publicstaticvoidMain(string[]args){
//Enumeratecommandlineargsarray
foreach(stringarginargs)
System.Console.WriteLine(arg);
//Createalinkedlist
ObjectListlist=newObjectList();
list.Add("CubeFarm");
list.Add("Sasha&Digweed");
//Enumeratethelist
foreach(stringstrinlist)
System.Console.WriteLine(str);
}
}

BacktoArticle
(a)
classHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("Hello,World!");
}
}
(b)
classHelloWorld{
publicstaticvoidMain(string[]args){
System.Console.WriteLine("Hello,World!");
}

http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

6/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

Example1:HelloWorld.(a)inJava(b)inC#.

(a)
inti=10;
System.out.println((newInteger(i)).hashCode());//Usewrapperclass
(b)
inti=10;
System.Console.WriteLine(i.GetHashCode());//Conversionisimplicit

Example2:Valuetypes.(a)inJava(b)inC#.

(a)
Stringname;
publicStringgetName(){returnname;}
publicvoidsetName(Stringvalue){name=value;}
Ex:
obj.setName("Marc");
if(obj.getName()!="Marc")
thrownewException("Thatain'tme!");
(b)
stringname;
publicstringName{
get{returnname;}
set{name=value;}//'value'isthenewvalue
}
Ex:
obj.Name="Marc";
if(obj.Name!="Marc")
thrownewSystem.Exception("Thatain'tme!");

Example3:ImplementingtheNamepropertyusingthenamefield:(a)inJava(b)inC#.

(a)
//Createanobjectarray
Objectargs[]={"Filenotfound.",newInteger(2)};
//Formatthemessage
System.out.println(
java.text.MessageFormat.format("Error:{0}(Code{1})",args));
(b)
System.Console.WriteLine("Error:{0}(Code{1})","Filenotfound.",2);

Example4:Stringformatting.(a)inJava(b)inC#.

Figure1:Theassertiondialog.

http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

7/8

04/09/2014

Dr.Dobb's|C#VersusJava|February01,2001

Table1:CosmeticdifferencesbetweenJavaandC#.
TermsofService|PrivacyStatement|Copyright2012UBMTech,Allrightsreserved.

http://www.drdobbs.com/article/print?articleId=184404487&siteSectionName=windows

8/8

You might also like