最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java學習25個JAVA常見代碼示例-值得收藏的筆記

 更新時間:2025年11月08日 14:51:33   作者:啊健的影子  
本文列舉了25個Java常用代碼示例,涵蓋了基礎語法、面向?qū)ο缶幊?、高級編程概念等?nèi)容,旨在幫助Java初學者掌握編程技能,從入門到成長為架構(gòu)師

Java,作為一門流行多年的編程語言,始終占據(jù)著軟件開發(fā)領域的重要位置。無論是初學者還是經(jīng)驗豐富的程序員,掌握Java中常見的代碼和概念都是至關(guān)重要的。本文將列出50個Java常用代碼示例,并提供相應解釋,助力你從Java小白成長為架構(gòu)師。

基礎語法

1. Hello World

這是學習任何編程語言的第一步,Java也不例外。

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

2. 數(shù)據(jù)類型

了解Java的基本數(shù)據(jù)類型對編寫程序至關(guān)重要。

int a = 100;          // 整型
float b = 5.25f;      // 浮點型
double c = 5.25;      // 雙精度浮點型
boolean d = true;     // 布爾型
char e = 'A';         // 字符型
String f = "Hello";   // 字符串型
int a = 100;          // 整型
float b = 5.25f;      // 浮點型
double c = 5.25;      // 雙精度浮點型
boolean d = true;     // 布爾型
char e = 'A';         // 字符型
String f = "Hello";   // 字符串型

3. 條件判斷

學習如何使用 if-else 語句來控制程序的流程。

int score = 75;
if (score > 70) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
int score = 75;
if (score > 70) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

4. 循環(huán)結(jié)構(gòu)

掌握 for、whiledo-while 循環(huán)對于執(zhí)行重復任務至關(guān)重要。

for循環(huán)

for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

while循環(huán)

int i = 0;
while (i < 5) {
    System.out.println("Iteration: " + i);
    i++;
}
int i = 0;
while (i < 5) {
    System.out.println("Iteration: " + i);
    i++;
}

do-while循環(huán)

int j = 0;
do {
    System.out.println("Iteration: " + j);
    j++;
} while (j < 5);
int j = 0;
do {
    System.out.println("Iteration: " + j);
    j++;
} while (j < 5);

5. 數(shù)組

數(shù)組是存儲固定大小的同類型元素的集合。

int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 2;
}
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 2;
}

6. 方法定義與調(diào)用

方法允許你將代碼組織成可重用的單元。

public static int multiply(int a, int b) {
    return a * b;
}

public static void main(String[] args) {
    int result = multiply(5, 10);
    System.out.println("Result: " + result);
}
public static int multiply(int a, int b) {
    return a * b;
}

public static void main(String[] args) {
    int result = multiply(5, 10);
    System.out.println("Result: " + result);
}

面向?qū)ο缶幊?/h2>

7. 類與對象

類是對象的藍圖,對象是類的實例。

public class Car {
    String color;

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Car myCar = new Car();
myCar.setColor("Red");
System.out.println("Car color: " + myCar.getColor());
public class Car {
    String color;

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Car myCar = new Car();
myCar.setColor("Red");
System.out.println("Car color: " + myCar.getColor());

8. 構(gòu)造方法

構(gòu)造方法用于在創(chuàng)建對象時初始化對象。

public class Rectangle {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }
}

Rectangle rect = new Rectangle(5, 3);
System.out.println("Area: " + rect.getArea());
public class Rectangle {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }
}

Rectangle rect = new Rectangle(5, 3);
System.out.println("Area: " + rect.getArea());

9. 繼承

繼承允許一個類(子類)繼承另一個類(父類)的屬性和方法。

public class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog barks.");
    }
}

Dog myDog = new Dog();
myDog.eat(); // 繼承的方法
myDog.bark(); // Dog特有的方法
public class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog barks.");
    }
}

Dog myDog = new Dog();
myDog.eat(); // 繼承的方法
myDog.bark(); // Dog特有的方法

10. 接口

接口定義了一組相關(guān)方法的契約,可以被任何類實現(xiàn)。

public interface Runnable {
    void run();
}

public class ThreadImpl implements Runnable {
    public void run() {
        System.out.println("Running via implement Runnable interface");
    }
}

Thread thread = new Thread(new ThreadImpl());
thread.start();
public interface Runnable {
    void run();
}

public class ThreadImpl implements Runnable {
    public void run() {
        System.out.println("Running via implement Runnable interface");
    }
}

Thread thread = new Thread(new ThreadImpl());
thread.start();

11. 抽象類

抽象類不能被實例化,通常作為其他類的基類。

public abstract class Shape {
    abstract double getArea();
}

public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    double getArea() {
        return Math.PI * radius * radius;
    }
}

// Circle circle = new Circle(5); // Cannot instantiate the abstract class
public abstract class Shape {
    abstract double getArea();
}

public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    double getArea() {
        return Math.PI * radius * radius;
    }
}

// Circle circle = new Circle(5); // Cannot instantiate the abstract class

12. 方法重載

方法重載允許在一個類中定義多個同名方法,只要它們的參數(shù)列表不同。

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
System.out.println(calc.add(5, 3));        // 調(diào)用第一個方法
System.out.println(calc.add(5.5, 3.1));    // 調(diào)用第二個方法
System.out.println(calc.add(5, 3, 2));     // 調(diào)用第三個方法
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
System.out.println(calc.add(5, 3));        // 調(diào)用第一個方法
System.out.println(calc.add(5.5, 3.1));    // 調(diào)用第二個方法
System.out.println(calc.add(5, 3, 2));     // 調(diào)用第三個方法

13. 方法重寫

方法重寫是子類中覆蓋繼承自父類的方法。

public class Animal {
    public void sound() {
        System.out.println("Animal sound");
    }
}

public class Bird extends Animal {
    @Override
    public void sound() {
        System.out.println("Tweet tweet");
    }
}

Bird bird = new Bird();
bird.sound(); // 輸出 "Tweet tweet"
public class Animal {
    public void sound() {
        System.out.println("Animal sound");
    }
}

public class Bird extends Animal {
    @Override
    public void sound() {
        System.out.println("Tweet tweet");
    }
}

Bird bird = new Bird();
bird.sound(); // 輸出 "Tweet tweet"

14. 多態(tài)

多態(tài)允許將子類的實例視為父類類型。

public class Animal {
    public void makeSound() {
        System.out.println("Some generic sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

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

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

Animal myAnimal = new Dog();
myAnimal.makeSound(); // Bark
myAnimal = new Cat();
myAnimal.makeSound(); // Meow

15. 封裝

封裝是隱藏對象的內(nèi)部狀態(tài)和復雜性,只暴露操作該對象的接口。

public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }

    public double getBalance() {
        return balance;
    }
}

BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());
public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }

    public double getBalance() {
        return balance;
    }
}

BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());

16. 靜態(tài)變量和方法

靜態(tài)變量和方法是類的一部分,而不是對象的一部分。

public class MathUtils {
    public static final double PI = 3.14159;

    public static double add(double a, double b) {
        return a + b;
    }
    // 其他靜態(tài)方法...
}

double circumference = MathUtils.PI * 2 * 5;
System.out.println("Circumference: " + circumference);
public class MathUtils {
    public static final double PI = 3.14159;

    public static double add(double a, double b) {
        return a + b;
    }
    // 其他靜態(tài)方法...
}

double circumference = MathUtils.PI * 2 * 5;
System.out.println("Circumference: " + circumference);

17. 內(nèi)部類

內(nèi)部類是定義在另一個類中的類。

public class OuterClass {
    private String outerField = "From Outer";

    public class InnerClass {
        public void display() {
            System.out.println(outerField);
        }
    }

    public void createInner() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}

OuterClass outer = new OuterClass();
outer.createInner(); // 輸出 "From Outer"
public class OuterClass {
    private String outerField = "From Outer";

    public class InnerClass {
        public void display() {
            System.out.println(outerField);
        }
    }

    public void createInner() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}

OuterClass outer = new OuterClass();
outer.createInner(); // 輸出 "From Outer"

18. 匿名類

匿名類是沒有名稱的類,常用于實現(xiàn)接口或繼承抽象類。

public class TestAnonymous {
    public void performTask(Runnable task) {
        task.run();
    }

    public static void main(String[] args) {
        TestAnonymous test = new TestAnonymous();
        test.performTask(new Runnable() {
            public void run() {
                System.out.println("Running an anonymous class");
            }
        });
    }
}
public class TestAnonymous {
    public void performTask(Runnable task) {
        task.run();
    }

    public static void main(String[] args) {
        TestAnonymous test = new TestAnonymous();
        test.performTask(new Runnable() {
            public void run() {
                System.out.println("Running an anonymous class");
            }
        });
    }
}

高級編程概念

19. 泛型

泛型允許在編譯時提供類型安全。

public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
    return t;
}

public static void main(String[] args) {
    Box<Integer> integerBox = new Box<>();
    integerBox.set(10);
    System.out.println(integerBox.get()); // 輸出:10
}
public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
    return t;
}

public static void main(String[] args) {
    Box<Integer> integerBox = new Box<>();
    integerBox.set(10);
    System.out.println(integerBox.get()); // 輸出:10
}

20. 集合框架

ArrayList

ArrayList 是一個可變的數(shù)組,允許存儲任意數(shù)量的元素。

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages); // 輸出:[Java, Python, C++]
import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages); // 輸出:[Java, Python, C++]

HashMap

HashMap 是一個鍵值對集合,通過鍵來快速訪問數(shù)據(jù)。

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map.get("Apple")); // 輸出:1
import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map.get("Apple")); // 輸出:1

21. 異常處理

異常處理是程序中錯誤處理的一種方法。

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}

22. 文件I/O

讀取文件

讀取文件是文件I/O操作中的基本功能。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

寫入文件

寫入文件允許將數(shù)據(jù)保存到磁盤上。

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}

23. 多線程

創(chuàng)建線程

多線程允許同時執(zhí)行多個任務。

class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

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

MyThread myThread = new MyThread();
myThread.start();

實現(xiàn)Runnable接口

Runnable 接口提供了另一種創(chuàng)建線程的方式。

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

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

Thread thread = new Thread(new MyRunnable());
thread.start();

24. 同步

同步是控制多個線程對共享資源訪問的一種機制。

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}
public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

25. 高級多線程

使用Executors

Executors 提供了一種更高級的線程管理方式。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
    System.out.println("ExecutorService running");
});

executor.shutdown();
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

Future 和 Callable 允許你異步執(zhí)行任務并獲取結(jié)果。

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<Integer> callableTask = () -> {
    return 10;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);

try {
    Integer result = future.get(); // 這將等待任務完成
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}
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<Integer> callableTask = () -> {
    return 10;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);

try {
    Integer result = future.get(); // 這將等待任務完成
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}

以上是Java編程中常見的25個代碼示例,涵蓋了從基礎語法到高級編程概念的多個方面。掌握這些代碼片段將極大提升你的編碼技能,并為成長為一名優(yōu)秀的Java架構(gòu)師打下堅實基礎。持續(xù)實踐和學習,相信不久的將來,你將在Java的世界里駕輕就熟。

到此這篇關(guān)于Java學習25個JAVA常見代碼-值得收藏的筆記的文章就介紹到這了,更多相關(guān)Java學習25個JAVA常見代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解讀System.getProperty("ENM_HOME")中的值從哪獲取的

    解讀System.getProperty("ENM_HOME")中的值從哪獲取的

    這篇文章主要介紹了解讀System.getProperty("ENM_HOME")中的值從哪獲取的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Spring IOC中的Bean對象用法

    Spring IOC中的Bean對象用法

    這篇文章主要介紹了Spring IOC中的Bean對象用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java微信二次開發(fā)(二) Java微信文本消息接口請求與發(fā)送

    Java微信二次開發(fā)(二) Java微信文本消息接口請求與發(fā)送

    這篇文章主要為大家詳細介紹了Java微信二次開發(fā)第二篇,Java微信文本消息接口請求與發(fā)送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • Java中流的有關(guān)知識點詳解

    Java中流的有關(guān)知識點詳解

    今天小編就為大家分享一篇關(guān)于Java中流的有關(guān)知識點詳解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Java詳解實現(xiàn)多線程的四種方式總結(jié)

    Java詳解實現(xiàn)多線程的四種方式總結(jié)

    哈哈!經(jīng)過一個階段的學習,Java基礎知識學習終于到多線程了!Java多線程以及后面互斥鎖的概念都是Java基礎學習的難點,所以我做了一個總結(jié),希望對大家也有幫助
    2022-07-07
  • 使用Pinyin4j進行拼音分詞的方法

    使用Pinyin4j進行拼音分詞的方法

    下面小編就為大家分享一篇使用Pinyin4j進行拼音分詞的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • Java中HashMap的元素遍歷順序問題及處理

    Java中HashMap的元素遍歷順序問題及處理

    文章總結(jié)了HashMap、LinkedHashMap和TreeMap在遍歷順序上的區(qū)別,HashMap不保證遍歷順序,LinkedHashMap保證插入順序,而TreeMap保證鍵的順序,理解這些特性有助于在編程中選擇合適的Map實現(xiàn)
    2026-01-01
  • JavaWeb讀取配置文件的四種方法

    JavaWeb讀取配置文件的四種方法

    這篇文章主要介紹了JavaWeb讀取配置文件的4種方法,方法一采用ServletContext讀取,方法二采用ResourceBundle類讀取配置信息,方法三采用ClassLoader方式進行讀取配置信息,對javaweb讀取配置文件的四種方法感興趣的朋友參考下吧
    2018-03-03
  • 給Java文件打成獨立JAR包的詳細步驟記錄

    給Java文件打成獨立JAR包的詳細步驟記錄

    這篇文章主要介紹了給Java文件打成獨立JAR包的相關(guān)資料,文中將Java文件打包成獨立的JAR包,包括非Maven和Maven項目的打包步驟,需要的朋友可以參考下
    2024-12-12
  • Kotlin 基礎教程之注解與java中的注解比較

    Kotlin 基礎教程之注解與java中的注解比較

    這篇文章主要介紹了Kotlin 基礎教程之注解與java中的注解比較的相關(guān)資料,需要的朋友可以參考下
    2017-06-06

最新評論

长武县| 淳安县| 宜君县| 黑山县| 综艺| 巴楚县| 嘉黎县| 安化县| 岐山县| 大关县| 宁南县| 阿鲁科尔沁旗| 徐水县| 西丰县| 鄢陵县| 安岳县| 乌苏市| 苏尼特左旗| 广宗县| 汤原县| 张家港市| 井陉县| 鄂托克旗| 建平县| 丘北县| 富裕县| 辽宁省| 洱源县| 揭西县| 紫金县| 利津县| 伊金霍洛旗| 崇仁县| 新泰市| 新蔡县| 马山县| 专栏| 会昌县| 铁岭市| 仁寿县| 兴海县|