Java 是一种强类型语言,这意味着每个变量都有明确的数据类型。Java 提供了八种基本数据类型(primitive data types),用于存储简单的值,如数字、字符和布尔值。这些数据类型不依赖于类或对象,因此它们是 Java 程序中最基本和高效的类型。
目录
1. 整数类型
整数类型用于存储没有小数部分的数字。Java 提供了四种整数类型,分别用于存储不同范围的整数值。
数据类型 | 大小 | 范围 | 默认值 |
---|---|---|---|
byte | 1 字节 | -128 到 127 | 0 |
short | 2 字节 | -32,768 到 32,767 | 0 |
int | 4 字节 | -2,147,483,648 到 2,147,483,647 | 0 |
long | 8 字节 | -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 | 0L |
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class IntegerTypes { public static void main(String[] args) { byte byteValue = 100; short shortValue = 10000; int intValue = 1000000; long longValue = 1000000000L; // 注意 long 类型要加上 "L" System.out.println("Byte: " + byteValue); System.out.println("Short: " + shortValue); System.out.println("Int: " + intValue); System.out.println("Long: " + longValue); } } |
2. 浮点类型
浮点类型用于存储带有小数部分的数字。Java 提供了两种浮点类型,分别用于存储不同精度的浮点数。
数据类型 | 大小 | 范围 | 默认值 |
---|---|---|---|
float | 4 字节 | ±1.4E-45 到 ±3.4E+38 | 0.0f |
double | 8 字节 | ±4.9E-324 到 ±1.8E+308 | 0.0d |
示例:
1 2 3 4 5 6 7 8 9 | public class FloatingPointTypes { public static void main(String[] args) { float floatValue = 10.5f; // float 类型要加上 "f" double doubleValue = 100.123456789; System.out.println("Float: " + floatValue); System.out.println("Double: " + doubleValue); } } |
3. 字符类型
字符类型用于存储单个字符,通常用来表示文本中的字母、数字或符号。Java 使用 char
类型来表示字符,它的大小为 2 字节。
数据类型 | 大小 | 范围 | 默认值 |
---|---|---|---|
char | 2 字节 | 0 到 65,535 | ‘\u0000’(空字符) |
示例:
1 2 3 4 5 6 | public class CharType { public static void main(String[] args) { char charValue = 'A'; System.out.println("Char: " + charValue); } } |
Java 中的 char
类型实际上是基于 Unicode 编码的,可以表示世界上几乎所有的字符。
4. 布尔类型
布尔类型用于存储两个可能的值:true
或 false
。它通常用于条件判断中。
数据类型 | 大小 | 范围 | 默认值 |
---|---|---|---|
boolean | 1 字节(实现依赖) | true 或 false | false |
示例:
1 2 3 4 5 6 7 8 9 | public class BooleanType { public static void main(String[] args) { boolean isJavaFun = true; boolean isFishTasty = false; System.out.println("Is Java fun? " + isJavaFun); System.out.println("Is fish tasty? " + isFishTasty); } } |
5. 包装类(Wrapper Classes)
Java 中的基本数据类型(primitive types)都有对应的包装类(wrapper classes),它们是类类型(reference types),并提供了基本数据类型的各种方法。包装类用于将基本类型转化为对象,可以进行一些对象操作,如存储在集合中等。
数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
示例:
1 2 3 4 5 6 7 8 9 10 | public class WrapperClasses { public static void main(String[] args) { // 使用 Integer 类将 int 转为对象 Integer intValue = Integer.valueOf(100); // 装箱 int primitiveValue = intValue.intValue(); // 拆箱 System.out.println("Integer value: " + intValue); System.out.println("Primitive int: " + primitiveValue); } } |
通过包装类,可以方便地将基本数据类型转换为对象,或者将字符串转换为基本类型(如 Integer.parseInt("123")
)。
发表回复