Java學(xué)習(xí)25個JAVA常見代碼示例-值得收藏的筆記
Java,作為一門流行多年的編程語言,始終占據(jù)著軟件開發(fā)領(lǐng)域的重要位置。無論是初學(xué)者還是經(jīng)驗豐富的程序員,掌握J(rèn)ava中常見的代碼和概念都是至關(guān)重要的。本文將列出50個Java常用代碼示例,并提供相應(yīng)解釋,助力你從Java小白成長為架構(gòu)師。
基礎(chǔ)語法
1. Hello World
這是學(xué)習(xí)任何編程語言的第一步,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. 條件判斷
學(xué)習(xí)如何使用 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、while 和 do-while 循環(huán)對于執(zhí)行重復(fù)任務(wù)至關(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. 類與對象
類是對象的藍(lán)圖,對象是類的實例。
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)和復(fù)雜性,只暴露操作該對象的接口。
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í)行多個任務(wù)。
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. 同步
同步是控制多個線程對共享資源訪問的一種機(jī)制。
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í)行任務(wù)并獲取結(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(); // 這將等待任務(wù)完成
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(); // 這將等待任務(wù)完成
System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
以上是Java編程中常見的25個代碼示例,涵蓋了從基礎(chǔ)語法到高級編程概念的多個方面。掌握這些代碼片段將極大提升你的編碼技能,并為成長為一名優(yōu)秀的Java架構(gòu)師打下堅實基礎(chǔ)。持續(xù)實踐和學(xué)習(xí),相信不久的將來,你將在Java的世界里駕輕就熟。
到此這篇關(guān)于Java學(xué)習(xí)25個JAVA常見代碼-值得收藏的筆記的文章就介紹到這了,更多相關(guān)Java學(xué)習(xí)25個JAVA常見代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vscode 配置java環(huán)境并調(diào)試運行的詳細(xì)過程
這篇文章主要介紹了vscode 配置java環(huán)境并調(diào)試運行的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05
springboot使用com.github.binarywang包實現(xiàn)微信網(wǎng)頁上的支付和退款
最近做項目需要實現(xiàn)在pc端需要實現(xiàn)微信的支付,本文主要介紹了springboot使用com.github.binarywang包實現(xiàn)微信網(wǎng)頁上的支付和退款,具有一定的參考價值,感興趣的可以了解一下2024-05-05
spring-boot react如何一步一步實現(xiàn)增刪改查
這篇文章主要介紹了spring-boot react如何一步一步實現(xiàn)增刪改查,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
Java實現(xiàn)將圖片壓縮為GZIP格式并輸出為流的詳細(xì)過程
在Java中,要實現(xiàn)將圖片壓縮為GZIP格式并輸出為流,通常會涉及到以下幾個步驟:讀取圖片文件、創(chuàng)建GZIP壓縮流、將壓縮后的數(shù)據(jù)寫入目標(biāo)流,下面我們將詳細(xì)探討這一過程,并結(jié)合具體代碼示例來說明,需要的朋友可以參考下2025-10-10

