Java Data Types - W3Schools
文章推薦指數: 80 %
A primitive data type specifies the size and type of variable values, and it has no additional methods. There are eight primitive data types in Java: ... Tutorials References Exercises VideosNEW Menu Login PaidCourses WebsiteNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC++ LearnC# LearnR LearnKotlin LearnGo ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit WebBuilding CreateaWebsiteNEW WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop JavaTutorial JavaHOME JavaIntro JavaGetStarted JavaSyntax JavaComments JavaVariables JavaDataTypes JavaTypeCasting JavaOperators JavaStrings JavaMath JavaBooleans JavaIf...Else JavaSwitch JavaWhileLoop JavaForLoop JavaBreak/Continue JavaArrays JavaMethods JavaMethods JavaMethodParameters JavaMethodOverloading JavaScope JavaRecursion JavaClasses JavaOOP JavaClasses/Objects JavaClassAttributes JavaClassMethods JavaConstructors JavaModifiers JavaEncapsulation JavaPackages/API JavaInheritance JavaPolymorphism JavaInnerClasses JavaAbstraction JavaInterface JavaEnums JavaUserInput JavaDate JavaArrayList JavaLinkedList JavaHashMap JavaHashSet JavaIterator JavaWrapperClasses JavaExceptions JavaRegEx JavaThreads JavaLambda JavaFileHandling JavaFiles JavaCreate/WriteFiles JavaReadFiles JavaDeleteFiles JavaHowTo AddTwoNumbers JavaReference JavaKeywords abstract boolean break byte case catch char class continue default do double else enum extends final finally float for if implements import instanceof int interface long new package private protected public return short static super switch this throw throws try void while JavaStringMethods JavaMathMethods JavaExamples JavaExamples JavaCompiler JavaExercises JavaQuiz JavaCertificate JavaDataTypes ❮Previous Next❯ JavaDataTypes Asexplainedinthepreviouschapter,avariableinJavamustbeaspecifieddatatype: Example intmyNum=5; //Integer(wholenumber) floatmyFloatNum=5.99f; //Floatingpointnumber charmyLetter='D'; //Character booleanmyBool=true; //Boolean StringmyText="Hello"; //String TryitYourself» Datatypesaredividedintotwogroups: Primitivedatatypes-includesbyte,short,int,long, float,double,booleanandchar Non-primitivedatatypes-suchasString,ArraysandClasses(youwilllearnmoreabouttheseinalaterchapter) PrimitiveDataTypes Aprimitivedatatypespecifiesthesizeandtypeofvariablevalues,andithasno additionalmethods. ThereareeightprimitivedatatypesinJava: DataType Size Description byte 1byte Storeswholenumbersfrom-128to127 short 2bytes Storeswholenumbersfrom-32,768to32,767 int 4bytes Storeswholenumbersfrom-2,147,483,648to2,147,483,647 long 8bytes Storeswholenumbersfrom-9,223,372,036,854,775,808to 9,223,372,036,854,775,807 float 4bytes Storesfractionalnumbers.Sufficientfor storing6to7decimaldigits double 8bytes Storesfractionalnumbers.Sufficientfor storing15decimaldigits boolean 1bit Storestrueorfalsevalues char 2bytes Storesasinglecharacter/letterorASCIIvalues Numbers Primitivenumbertypesaredividedintotwogroups: Integertypesstoreswholenumbers,positiveornegative(suchas123or-456),withoutdecimals. Validtypesarebyte,short,int andlong.Whichtypeyoushoulduse,dependsonthenumericvalue. Floatingpointtypesrepresentsnumberswithafractionalpart, containingoneormoredecimals.Therearetwotypes:floatanddouble. EventhoughtherearemanynumerictypesinJava,themostusedfornumbers areint(forwholenumbers)anddouble(forfloatingpointnumbers).However,wewilldescribethemallasyoucontinueto read. IntegerTypes Byte Thebytedatatypecanstorewholenumbers from-128to127.Thiscanbeusedinsteadofintorotherintegertypesto savememorywhenyouarecertainthatthevaluewillbewithin-128and127: Example bytemyNum=100; System.out.println(myNum); TryitYourself» Short Theshortdatatypecanstorewholenumbersfrom-32768to32767: Example shortmyNum=5000; System.out.println(myNum); TryitYourself» Int Theintdatatypecanstorewholenumbersfrom-2147483648to2147483647.Ingeneral,andinourtutorial,theintdatatypeis thepreferreddatatypewhenwecreatevariableswithanumericvalue. Example intmyNum=100000; System.out.println(myNum); TryitYourself» Long Thelongdatatypecanstorewholenumbersfrom-9223372036854775808to9223372036854775807.Thisisusedwhenintisnotlargeenoughtostorethevalue.Notethatyoushouldendthevaluewithan"L": Example longmyNum=15000000000L; System.out.println(myNum); TryitYourself» FloatingPointTypes Youshoulduseafloatingpointtypewheneveryouneedanumberwithadecimal,suchas9.99or3.14515. Float Thefloatdatatypecanstorefractionalnumbersfrom3.4e−038to3.4e+038.Notethatyoushouldendthevaluewithan"f": Example floatmyNum=5.75f; System.out.println(myNum); TryitYourself» Double Thedoubledatatypecanstorefractionalnumbersfrom1.7e−308to1.7e+308.Notethatyoushouldendthevaluewitha"d": Example doublemyNum=19.99d; System.out.println(myNum); TryitYourself» Usefloatordouble? Theprecisionofafloatingpointvalueindicateshowmanydigitsthevaluecanhave afterthedecimalpoint. Theprecisionoffloatisonlysixorseven decimaldigits,whiledoublevariableshaveaprecision ofabout15digits.Thereforeitissafertousedoubleformostcalculations. ScientificNumbers Afloatingpointnumbercanalsobeascientificnumberwithan"e"toindicatethepowerof10: Example floatf1=35e3f; doubled1=12E4d; System.out.println(f1); System.out.println(d1); TryitYourself» Booleans Abooleandatatypeisdeclaredwiththebooleankeywordandcanonlytakethevaluestrueorfalse: Example booleanisJavaFun=true; booleanisFishTasty=false; System.out.println(isJavaFun); //Outputstrue System.out.println(isFishTasty); //Outputsfalse TryitYourself» Booleanvaluesaremostlyusedforconditionaltesting,whichyouwilllearnmoreaboutinalaterchapter. Characters Thechardatatypeisusedtostorea singlecharacter.Thecharactermustbe surroundedbysinglequotes,like'A'or'c': Example charmyGrade='B'; System.out.println(myGrade); TryitYourself» Alternatively,youcanuseASCIIvaluestodisplaycertaincharacters: Example charmyVar1=65,myVar2=66,myVar3=67; System.out.println(myVar1); System.out.println(myVar2); System.out.println(myVar3); TryitYourself» Tip:AlistofallASCIIvaluescanbefoundinourASCIITableReference. Strings TheStringdatatypeisusedtostoreasequenceofcharacters(text).Stringvaluesmustbesurroundedbydoublequotes: Example Stringgreeting="HelloWorld"; System.out.println(greeting); TryitYourself» TheStringtypeissomuchusedandintegratedinJava,thatsomecallit"thespecial ninthtype". AStringinJavaisactuallyanon-primitivedatatype,becauseitrefersto anobject.TheStringobjecthasmethodsthatareusedtoperformcertain operationsonstrings.Don'tworryifyoudon'tunderstandtheterm"object"justyet.Wewilllearnmoreaboutstringsandobjectsinalaterchapter. Non-PrimitiveDataTypes Non-primitivedatatypesarecalledreferencetypesbecause theyrefertoobjects. Themaindifferencebetweenprimitiveandnon-primitivedatatypesare: Primitivetypesarepredefined(alreadydefined)inJava.Non-primitivetypesarecreatedbytheprogrammerand isnotdefinedbyJava(exceptforString). Non-primitivetypescanbeusedtocallmethodstoperformcertainoperations,whileprimitivetypescannot. Aprimitivetypehasalwaysavalue,whilenon-primitivetypescanbenull. Aprimitivetypestartswithalowercaseletter,whilenon-primitivetypesstartswithanuppercaseletter. Thesizeofaprimitivetypedependsonthedatatype,whilenon-primitivetypeshaveallthesamesize. Examplesofnon-primitivetypesareStrings,Arrays,Classes,Interface,etc.Youwilllearnmoreabouttheseinalaterchapter. TestYourselfWithExercises Exercise: Addthecorrectdatatypeforthefollowingvariables: myNum=9; myFloatNum=8.99f; myLetter='A'; myBool=false; myText="HelloWorld"; SubmitAnswer» StarttheExercise ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2021 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1[Java] Wrapper Classes 介紹 - iT 邦幫忙
閱讀時間: 10分鐘. Wrapper class 內的物件(object) 是包含基本資料型類別(primitive data types)。 當我們利用Wrapper class創建一個物件...
- 2Primitive 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...
- 3Java 入門指南- 單元3 - 基本資料型態與參考 - 程式語言教學誌
Java 中的變數(variable) 有兩種,一種是基本資料型態(primitive data type) ,另一種則是對物件(object) 的參考(reference). variable...
- 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...
- 5Java Data Types - W3Schools
A primitive data type specifies the size and type of variable values, and it has no additional me...