以下是一些适合 Java 入门的代码示例,涵盖了 Java 的基本语法和常见概念:
public class HelloWorld {
// 主方法,程序的入口点
public static void main(String[] args) {
// 输出语句,打印Hello World!
System.out.println("Hello, World!");
}
}
public class VariablesExample {
public static void main(String[] args) {
// 整数类型
int age = 25;
// 浮点类型
double height = 1.75;
// 字符类型
char grade = 'A';
// 布尔类型
boolean isStudent = true;
// 字符串类型
String name = "John Doe";
// 打印变量值
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("身高: " + height + "米");
System.out.println("成绩等级: " + grade);
System.out.println("是否为学生: " + isStudent);
}
}
public class ConditionalsExample {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
}
}
public class LoopsExample {
public static void main(String[] args) {
// for循环:打印1到5
System.out.println("使用for循环:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// while循环:打印5到1
System.out.println("\n使用while循环:");
int j = 5;
while (j >= 1) {
System.out.println(j);
j--;
}
}
}
public class MethodsExample {
// 定义一个加法方法
public static int add(int a, int b) {
return a + b;
}
// 定义一个乘法方法
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
// 调用方法
int sum = add(num1, num2);
int product = multiply(num1, num2);
System.out.println(num1 + " + " + num2 + " = " + sum);
System.out.println(num1 + " × " + num2 + " = " + product);
}
}
这些示例涵盖了 Java 编程的基础知识,包括类结构、主方法、变量、数据类型、条件语句、循环和方法等核心概念。初学者可以从这些示例开始,逐步理解 Java 的语法规则和编程思想。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。