学习 Java 的基本语法规则和数据类型
public class MyClass { // 类定义
public static void main(String[] args) { // 主方法
// 程序代码
System.out.println("Hello");
}
}Java 是强类型语言,所有变量必须先声明类型才能使用。
| 类型 | 大小 | 范围 | 默认值 | 示例 |
|---|---|---|---|---|
| byte | 1字节 | -128 ~ 127 | 0 | byte b = 100; |
| short | 2字节 | -32768 ~ 32767 | 0 | short s = 1000; |
| int | 4字节 | -2^31 ~ 2^31-1 | 0 | int i = 100000; |
| long | 8字节 | -2^63 ~ 2^63-1 | 0L | long l = 100000L; |
| float | 4字节 | 单精度浮点数 | 0.0f | float f = 3.14f; |
| double | 8字节 | 双精度浮点数 | 0.0d | double d = 3.14; |
| char | 2字节 | Unicode 字符 | '\u0000' | char c = 'A'; |
| boolean | 1位 | true 或 false | false | boolean b = true; |
public class DataTypeDemo {
public static void main(String[] args) {
// 整数类型
int age = 25;
long population = 7800000000L;
// 浮点类型
float price = 99.99f;
double pi = 3.14159265359;
// 字符类型
char grade = 'A';
// 布尔类型
boolean isStudent = true;
// 输出
System.out.println("年龄: " + age);
System.out.println("人口: " + population);
System.out.println("价格: " + price);
System.out.println("π: " + pi);
System.out.println("等级: " + grade);
System.out.println("是学生: " + isStudent);
}
}// 声明单个变量
int age;
String name;
// 声明多个变量
int x, y, z;
// 声明并初始化
int count = 0;
String message = "Hello";
// 常量(使用 final 关键字)
final double PI = 3.14159;
final int MAX_SIZE = 100;// 创建字符串
String name = "Alice";
String greeting = "Hello, World!";
// 字符串拼接
String fullName = "Alice" + " " + "Smith";
// 字符串方法
int length = name.length(); // 获取长度
String upper = name.toUpperCase(); // 转大写
String lower = name.toLowerCase(); // 转小写
boolean contains = name.contains("li"); // 包含判断
char firstChar = name.charAt(0); // 获取字符// 声明数组
int[] numbers;
String[] names;
// 创建数组
numbers = new int[5]; // 创建长度为5的数组
names = new String[]{"Alice", "Bob", "Charlie"};
// 声明并初始化
int[] scores = {90, 85, 92, 88, 95};
// 访问数组元素
int firstScore = scores[0]; // 90
int lastScore = scores[4]; // 95
// 数组长度
int length = scores.length; // 5小范围类型自动转换为大范围类型。
byte b = 10;
int i = b; // byte → int(自动转换)
int num = 100;
long l = num; // int → long(自动转换)
float f = 3.14f;
double d = f; // float → double(自动转换)大范围类型转换为小范围类型,可能丢失精度。
double d = 3.14;
int i = (int)d; // 3(小数部分丢失)
long l = 100L;
int num = (int)l; // long → int
int x = 128;
byte b = (byte)x; // 可能溢出判断以下变量声明是否正确:
int age = 25.5;
String name = "Alice";
char c = "A";
以下哪个不是 Java 的基本数据类型?
声明一个整型变量 age 并赋值为 25: