Primitive Data Types - Java Tutorials - Oracle Help Center
文章推薦指數: 80 %
Primitive Data Types · byte: The byte data type is an 8-bit signed two's complement integer. · short: The short data type is a 16-bit signed two's complement ... Documentation TheJava™Tutorials HideTOC LanguageBasics Variables PrimitiveDataTypes Arrays SummaryofVariables QuestionsandExercises Operators Assignment,Arithmetic,andUnaryOperators Equality,Relational,andConditionalOperators BitwiseandBitShiftOperators SummaryofOperators QuestionsandExercises Expressions,Statements,andBlocks QuestionsandExercises ControlFlowStatements Theif-thenandif-then-elseStatements TheswitchStatement Thewhileanddo-whileStatements TheforStatement BranchingStatements SummaryofControlFlowStatements QuestionsandExercises Trail:LearningtheJavaLanguage Lesson:LanguageBasics Section:Variables HomePage > LearningtheJavaLanguage > LanguageBasics « Previous • Trail • Next » TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedon'ttakeadvantageofimprovementsintroducedinlaterreleasesandmightusetechnologynolongeravailable.SeeJavaLanguageChangesforasummaryofupdatedlanguagefeaturesinJavaSE9andsubsequentreleases.SeeJDKReleaseNotesforinformationaboutnewfeatures,enhancements,andremovedordeprecatedoptionsforallJDKreleases. PrimitiveDataTypes TheJavaprogramminglanguageisstatically-typed,whichmeansthatallvariablesmustfirstbedeclaredbeforetheycanbeused.Thisinvolvesstatingthevariable'stypeandname,asyou'vealreadyseen: intgear=1; Doingsotellsyourprogramthatafieldnamed"gear"exists,holdsnumericaldata,andhasaninitialvalueof"1".Avariable'sdatatypedeterminesthevaluesitmaycontain,plustheoperationsthatmaybeperformedonit.Inadditiontoint,theJavaprogramminglanguagesupportssevenotherprimitivedatatypes.Aprimitivetypeispredefinedbythelanguageandisnamedbyareservedkeyword.Primitivevaluesdonotsharestatewithotherprimitivevalues.TheeightprimitivedatatypessupportedbytheJavaprogramminglanguageare: byte:Thebytedatatypeisan8-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-128andamaximumvalueof127(inclusive).Thebytedatatypecanbeusefulforsavingmemoryinlarge arrays,wherethememorysavingsactuallymatters.Theycanalsobeusedinplaceofintwheretheirlimitshelptoclarifyyourcode;thefactthatavariable'srangeislimitedcanserveasaformofdocumentation. short:Theshortdatatypeisa16-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-32,768andamaximumvalueof32,767(inclusive).Aswithbyte,thesameguidelinesapply:youcanuseashorttosavememoryinlargearrays,insituationswherethememorysavingsactuallymatters. int:Bydefault,theintdatatypeisa32-bitsignedtwo'scomplementinteger,whichhasaminimumvalueof-231andamaximumvalueof231-1.InJavaSE8andlater,youcanusetheintdatatypetorepresentanunsigned32-bitinteger,whichhasaminimumvalueof0andamaximumvalueof232-1.UsetheIntegerclasstouseintdatatypeasanunsignedinteger.SeethesectionTheNumberClassesformoreinformation.StaticmethodslikecompareUnsigned,divideUnsignedetchavebeenaddedtothe Integerclasstosupportthearithmeticoperationsforunsignedintegers. long:Thelongdatatypeisa64-bittwo'scomplementinteger.Thesignedlonghasaminimumvalueof-263andamaximumvalueof263-1.InJavaSE8andlater,youcanusethelongdatatypetorepresentanunsigned64-bitlong,whichhasaminimumvalueof0andamaximumvalueof264-1.Usethisdatatypewhenyouneedarangeofvalueswiderthanthoseprovidedbyint.The LongclassalsocontainsmethodslikecompareUnsigned,divideUnsignedetctosupportarithmeticoperationsforunsignedlong. float:Thefloatdatatypeisasingle-precision32-bitIEEE754floatingpoint.Itsrangeofvaluesisbeyondthescopeofthisdiscussion,butisspecifiedinthe Floating-PointTypes,Formats,andValuessectionoftheJavaLanguageSpecification.Aswiththerecommendationsforbyteandshort,useafloat(insteadofdouble)ifyouneedtosavememoryinlargearraysoffloatingpointnumbers.Thisdatatypeshouldneverbeusedforprecisevalues,suchascurrency.Forthat,youwillneedtousethe java.math.BigDecimalclassinstead. NumbersandStringscoversBigDecimalandotherusefulclassesprovidedbytheJavaplatform. double:Thedoubledatatypeisadouble-precision64-bitIEEE754floatingpoint.Itsrangeofvaluesisbeyondthescopeofthisdiscussion,butisspecifiedinthe Floating-PointTypes,Formats,andValuessectionoftheJavaLanguageSpecification.Fordecimalvalues,thisdatatypeisgenerallythedefaultchoice.Asmentionedabove,thisdatatypeshouldneverbeusedforprecisevalues,suchascurrency. boolean:Thebooleandatatypehasonlytwopossiblevalues:trueandfalse.Usethisdatatypeforsimpleflagsthattracktrue/falseconditions.Thisdatatyperepresentsonebitofinformation,butits"size"isn'tsomethingthat'spreciselydefined. char:Thechardatatypeisasingle16-bitUnicodecharacter.Ithasaminimumvalueof'\u0000'(or0)andamaximumvalueof'\uffff'(or65,535inclusive). Inadditiontotheeightprimitivedatatypeslistedabove,theJavaprogramminglanguagealsoprovidesspecialsupportforcharacterstringsviathe java.lang.Stringclass.EnclosingyourcharacterstringwithindoublequoteswillautomaticallycreateanewStringobject;forexample,Strings="thisisastring";.Stringobjectsareimmutable,whichmeansthatoncecreated,theirvaluescannotbechanged.TheStringclassisnottechnicallyaprimitivedatatype,butconsideringthespecialsupportgiventoitbythelanguage,you'llprobablytendtothinkofitassuch.You'lllearnmoreabouttheStringclassin SimpleDataObjects DefaultValues It'snotalwaysnecessarytoassignavaluewhenafieldisdeclared.Fieldsthataredeclaredbutnotinitializedwillbesettoareasonabledefaultbythecompiler.Generallyspeaking,thisdefaultwillbezeroornull,dependingonthedatatype.Relyingonsuchdefaultvalues,however,isgenerallyconsideredbadprogrammingstyle. Thefollowingchartsummarizesthedefaultvaluesfortheabovedatatypes. DataType DefaultValue(forfields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String(oranyobject) null boolean false Localvariablesareslightlydifferent;thecompilerneverassignsadefaultvaluetoanuninitializedlocalvariable.Ifyoucannotinitializeyourlocalvariablewhereitisdeclared,makesuretoassignitavaluebeforeyouattempttouseit.Accessinganuninitializedlocalvariablewillresultinacompile-timeerror. Literals Youmayhavenoticedthatthenewkeywordisn'tusedwheninitializingavariableofaprimitivetype.Primitivetypesarespecialdatatypesbuiltintothelanguage;theyarenotobjectscreatedfromaclass.Aliteralisthesourcecoderepresentationofafixedvalue;literalsarerepresenteddirectlyinyourcodewithoutrequiringcomputation.Asshownbelow,it'spossibletoassignaliteraltoavariableofaprimitivetype: booleanresult=true; charcapitalC='C'; byteb=100; shorts=10000; inti=100000; IntegerLiterals AnintegerliteralisoftypelongifitendswiththeletterLorl;otherwiseitisoftypeint.ItisrecommendedthatyouusetheuppercaseletterLbecausethelowercaseletterlishardtodistinguishfromthedigit1. Valuesoftheintegraltypesbyte,short,int,andlongcanbecreatedfromintliterals.Valuesoftypelongthatexceedtherangeofintcanbecreatedfromlongliterals.Integerliteralscanbeexpressedbythesenumbersystems: Decimal:Base10,whosedigitsconsistsofthenumbers0through9;thisisthenumbersystemyouuseeveryday Hexadecimal:Base16,whosedigitsconsistofthenumbers0through9andthelettersAthroughF Binary:Base2,whosedigitsconsistsofthenumbers0and1(youcancreatebinaryliteralsinJavaSE7andlater) Forgeneral-purposeprogramming,thedecimalsystemislikelytobetheonlynumbersystemyou'lleveruse.However,ifyouneedtouseanothernumbersystem,thefollowingexampleshowsthecorrectsyntax.Theprefix0xindicateshexadecimaland0bindicatesbinary: //Thenumber26,indecimal intdecVal=26; //Thenumber26,inhexadecimal inthexVal=0x1a; //Thenumber26,inbinary intbinVal=0b11010; Floating-PointLiterals Afloating-pointliteralisoftypefloatifitendswiththeletterForf;otherwiseitstypeisdoubleanditcanoptionallyendwiththeletterDord. Thefloatingpointtypes(floatanddouble)canalsobeexpressedusingEore(forscientificnotation),Forf(32-bitfloatliteral)andDord(64-bitdoubleliteral;thisisthedefaultandbyconventionisomitted). doubled1=123.4; //samevalueasd1,butinscientificnotation doubled2=1.234e2; floatf1=123.4f; CharacterandStringLiterals LiteralsoftypescharandStringmaycontainanyUnicode(UTF-16)characters.Ifyoureditorandfilesystemallowit,youcanusesuchcharactersdirectlyinyourcode.Ifnot,youcanusea"Unicodeescape"suchas'\u0108'(capitalCwithcircumflex),or"S\u00EDSe\u00F1or"(SíSeñorinSpanish).Alwaysuse'singlequotes'forcharliteralsand"doublequotes"forStringliterals.Unicodeescapesequencesmaybeusedelsewhereinaprogram(suchasinfieldnames,forexample),notjustincharorStringliterals. TheJavaprogramminglanguagealsosupportsafewspecialescapesequencesforcharandStringliterals:\b(backspace),\t(tab),\n(linefeed),\f(formfeed),\r(carriagereturn),\"(doublequote),\'(singlequote),and\\(backslash). There'salsoaspecialnullliteralthatcanbeusedasavalueforanyreferencetype.nullmaybeassignedtoanyvariable,exceptvariablesofprimitivetypes.There'slittleyoucandowithanullvaluebeyondtestingforitspresence.Therefore,nullisoftenusedinprogramsasamarkertoindicatethatsomeobjectisunavailable. Finally,there'salsoaspecialkindofliteralcalledaclassliteral,formedbytakingatypenameandappending".class";forexample,String.class.Thisreferstotheobject(oftypeClass)thatrepresentsthetypeitself. UsingUnderscoreCharactersinNumericLiterals InJavaSE7andlater,anynumberofunderscorecharacters(_)canappearanywherebetweendigitsinanumericalliteral.Thisfeatureenablesyou,forexample.toseparategroupsofdigitsinnumericliterals,whichcanimprovethereadabilityofyourcode. Forinstance,ifyourcodecontainsnumberswithmanydigits,youcanuseanunderscorecharactertoseparatedigitsingroupsofthree,similartohowyouwoulduseapunctuationmarklikeacomma,oraspace,asaseparator. Thefollowingexampleshowsotherwaysyoucanusetheunderscoreinnumericliterals: longcreditCardNumber=1234_5678_9012_3456L; longsocialSecurityNumber=999_99_9999L; floatpi=3.14_15F; longhexBytes=0xFF_EC_DE_5E; longhexWords=0xCAFE_BABE; longmaxLong=0x7fff_ffff_ffff_ffffL; bytenybbles=0b0010_0101; longbytes=0b11010010_01101001_10010100_10010010; Youcanplaceunderscoresonlybetweendigits;youcannotplaceunderscoresinthefollowingplaces: Atthebeginningorendofanumber Adjacenttoadecimalpointinafloatingpointliteral PriortoanForLsuffix Inpositionswhereastringofdigitsisexpected Thefollowingexamplesdemonstratevalidandinvalidunderscoreplacements(whicharehighlighted)innumericliterals: //Invalid:cannotputunderscores //adjacenttoadecimalpoint floatpi1=3_.1415F; //Invalid:cannotputunderscores //adjacenttoadecimalpoint floatpi2=3._1415F; //Invalid:cannotputunderscores //priortoanLsuffix longsocialSecurityNumber1=999_99_9999_L; //OK(decimalliteral) intx1=5_2; //Invalid:cannotputunderscores //Attheendofaliteral intx2=52_; //OK(decimalliteral) intx3=5_______2; //Invalid:cannotputunderscores //inthe0xradixprefix intx4=0_x52; //Invalid:cannotputunderscores //atthebeginningofanumber intx5=0x_52; //OK(hexadecimalliteral) intx6=0x5_2; //Invalid:cannotputunderscores //attheendofanumber intx7=0x52_; «Previous • Trail • Next» AboutOracle| ContactUs| LegalNotices| TermsofUse| YourPrivacyRights Copyright©1995,2021Oracleand/oritsaffiliates.Allrightsreserved. Previouspage:Variables Nextpage:Arrays
延伸文章資訊
- 1Java 入門指南- 單元3 - 基本資料型態與參考 - 程式語言教學誌
Java 中的變數(variable) 有兩種,一種是基本資料型態(primitive data type) ,另一種則是對物件(object) 的參考(reference). variable...
- 2Java Data Types - W3Schools
A primitive data type specifies the size and type of variable values, and it has no additional me...
- 3Java 基本資料型類別(primitive type)和外包類別(wrapper classes)
基本資料型類別(primitive type),又稱為工具類別,例如char, int等,和外包類別(wrapper classes) Character, Integer是有分別的。 錯誤示範:
- 4Primitive Data Types - Java Tutorials - Oracle Help Center
Primitive Data Types · byte: The byte data type is an 8-bit signed two's complement integer. · sh...
- 5[Java] 4-1 Primitive data type基本資料型態 - 給你魚竿
Java內有8大基本資料型態Primitive data type 相較於其他物件使用基本資料型態就是非常快以下就介紹如下: 1. 官網https://docs.oracle.com/javas.