50个JAVA常见代码大全:学完这篇从Java小白到架构师

07-21 1322阅读

50个JAVA常见代码大全:学完这篇从Java小白到架构师

Java,作为一门流行多年的编程语言,始终占据着软件开发领域的重要位置。无论是初学者还是经验丰富的程序员,掌握Java中常见的代码和概念都是至关重要的。本文将列出50个Java常用代码示例,并提供相应解释,助力你从Java小白成长为架构师。

50个JAVA常见代码大全:学完这篇从Java小白到架构师
(图片来源网络,侵删)

基础语法

1. Hello World

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

2. 数据类型

int a = 100;
float b = 5.25f;
double c = 5.25;
boolean d = true;
char e = 'A';
String f = "Hello";

3. 条件判断

if (a > b) {
    // 条件成立时执行
} else if (a == b) {
    // 另一个条件
} else {
    // 条件都不成立时执行
}

4. 循环结构

for循环
for (int i = 0; i  
while循环
int i = 0;
while (i  
do-while循环
int i = 0;
do {
    System.out.println("i: " + i);
    i++;
} while (i  

5. 数组

int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
// ...
int[] arr2 = {1, 2, 3, 4, 5};

6. 方法定义与调用

public static int add(int a, int b) {
    return a + b;
}
int sum = add(5, 3); // 调用方法

面向对象编程

7. 类与对象

public class Dog {
    String name;
    public void bark() {
        System.out.println(name + " says: Bark!");
    }
}
Dog myDog = new Dog();
myDog.name = "Rex";
myDog.bark();

8. 构造方法

public class User {
    String name;
    public User(String newName) {
        name = newName;
    }
}
User user = new User("Alice");

9. 继承

public class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}
public class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}
Dog dog = new Dog();
dog.eat(); // 继承自Animal
dog.bark();

10. 接口

public interface Animal {
    void eat();
}
public class Dog implements Animal {
    public void eat() {
        System.out.println("The dog eats.");
    }
}
Dog dog = new Dog();
dog.eat();

11. 抽象类

public abstract class Animal {
    abstract void eat();
}
public class Dog extends Animal {
    void eat() {
        System.out.println("The dog eats.");
    }
}
Animal dog = new Dog();
dog.eat();

12. 方法重载

public class Calculator {
    int add(int a, int b) {
        return a + b;
   ```java
    double add(double a, double b) {
        return a + b;
    }
    int add(int a, int b, int c) {
        return a + b + c;
    }
}
Calculator calc = new Calculator();
calc.add(5, 3); // 调用第一个方法
calc.add(5.0, 3.0); // 调用第二个方法
calc.add(5, 3, 2); // 调用第三个方法

13. 方法重写

public class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}
public class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}
Animal myDog = new Dog();
myDog.makeSound(); // 输出 "Bark"

14. 多态

public class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}
public class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}
public class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow");
    }
}
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Bark
myAnimal = new Cat();
myAnimal.makeSound(); // Meow

15. 封装

public class Account {
    private double balance;
    public Account(double initialBalance) {
        if(initialBalance > 0) {
            balance = initialBalance;
        }
    }
    public void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
        }
    }
    public void withdraw(double amount) {
        if(amount 
            balance -= amount;
        }
    }
    public double getBalance() {
        return balance;
    }
}
Account myAccount = new Account(50);
myAccount.deposit(150);
myAccount.withdraw(75);
System.out.println(myAccount.getBalance()); // 应输出:125.0

    public static final double PI = 3.14159;
    public static double add(double a, double b) {
        return a + b;
    }
    public static double subtract(double a, double b) {
        return a - b;
    }
    public static double multiply(double a, double b) {
        return a * b;
    }
}
double circumference = MathUtils.PI * 2 * 5;
System.out.println(circumference); // 打印圆的周长

    private String msg = "Hello";
    class InnerClass {
        void display() {
            System.out.println(msg);
        }
    }
    public void printMessage() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}
OuterClass outer = new OuterClass();
outer.printMessage(); // 输出 "Hello"

    abstract int dollarsOff();
}
public class Store {
    public SaleTodayOnly sale = new SaleTodayOnly() {
        int dollarsOff() {
            return 3;
        }
    };
}
Store store = new Store();
System.out.println(store.sale.dollarsOff()); // 应输出3

    private T t;
    public void set(T t) {
        this.t = t;
    }
    public T get() {
        return t;
    }
}
Box
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}

    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}

    public void run() {
        System.out.println("MyThread running");
    }
}
MyThread myThread = new MyThread();
myThread.start();

    public void run() {
        System.out.println("MyRunnable running");
    }
}
Thread thread = new Thread(new MyRunnable());
thread.start();

    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public synchronized int getCount() {
        return count;
    }
}
h425. 高级多线程/h4 h5使用Executors/h5 pre class="brush:python;toolbar:false"import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> { System.out.println("ExecutorService running"); }); executor.shutdown();
Future和Callable
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
Callable callableTask = () -> {
    return 10;
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(callableTask);
try {
    Integer result = future.get(); // this will wait for the task to finish
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}

以上就是Java常见的50个代码示例,涵盖了从基础到高级的多方面知识。掌握这些代码片段将极大提升你的编码技能,并为成长为一名优秀的Java架构师打下坚实基础。持续实践和学习,相信不久的将来,你将在Java的世界里驾轻就熟。

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]