The eight basic data types are: 1. 4 integer types (byte, short, int, long); 2. 2 floating point types (float, double); 3. 1 character type" char"; 4. 1 Boolean type "boolean".
The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.
8 basic data types
There are 8 basic data types in Java, which are used to store integers, floating point numbers, character data and Boolean type data respectively. It should be noted that: What is introduced now is only the basic data types, and many non-basic data types will be introduced later. The basic data types are shown in Figure – 1:
Figure- 1
From Figure- 1 It can be seen that basic data types are mainly divided into 4 major categories (integer type, floating point type, char, boolean), integer types are further divided into 4 subcategories (byte, short, int, long), and floating point types are also divided into There are 2 small categories (float, double). What are the differences between these data types? Figure-2 shows the storage space and usage scenarios of these 8 data types:
Figure- 2
Among the 8 data types above, 5 are the most commonly used, namely int, long, double, char, and boolean. The rest of the data types are almost not used. It is required to focus on mastering these five basic data types. If you are interested in learning about the other data types, you can learn about them.
2. Int type
2.1. Int type
#int is the most commonly used integer type, an int type Variables occupy 4 bytes, which is 32 bits of memory space. The maximum representation range of Int is: -231~231-1, that is, -2147483648 ~2147483647, which is about plus or minus 2.1 billion.2.2. Integer literals are int types
The so-called integer literals (literal) are integers written directly, for example: the following In the statement, 100 is the direct quantity.
int a = 100; int a = 100;Regarding integer direct quantities, you need to pay attention to the following points:
The type of integer direct quantities defaults to the int type. If the directly written integer exceeds the int If the expression range is exceeded, a compilation error will occur. The following statement is a compilation error caused by exceeding the range of integers.
int d = 10000000000; // 編譯錯誤10000000000這個數(shù)值寫出來就是錯誤的,因為Java認為所有直接寫出的整數(shù)都是int類型,而這個數(shù)值超過了int的表達范圍。 int d = 10000000000; // 編譯錯誤10000000000這個數(shù)值寫出來就是錯誤的,因為Java認為所有直接寫出的整數(shù)都是int類型,而這個數(shù)值超過了int的表達范圍。
In addition to the usual decimal number form, integer literals can also be written in hexadecimal form (starting with 0X or 0x) or octal form (starting with 0), Please see the following three expressions of direct quantities:
int a = 100000; // 10進制 int b = 0x186a0; // 16進制 int c = 0303240; // 8進制 int a = 100000; // 10進制 int b = 0x186a0; // 16進制 int c = 0303240; // 8進制
2.3. Rounding in integer data division operations
If two integers are divided, they will be discarded. The decimal part (note: not rounded), the result is also an integer. The sample code is as follows:int c = 5/3; System.out.println(c); // c的值為1,取整 int total = 87; int error = 23; int percent = error / total * 100; System.out.println(percent+"%"); //結(jié)果為0%,23除以87整數(shù)部分為0,乘以100,為0 percent = 100 * error / total; System.out.println(percent + "%"); // 結(jié)果為26%,230除以87整數(shù)部分為26 int c = 5/3; System.out.println(c); // c的值為1,取整 int total = 87; int error = 23; int percent = error / total * 100; System.out.println(percent+"%"); //結(jié)果為0%,23除以87整數(shù)部分為0,乘以100,為0 percent = 100 * error / total; System.out.println(percent + "%"); // 結(jié)果為26%,230除以87整數(shù)部分為26
2.4. To prevent overflow during operation
When two integers are operated on, The result may exceed the range of the integer and cause overflow. If the positive number is too large, the result will be a negative number; if the negative number is too large, the result will be a positive number. The sample code is as follows:
int a = 2147483647; //int類型整數(shù)的上限 int b = -2147483648; //int類型整數(shù)的下限 a = a + 1; b = b - 1; System.out.println("a=" + a); //輸出結(jié)果: a=-2147483648 溢出,結(jié)果錯誤。 System.out.println("b=" + b); //輸出結(jié)果: b=2147483647溢出,結(jié)果錯誤。 int a = 2147483647; //int類型整數(shù)的上限 int b = -2147483648; //int類型整數(shù)的下限 a = a + 1; b = b - 1; System.out.println("a=" + a); //輸出結(jié)果: a=-2147483648 溢出,結(jié)果錯誤。 System.out.println("b=" + b); //輸出結(jié)果: b=2147483647溢出,結(jié)果錯誤。
3. long type
3.1. long type
When representing integers, if the range of the int type is not enough, you can use the long type. A long type variable occupies 8 bytes (that is, 64 bits), and the maximum representation range is: -263 ~ 263-1, that is -9223372036854775808 ~ 9223372036854775807.
If you want to express a long direct quantity, it needs to end with L or l. The sample code is as follows:
long a = 10000000000; //會有編譯錯誤,因為10000000000編譯器認為是int類型,而這個值,已經(jīng)超出了int的范圍 long b = 10000000000l; //正確 long a = 10000000000; //會有編譯錯誤,因為10000000000編譯器認為是int類型,而這個值,已經(jīng)超出了int的范圍 long b = 10000000000l; //正確
3.2. Use long type for larger integer operations
For larger integer operations (more than int Expression range), long type can be used. The sample code is as follows:
long distance1 = 10000 * 365 * 24 * 60 * 60 * 299792458l; //必須有一個long型數(shù)據(jù)參與的運算結(jié)果才是long型 System.out.println("distance1="+distance1);//distance1=547836957965889536 結(jié)果正確 long distance2 = 10000 * 365 * 24 * 60 * 60 * 299792458; System.out.println("distance2="+ distance2); //distance2=-1973211136 溢出,=號后面的數(shù)據(jù)默認為int類型,超出了范圍,發(fā)生溢出。 long distance1 = 10000 * 365 * 24 * 60 * 60 * 299792458l; //必須有一個long型數(shù)據(jù)參與的運算結(jié)果才是long型 System.out.println("distance1="+distance1);//distance1=547836957965889536 結(jié)果正確 long distance2 = 10000 * 365 * 24 * 60 * 60 * 299792458; System.out.println("distance2="+ distance2); //distance2=-1973211136 溢出,=號后面的數(shù)據(jù)默認為int類型,超出了范圍,發(fā)生溢出。
3.3. Store date and time through time milliseconds
JDK provides the System.currentTimeMillis() method, which returns January 1, 1970 The number of milliseconds elapsed from zero to this moment is too large, so its data type is long. The sample code is as follows:long time = System.currentTimeMillis(); System.out.println(time); //輸出的結(jié)果為: 1383835712828 long time = System.currentTimeMillis(); System.out.println(time); //輸出的結(jié)果為: 1383835712828
It can be seen from the above code that the output result has exceeded the maximum value of the int type. Therefore, the return type designed by the JDK is long. This method often is used for timing operations.
4. double類型
4.1. 使用double進行浮點數(shù)的運算
前面所學習的int、long都是用于存儲整數(shù)的,小數(shù)即為浮點數(shù),包括: float(單精度)和double(雙精度),double類型的精度值是float類型的兩倍,因此而得名雙精精,在實際的應用開發(fā)中,float應用極少,大多數(shù)場合使用double表示浮點數(shù)。示例代碼如下:
double pi = 3.14; double r = 8; double s = pi * r * r; System.out.println("s=" + s); // 輸出的結(jié)果為:s=200.96 double pi = 3.14; double r = 8; double s = pi * r * r; System.out.println("s=" + s); // 輸出的結(jié)果為:s=200.96
4.2. 浮點數(shù)直接量是double類型
浮點數(shù)的直接量有兩種寫法:1)通常寫法,如:3.14、314、0.1、.5。 2)科學計數(shù)法,如:1.25E2、1.25e2、1.25E-2。其中,1.25E2表示1.25乘以10的2次方。
默認的浮點直接量為double型,如果需要表示float類型的直接量,需要加“f”或“F”后綴。例如:
float f1 = 3.14 //編譯錯誤,應該寫成3.14f float f1 = 3.14 //編譯錯誤,應該寫成3.14f
4.3. double運算時會出現(xiàn)舍入誤差
2進制系統(tǒng)中無法精確的表示1/10,就好像十進制系統(tǒng)中無法精確的表示1/3一樣,
所以,2進制表示10進制會有一些舍入誤差,對于一些要求精確運算的場合會導致代碼的缺陷。示例代碼如下所示:
double money = 3.0; double price = 2.9; System.out.println(money - price); //輸出的結(jié)果是: 0.10000000000000009 double money = 3.0; double price = 2.9; System.out.println(money - price); //輸出的結(jié)果是: 0.10000000000000009
如果需要精確的運算可以考慮放棄使用double或float而采用BigDecimal 類來實現(xiàn)。關(guān)于這一點,將在后續(xù)的章節(jié)中介紹。
5. char類型
5.1. char類型
字符類型char事實上是一個16位無符號整數(shù)(都是正數(shù)),這個值是對應字符的編碼,Java字符類型采用Unicode字符集編碼(通用碼、統(tǒng)一碼、萬國碼),而Unicode是世界通用的定長字符集,所有的字符都是16位來表示。例如:字符a實際的值為97,字符A實際的值為65,字符0實際的值為48。
字符直接量可以采用諸如:‘中’的形式,也可以采用16進制的表示形式,例如: ‘\u4e2d’,代碼如下所示:
char c1 = ‘中’; //c1中存的是”中”的編碼 char c2 = '\u4e2d'; //‘4e2d’為‘中’所對應的16位Unicode編碼的16進制表示形式 System.out.println(c1); System.out.println(c2); char c1 = ‘中’; //c1中存的是”中”的編碼 char c2 = '\u4e2d'; //‘4e2d’為‘中’所對應的16位Unicode編碼的16進制表示形式 System.out.println(c1); System.out.println(c2);
如上代碼的輸出結(jié)果:c1的值為中,c2值也為中,但c1和c2內(nèi)部存儲的其實是”中”這個字符所對應的Unicode碼,即:一個無符號的整數(shù)。
5.2. 對char型變量賦值
在對char型變量賦值時,可以采用如下三種方式:
方式一:
字符直接量:形如‘A’,變量中實際存儲的是該字符的Unicode編碼(無符號整數(shù)值),一個char型變量只能存儲一個字符。示例如下:
char c1 = 'A'; char c1 = 'A';
方式二:
整型直接量:范圍在0~65535之間的整數(shù),變量中實際存儲的即該整數(shù)值,但表示的是該整數(shù)值所對應的Unicode字符。示例如下:
char c2 = 65; char c2 = 65;
Unicode形式:形如‘\u0041’,Unicode字符的16進制形式。示例如下:
char c3 = '\u0041'; char c3 = '\u0041';
5.3. 使用轉(zhuǎn)義字符
字符直接量需要包含在一對’’單引號之中,那如果想表示單引號’的字符時,需要怎么表示?想表示回車、換行符時,怎么表示?
因為單引號為特殊意義的字符, 那么,對于不方便輸出的字符可以采用轉(zhuǎn)義字符來表示,示例代碼如下:
char c = '\\'; System.out.println(c); //輸出的結(jié)果為:\ char c = '\\'; System.out.println(c); //輸出的結(jié)果為:\
常用轉(zhuǎn)義字符如下圖 – 2所示:
圖- 2
6. boolean類型
6.1. 使用boolean變量進行關(guān)系運算
boolean類型適用于關(guān)系、邏輯運算, 表示某個條件是否成立, 只允許取值true或false,true表示條件成立, 而false表示條件不成立。
boolean型變量經(jīng)常用于存儲關(guān)系運算的結(jié)果,所謂關(guān)系運算就是比較兩個變量的大小相等等關(guān)系(此知識點,后續(xù)詳細介紹)。boolean示例代碼如下所示:
int age = 18; boolean isChild = age<16; System.out.println(isChild); // isChild的值為false boolean running = true; boolean closed = false; int age = 18; boolean isChild = age<16; System.out.println(isChild); // isChild的值為false boolean running = true; boolean closed = false;
7. 基本類型間轉(zhuǎn)換
7.1. 類型間轉(zhuǎn)換
不同的基本類型直接可以相互轉(zhuǎn)化,主要有兩種方式:
自動類型轉(zhuǎn)化(隱式類型轉(zhuǎn)換):從小類型到大類型可以自動完成。類型的大小關(guān)系如下圖 - 3所示:
圖- 3
強制轉(zhuǎn)化:從大類型到小類型需要強制轉(zhuǎn)換符,語法如下:
(需要轉(zhuǎn)換成的類型)變量
因為大類型的精度值大于小類型,取值范圍大于小類型,所以,當使用強制轉(zhuǎn)化時,有可能會造成精度的損失或者溢出,所以,在使用強制轉(zhuǎn)化時要求顯式的告訴編譯器,正在進行強制轉(zhuǎn)換。
7.2. 強制轉(zhuǎn)換時的精度喪失和溢出
基本類型轉(zhuǎn)化如下示例所示,注意強制轉(zhuǎn)換時可能會造成的精度喪失和溢出。
int a = 100; int b = 200; long c = a + b; //自動將int轉(zhuǎn)化為long long l1 = 1024l; int i = (int) l1; //需要加強制轉(zhuǎn)化符由于1024在int的范圍內(nèi),所以沒有產(chǎn)生溢出 long l = 1024L * 1024 * 1024 * 4; int j = (int) l; //會產(chǎn)生溢出 System.out.println(j); // 結(jié)果為:0 double pi = 3.1415926535897932384; float f = (float) pi; //會造成精度的損失,因為單精度的精確度小于double System.out.println(f); //結(jié)果為:3.1415927 int a = 100; int b = 200; long c = a + b; //自動將int轉(zhuǎn)化為long long l1 = 1024l; int i = (int) l1; //需要加強制轉(zhuǎn)化符由于1024在int的范圍內(nèi),所以沒有產(chǎn)生溢出 long l = 1024L * 1024 * 1024 * 4; int j = (int) l; //會產(chǎn)生溢出 System.out.println(j); // 結(jié)果為:0 double pi = 3.1415926535897932384; float f = (float) pi; //會造成精度的損失,因為單精度的精確度小于double System.out.println(f); //結(jié)果為:3.1415927
7.3. 數(shù)值運算時的自動轉(zhuǎn)換
如果在一個表達式中出現(xiàn)了多種數(shù)據(jù)類型,則運算結(jié)果會自動的向較大的類型進行轉(zhuǎn)化,
示例如下:
//由于有l(wèi)ong型的直接量參與,整個表達式的結(jié)果為long long distance = 10000 * 365 * 24 * 60 * 60 * 299792458l; //由于有double型的直接量599.0參與,整個表達式的結(jié)果為 double double change = 800 - 599.0; //結(jié)果為0.0,右邊都是int型數(shù)據(jù)運算結(jié)果也為int類型,結(jié)果為0,再賦值給double 將0轉(zhuǎn)化為 0.0 double persent1 = 80 / 100; //結(jié)果為0.8,右邊表達式有double型直接量參與, 運算結(jié)果為double型 double persent2 = 80.0 / 100; //由于有l(wèi)ong型的直接量參與,整個表達式的結(jié)果為long long distance = 10000 * 365 * 24 * 60 * 60 * 299792458l; //由于有double型的直接量599.0參與,整個表達式的結(jié)果為 double double change = 800 - 599.0; //結(jié)果為0.0,右邊都是int型數(shù)據(jù)運算結(jié)果也為int類型,結(jié)果為0,再賦值給double 型,將0轉(zhuǎn)化為 0.0 double persent1 = 80 / 100; //結(jié)果為0.8,右邊表達式有double型直接量參與, 運算結(jié)果為double型 double persent2 = 80.0 / 100;
7.4. byte、char、short轉(zhuǎn)換為int
在前面所介紹的8種數(shù)據(jù)類型中,byte、char、short、int、long都表示整數(shù)類型,而整型的直接量為int,在實際使用中,為了方便使用,遵循了如下的規(guī)則:
int直接量可以直接賦值給byte、char和short,只要不超過其表示范圍。示例如下:
byte b = 97; short s = 97; char c = 97; byte b = 97; short s = 97; char c = 97;
byte、char、short三種類型參與運算時,先一律轉(zhuǎn)換成int類型再進行運算。示例如下:
byte b = 97; int num = b + b; //num的值為194
相關(guān)視頻教程推薦:Java視頻教程
The above is the detailed content of What are the eight basic data types?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
