java简单代码样例
当提到"简单的Java代码样例"时,具体的示例可能涉及各种不同的主题。
Hello World:
javapublic class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
变量和数据类型:
javapublic class VariableExample {
public static void main(String[] args) {
int num1 = 5;
double num2 = 3.14;
String text = "Hello";
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
System.out.println("Text: " + text);
}
}
条件语句:
javapublic class ConditionalExample {
public static void main(String[] args) {
int x = 10;
if (x > 0) {
System.out.println("Positive number");
} else if (x < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
}
}
循环语句:
javapublic class LoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}
数组:
javapublic class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element " + i + ": " + numbers[i]);
}
}
}
方法:
javapublic class MethodExample {
public static void main(String[] args) {
int result = addNumbers(3, 7);
System.out.println("Sum: " + result);
}
static int addNumbers(int a, int b) {
return a + b;
}
}
类和对象:
javapublic class Dog {
String name;
int age;
// 构造方法
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// 方法
public void bark() {
System.out.println("Woof, woof!");
}
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", 3);
System.out.println("Dog's name: " + myDog.name);
System.out.println("Dog's age: " + myDog.age);
myDog.bark();
}
}
异常处理:
javaimport java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}
集合:
javaimport java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
线程:
javapublic class ThreadExample {
public static void main(String[] args) {
Thread myThread = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
try {
Thread.sleep(1000); // 暂停1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
myThread.start();
}
}