Introduction to Java Primitives | Baeldung

文章推薦指數: 80 %
投票人數:10人

The eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char – those aren't considered objects and ... StartHereCourses ▼▲ RESTwithSpring ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring. LearnSpringSecurity ▼▲ THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday. LearnSpringSecurityCore FocusontheCoreofSpringSecurity5 LearnSpringSecurityOAuth FocusonthenewOAuth2stackinSpringSecurity5 LearnSpring Fromnoexperiencetoactuallybuildingstuff​.(thepricewillincreaseby$40attheendofthisweek) LearnSpringDataJPA ThefullguidetopersistencewithSpringDataJPA. Guides ▼▲ Persistence ThePersistencewithSpringguides REST TheguidesonbuildingRESTAPIswithSpring Security TheSpringSecurityguides About ▼▲ FullArchive Thehighleveloverviewofallthearticlesonthesite. BaeldungEbooks DiscoverallofoureBooks WriteforBaeldung Becomeawriteronthesite. AboutBaeldung AboutBaeldung. LSPriceIncreaseLaunch ThePriceofall“LearnSpring”coursepackageswillincreaseby$40attheendofthisweek: >>GETACCESSNOW 1.Overview TheJavaProgrammingLanguagefeatureseightprimitivedatatypes. Inthisarticle,we'llrecallwhatprimitivesareandgooverthem. 2.PrimitiveDataTypes TheeightprimitivesdefinedinJavaareint,byte,short,long,float,double,boolean,andchar–thosearen'tconsideredobjectsandrepresentrawvalues. They'restoreddirectlyonthestack(checkoutthisarticleformoreinformationaboutmemorymanagementinJava). Let'stakealookatstoragesize,defaultvalues,andexamplesofhowtouseeachtype. Let'sstartwithaquickreference: Type Size(bits) Minimum Maximum Example byte 8 -27 27–1 byteb=100; short 16 -215 215–1 shorts=30_000; int 32 -231 231–1 inti=100_000_000; long 64 -263 263–1 longl=100_000_000_000_000; float 32 -2-149 (2-2-23)·2127 floatf=1.456f; double 64 -2-1074 (2-2-52)·21023 doublef=1.456789012345678; char 16 0 216–1 charc=‘c'; boolean 1 – – booleanb=true; 2.1.int Thefirstprimitivedatatypewe'regoingtocoverisint.Alsoknownasaninteger,inttypeholdsawiderangeofnon-fractionalnumbervalues. Specifically,Javastoresitusing32bitsofmemory.Inotherwords,itcanrepresentvaluesfrom-2,147,483,648(-231)to2,147,483,647(231-1). InJava8,it'spossibletostoreanunsignedintegervalueupto4,294,967,295(232-1)byusingnewspecialhelperfunctions. Wecansimplydeclareanintsimply: intx=424_242; inty; Thedefaultvalueofanintdeclaredwithoutanassignmentis0. Ifthevariableisdefinedinamethod,wemustassignavaluebeforewecanuseit. Wecanperformallstandardarithmeticoperationsonints.Justbeawarethatdecimalvalueswillbechoppedoffwhenperformingtheseonintegers. 2.2.byte byteisaprimitivedatatypesimilartoint,exceptitonlytakesup8bitsofmemory.Thus,whywecallitabyte.Becausethememorysizebeingsosmall,bytecanonlyholdthevaluesfrom-128(-27)to127(27–1). Wecancreatebyte: byteb=100; byteempty; Thedefaultvalueofbyteisalso0. 2.3.short ThenextstoponourlistofprimitivedatatypesinJavaisshort. Ifwewanttosavememoryandbyteistoosmall,wecanusethetypehalfwaybetweenthetwo:short. At16bitsofmemory,it'shalfthesizeofintandtwicethesizeofbyte.Itsrangeofpossiblevaluesis-32,768(-215)to32,767(215–1). shortisdeclaredlikethis: shorts=202_020; shorts; Alsosimilartotheothertypes,thedefaultvalueis0.Wecanuseallstandardarithmeticonitaswell. 2.4.long Ourlastprimitivedatatyperelatedtointegersislong. longisthebigbrotherofint.It'sstoredin64bitsofmemorysoitcanholdasignificantlylargersetofpossiblevalues. Thepossiblevaluesofalongarebetween-9,223,372,036,854,775,808(-263)to9,223,372,036,854,775,807(263–1). Wecansimplydeclareone: longl=1_234_567_890; longl; Aswithotherintegertypes,thedefaultisalso0.Wecanuseallarithmeticonlongthatworksonint. 2.5.float WerepresentbasicfractionalnumbersinJavausingthefloattype.Thisisasingle-precisiondecimalnumber.Whichmeansifwegetpastsixdecimalpoints,thisnumberbecomeslesspreciseandmoreofanestimate. Inmostcases,wedon'tcareabouttheprecisionloss.But,ifourcalculationrequiresabsoluteprecision(i.e.,financialoperations,landingonthemoon,etc.)weneedtousespecifictypesdesignedforthiswork.Formoreinformation,checkouttheJavaclassBigDecimal. Thistypeisstoredin32bitsofmemoryjustlikeint.However,becauseofthefloatingdecimalpointitsrangeismuchdifferent.Itcanrepresentbothpositiveandnegativenumbers.Thesmallestdecimalis1.40239846x10-45,andthelargestvalueis3.40282347x1038. Wedeclarefloatsthesameasanyothertype: floatf=3.145f; floatf; Andthedefaultvalueis0.0insteadof0.Also,noticeweaddthefdesignationtotheendoftheliteralnumbertodefineafloat.Otherwise,Javawillthrowanerrorbecausethedefaulttypeofadecimalvalueisdouble. Wecanalsoperformallstandardarithmeticoperationsonfloats.However,it'simportanttonotethatweperformfloatingpointarithmeticverydifferentlythanintegerarithmetic. 2.6.double Next,welookatdouble–itsnamecomesfromthefactthatit'sadouble-precisiondecimalnumber. It'sstoredin64bitsofmemory.Whichmeansitrepresentsamuchlargerrangeofpossiblenumbersthanfloat. Although,itdoessufferfromthesameprecisionlimitationasfloatdoes.Therangeis4.9406564584124654x10-324to1.7976931348623157x10308.Thatrangecanalsobepositiveornegative. Declaringdoubleisthesameasothernumerictypes: doubled=3.13457599923384753929348D; doubled; Thedefaultvalueisalso0.0asitiswithfloat.Similartofloat,weattachtheletterDtodesignatetheliteralasadouble. 2.7.boolean Thesimplestprimitivedatatypeisboolean.Itcancontainonlytwovalues:trueorfalse.Itstoresitsvalueinasinglebit. However,forconvenience,Javapadsthevalueandstoresitinasinglebyte. Declarebooleanlikethis: booleanb=true; booleanb; Declaringitwithoutavaluedefaultstofalse.booleanisthecornerstoneofcontrollingourprogramsflow.Wecanusebooleanoperatorsonthem(i.e.,and,or,etc.). 2.8.char Thefinalprimitivedatatypetolookatischar. Alsocalledacharacter,charisa16-bitintegerrepresentingaUnicode-encodedcharacter.Itsrangeisfrom0to65,535.WhichinUnicoderepresents‘\u0000'to‘\uffff'. ForalistofallpossibleUnicodevaluescheckoutsiteslikeUnicodeTable. Let'snowdeclareachar: charc='a'; charc=65; charc; Whendefiningourvariables,wecanuseanycharacterliteral,andtheywillgetautomaticallytransformedintotheirUnicodeencodingforus.Acharactersdefaultvalueis‘/u0000'. 2.9.Overflow Theprimitivedatatypeshavesizelimits.Butwhathappensifwetrytostoreavaluethat'slargerthanthemaximumvalue? Werunintoasituationcalledoverflow. Whenanintegeroverflows,itrollsovertotheminimumvalueandbeginscountingupfromthere. FloatingpointnumberoverflowbyreturningInfinity.Whentheyunderflow,theyreturn0.0. Here'sanexample: inti=Integer.MAX_VALUE; intj=i+1; //jwillrolloverto-2_147_483_648 doubled=Double.MAX_VALUE; doubleo=d+1; //owillbeInfinity Underflowisthesameissueexceptifwestoreavaluesmallerthantheminimumvalue. 2.10.Autoboxing EachprimitivedatatypealsohasafullJavaclassimplementationthatcanwrapit.Forinstance,theIntegerclasscanwrapanint.Thereissometimesaneedtoconvertfromtheprimitivetypetoitsobjectwrapper(e.g.,usingthemwithgenerics). Luckily,Javacanperformthisconversionforusautomatically.WecallthisprocessAutoboxing.Hereisanexample: Characterc='c'; Integeri=1; 3.Conclusion Inthistutorial,we'vecoveredtheeightprimitivedatatypessupportedinJava. Thesearethebuildingblocksusedbymost,ofnotallJavaprogramsoutthere–soit'swellworthunderstandinghowtheywork. LSPriceIncreaseLaunch ThePriceofall“LearnSpring”coursepackageswillincreaseby$40attheendofthisweek: >>GETACCESSNOW Genericfooterbanner LearningtobuildyourAPIwithSpring? DownloadtheE-book Commentsareclosedonthisarticle! lspriceincreaseoctober ThePriceof LEARNSPRINGisincreasing $197$237 Seethecourse Followthe Java Category FollowtheJavacategorytogetregularinfoaboutthenewarticlesandtutorialswepublishhere. FOLLOWTHEJAVACATEGORY



請為這篇文章評分?