本文目录导读:

我们来通过具体的代码案例,一步步实操Java中的数据类型,我将按照 基本数据类型(8种) 和 引用数据类型 的分类,用最直观的代码演示。
准备工作:环境搭建
在开始前,请确保:
- 安装了JDK
- 有一个文本编辑器或IDE(如IntelliJ IDEA、Eclipse)
- 创建一个Java文件,
DataTypeDemo.java
实操一:基本数据类型(8种)
案例1:整数类型(byte, short, int, long)
public class IntegerDemo {
public static void main(String[] args) {
// 1. byte:1字节,范围-128~127
byte myByte = 100;
// byte errorByte = 128; // 编译错误:超出范围
System.out.println("byte值:" + myByte);
// 2. short:2字节
short myShort = 30000;
System.out.println("short值:" + myShort);
// 3. int:4字节,默认整数类型
int myInt = 1000000;
System.out.println("int值:" + myInt);
// 4. long:8字节,注意要加L后缀
long myLong = 10000000000L; // 不加L会报错
long anotherLong = 100L; // 小值也建议加L
System.out.println("long值:" + myLong);
// 进制表示法(实操重点)
int hex = 0xFF; // 16进制,255
int binary = 0b1010; // 2进制,10(JDK7+)
int octal = 077; // 8进制,63(不推荐,容易混淆)
System.out.println("16进制0xFF = " + hex);
System.out.println("2进制0b1010 = " + binary);
}
}
运行结果:
byte值:100
short值:30000
int值:1000000
long值:10000000000
16进制0xFF = 255
2进制0b1010 = 10
案例2:浮点类型(float, double)
public class FloatDemo {
public static void main(String[] args) {
// 1. float:4字节,必须加F/f后缀
float myFloat = 3.14F; // 不加F会报错(默认double)
float scientific = 1.23e-5F; // 科学计数法
System.out.println("float:" + myFloat);
System.out.println("科学计数法:" + scientific);
// 2. double:8字节,默认小数类型
double myDouble = 3.141592653589793;
double scientificD = 1.23e10; // double不需要后缀
System.out.println("double:" + myDouble);
// 精度问题演示(面试常考)
double result = 0.1 + 0.2;
System.out.println("0.1 + 0.2 = " + result);
// 输出:0.30000000000000004(不是精确的0.3)
// 正确的比较方式
double a = 0.1;
double b = 0.2;
double sum = a + b;
double expected = 0.3;
double epsilon = 0.0000001;
if (Math.abs(sum - expected) < epsilon) {
System.out.println("在误差范围内相等");
}
}
}
运行结果:
float:3.14
科学计数法:1.23E-5
double:3.141592653589793
0.1 + 0.2 = 0.30000000000000004
在误差范围内相等
案例3:字符型(char)和布尔型(boolean)
public class CharBooleanDemo {
public static void main(String[] args) {
// 1. char:2字节(Unicode字符)
char letterA = 'A';
char chineseChar = '中';
char unicodeChar = '\u4E2D'; // '中'的Unicode编码
char digitChar = 65; // ASCII值为65的字符'A'
System.out.println("普通字符:" + letterA);
System.out.println("中文:" + chineseChar);
System.out.println("Unicode:" + unicodeChar);
System.out.println("数字65对应的字符:" + digitChar);
// 转义字符
char tab = '\t'; // 制表符
char newline = '\n'; // 换行符
char quote = '\''; // 单引号
System.out.println("转义字符演示:" + tab + "前面有制表符");
// 2. boolean:只有true/false
boolean isJavaFun = true;
boolean isHard = false;
boolean result = (10 > 5); // true
System.out.println("Java好玩吗?" + isJavaFun);
System.out.println("Java难吗?" + isHard);
System.out.println("10>5对吗?" + result);
// boolean不能和数字互换(和C语言不同)
// boolean error = 1; // 编译错误!
}
}
运行结果:
普通字符:A
中文:中
Unicode:中
数字65对应的字符:A
转义字符演示: 前面有制表符
Java好玩吗?true
Java难吗?false
10>5对吗?true
实操二:引用数据类型(重点)
案例4:String字符串
public class StringDemo {
public static void main(String[] args) {
// 1. 字符串创建
String str1 = "Hello"; // 直接赋值
String str2 = new String("World"); // new对象(不推荐)
String str3 = "Hello"; // 与str1指向同一个对象
// 2. 常用方法实操
String full = str1 + " " + str2; // 字符串拼接
System.out.println("拼接结果:" + full);
System.out.println("长度:" + full.length()); // 11
System.out.println("索引4的字符:" + full.charAt(4)); // 'o'
System.out.println("转大写:" + full.toUpperCase());
System.out.println("是否包含'lo':" + full.contains("lo"));
System.out.println("替换:" + full.replace("World", "Java"));
// 3. 重要:比较字符串要用equals
String s1 = "abc";
String s2 = new String("abc");
System.out.println("== 比较:" + (s1 == s2)); // false(比较地址)
System.out.println("equals比较:" + s1.equals(s2)); // true(比较内容)
// 4. 字符串格式化
String formatted = String.format("姓名:%s,年龄:%d", "小明", 25);
System.out.println(formatted);
}
}
运行结果:
拼接结果:Hello World
长度:11
索引4的字符:o
转大写:HELLO WORLD
是否包含'lo':true
替换:Hello Java
== 比较:false
equals比较:true
姓名:小明,年龄:25
案例5:数组(Array)
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// 1. 整数数组
int[] numbers = {10, 20, 30, 40, 50}; // 静态初始化
int[] numbers2 = new int[5]; // 动态初始化,默认值0
System.out.println("第一个元素:" + numbers[0]); // 10
System.out.println("数组长度:" + numbers.length); // 5
// 遍历数组
System.out.print("遍历数组:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
// for-each遍历(更推荐)
System.out.print("for-each遍历:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// 2. 字符串数组
String[] names = {"张三", "李四", "王五"};
System.out.println("名字数组:" + Arrays.toString(names));
// 3. 二维数组(矩阵)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("矩阵[1][2]:" + matrix[1][2]); // 6
// 4. 数组排序
int[] unsorted = {5, 3, 8, 1, 9};
Arrays.sort(unsorted);
System.out.println("排序后:" + Arrays.toString(unsorted));
}
}
运行结果:
第一个元素:10
数组长度:5
遍历数组:10 20 30 40 50
for-each遍历:10 20 30 40 50
名字数组:[张三, 李四, 王五]
矩阵[1][2]:6
排序后:[1, 3, 5, 8, 9]
实操三:类型转换(高频考点)
public class TypeConversionDemo {
public static void main(String[] args) {
// 1. 自动类型转换(小范围 -> 大范围)
int intNum = 100;
long longNum = intNum; // int自动转long
double doubleNum = intNum; // int自动转double
System.out.println("自动转换 int->long: " + longNum);
System.out.println("自动转换 int->double: " + doubleNum);
// 2. 强制类型转换(大范围 -> 小范围,可能丢失精度)
double pi = 3.14159;
int piInt = (int) pi; // 截断小数部分
System.out.println("强制转换 double->int: " + piInt); // 3
long bigLong = 10000000000L;
int smallInt = (int) bigLong; // 数据溢出
System.out.println("溢出转换:" + smallInt); // 可能为负数或其他值
// 3. 字符串与数字转换(面试常考)
// 字符串 -> 数字
String strNum = "123";
int parsedInt = Integer.parseInt(strNum); // 123
double parsedDouble = Double.parseDouble("3.14"); // 3.14
System.out.println("字符串转数字:" + (parsedInt + 1)); // 124
// 数字 -> 字符串
int num = 456;
String strFromInt = String.valueOf(num); // "456"
String strFromInt2 = Integer.toString(num); // "456"
String strFromInt3 = num + ""; // 最简单的但性能差
System.out.println("数字转字符串:" + (strFromInt + 1)); // "4561"
}
}
运行结果:
自动转换 int->long: 100
自动转换 int->double: 100.0
强制转换 double->int: 3
溢出转换:1410065408
字符串转数字:124
数字转字符串:4561
实操四:综合练习 - 学生成绩管理系统
这是一个综合案例,用到了多种数据类型:
public class StudentManager {
public static void main(String[] args) {
// 班级信息
String className = "Java基础班";
int studentCount = 3;
// 学生信息数组
String[] names = {"小明", "小红", "小刚"};
int[] ages = {20, 22, 21};
double[] scores = {85.5, 92.0, 78.5};
boolean[] isPassed = {true, true, false}; // 是否通过
// 计算平均分
double totalScore = 0;
for (double score : scores) {
totalScore += score;
}
double avgScore = totalScore / studentCount;
// 输出班级信息
System.out.println("=== " + className + " 成绩单 ===");
System.out.println("总人数:" + studentCount);
System.out.println("平均分:" + String.format("%.1f", avgScore));
System.out.println("\n学生详情:");
for (int i = 0; i < studentCount; i++) {
System.out.printf("%s(%d岁)- 成绩:%.1f - %s\n",
names[i], ages[i], scores[i],
isPassed[i] ? "【通过】" : "【未通过】");
}
// 查找最高分
double maxScore = scores[0];
String topStudent = names[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > maxScore) {
maxScore = scores[i];
topStudent = names[i];
}
}
System.out.println("\n最高分:" + topStudent + "(" + maxScore + "分)");
}
}
运行结果:
=== Java基础班 成绩单 ===
总人数:3
平均分:85.3
学生详情:
小明(20岁)- 成绩:85.5 - 【通过】
小红(22岁)- 成绩:92.0 - 【通过】
小刚(21岁)- 成绩:78.5 - 【未通过】
最高分:小红(92.0分)
学习建议
- 逐个尝试:先复制一个案例代码,运行成功后再修改数值看效果
- 刻意犯错:故意写一些错误代码,观察编译器报错信息
- 重点记忆:
- float加F后缀,long加L后缀
- 比较字符串用equals()而不是==
- 浮点数比较用误差范围
- 类型转换时小心精度丢失
请打开你的开发环境,从第一个案例开始,动手敲一遍代码吧!遇到问题可以随时问我。