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
延伸文章資訊
- 1Introduction to Java Primitives | Baeldung
The eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char...
- 2[Java] 4-1 Primitive data type基本資料型態 - 給你魚竿
Java內有8大基本資料型態Primitive data type 相較於其他物件使用基本資料型態就是非常快以下就介紹如下: 1. 官網https://docs.oracle.com/javas.
- 3Primitive Types - Wikibooks, open books for an open world
Primitive types are the most basic data types available within the Java language. There are 8: bo...
- 4Primitive Data Type - PsMonkey 隨手筆記
在Java 當中內建好的資料型態(primitive data type)有下列幾種: ... 既然每種不同資料型態有不同的範圍,而Java 又是一種Strong Type 的語言,所以下面這個...
- 5Primitive 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...