1. 变量和数据类型:
// 声明一个变量
int age;
// 初始化变量
age = 25;
// 声明并初始化变量
int number = 10;
// 数据类型
int intVar = 5;
double doubleVar = 3.14;
char charVar = 'A';
boolean boolVar = true;
String stringVar = "Hello, Java!";
2. 运算符:
// 算术运算符
int sum = 5 + 3;
int difference = 8 - 2;
int product = 4 * 6;
int quotient = 10 / 2;
int remainder = 10 % 3;
// 比较运算符
boolean isEqual = (a == b);
boolean isNotEqual = (a != b);
boolean greaterThan = (a > b);
boolean lessThan = (a < b);
boolean greaterOrEqual = (a >= b);
boolean lessOrEqual = (a <= b);
// 逻辑运算符
boolean andResult = (true && false);
boolean orResult = (true || false);
boolean notResult = !true;
3. 控制流语句:
条件语句 - if、else if、else:
int x = 10;
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
循环语句 - for、while、do-while:
// for 循环
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while 循环
int j = 0;
while (j < 5) {
System.out.println(j);
j++;
}
// do-while 循环
int k = 0;
do {
System.out.println(k);
k++;
} while (k < 5);
Switch 语句:
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ... 其他 case ...
default:
System.out.println("Invalid day");
}
4. 数组:
// 声明和初始化数组
int[] numbers = {1, 2, 3, 4, 5};
// 访问数组元素
int firstNumber = numbers[0];
// 修改数组元素
numbers[1] = 10;
5. 方法(函数):
// 方法定义
public static int addNumbers(int a, int b) {
return a + b;
}
// 方法调用
int result = addNumbers(3, 4);
这只是 Java 基础语法的简要概述。深入学习时,你还需要了解异常处理、面向对象编程等更高级的概念。建议通过实际编写代码和练习来巩固这些基础概念。
转载请注明出处:http://www.zyzy.cn/article/detail/13459/Java