Java教程

Java控制語句

面向物件程式設計

Java內建類

Java檔案處理

Java錯誤和異常

Java多執行緒

Java同步

Java網路程式設計

Java集合

Java介面

Java資料結構

Java集合演算法

高階Java

Java雜項

Java API和框架

Java類引用

Java有用資源

Java速查表



Java程式結構

// Package Declaration (Optional)
// Example: package mypackage;

// Import Statements (Optional)
// Example: import java.util.Scanner;

// Class Declaration
public class Class_name{
   // Main Method
   public static void main(String[] args) { }
}

列印Hello World

以下程式碼列印Hello World到控制檯:

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

public static void main

main()方法是JVM(Java虛擬機器)開始執行Java程式的起點。

public static void main(String[] args)

輸出 - System.out.println()

我們可以使用System.out.println()在Java中將內容列印到輸出控制檯。

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

println()方法

println()方法用於在Java中列印文字。每次呼叫後都會新增一個新行。

System.out.println("Hello World");

雙引號

在Java中,雙引號用於定義字串字面量。

System.out.println("If you forget the double quotes, a compilation error will occur");

print()方法

println()方法用於在Java中列印文字。每次呼叫後都會新增一個新行。

System.out.print("Hello World");

使用者輸入

在Java中,我們使用Scanner類來獲取使用者輸入。它位於java.util包中。

import java.util.Scanner; 
Scanner myObj = new Scanner(System.in); 
System.out.println("Enter username"); 
String userName = myObj.nextLine();

Java註釋

Java註釋有兩種型別:單行註釋和多行註釋。

單行註釋

Java中的單行註釋以雙斜槓//開頭,它們之間的文字會被Java編譯器忽略。

// This is a comment
System.out.println("Hello World");

多行註釋

Java中的多行註釋以/*開頭,以*/結尾,它們之間的文字會被Java編譯器忽略。

Java中的訪問修飾符

在Java中,訪問修飾符是用於設定類、方法、建構函式和欄位的可訪問性的關鍵字。

訪問修飾符型別

  • public - 可從任何其他類或包訪問。
  • private - 僅限於定義類;無法從外部訪問。
  • protected - 可在同一包內和子類中訪問,即使在不同的包中。
  • 預設(無修飾符) - 只能在同一包中的類內訪問。

變數

Java變數是儲存資料值的容器,每個變數都根據其分配的資料型別定義。

變數型別

  • 區域性變數 - 區域性變數在方法、塊或建構函式內定義,並且只能在其特定作用域內訪問。
  • 例項變數 - 例項變數是非靜態的,在類內但方法、建構函式或塊之外宣告。
  • 靜態變數 - 靜態變數使用static關鍵字在類內宣告,在任何方法、建構函式或塊之外。

內建型別變數

Java 中定義的八種基本資料型別是:int、byte、short、long、float、double、boolean 和 char。

byte

byte 是一種基本資料型別,佔用 8 位記憶體。它可以儲存 -128 到 127 之間的數字。

long

long 是另一種與整數相關的基本資料型別,可以儲存 -9223372036854775808 到 9223372036854775808 之間的整數。long 佔用 64 位記憶體。

float

float 關鍵字是一種資料型別,可以儲存 3.4e-038 到 3.4e+038 之間的浮點數。

char

char 是一個 16 位整數,表示一個 Unicode 編碼的字元。

int

int 關鍵字是一種基本資料型別,可以儲存 -2147483648 到 2147483647 之間的數字。

short

short 關鍵字是一種資料型別,可以儲存 -32768 到 32767 之間的數字。

控制流

if-else 語句

在 Java 中,if-else 語句 根據條件執行程式碼塊。

if (x > 0) { 
   // code block } 
else { 
   // code block } 

switch 語句

switch 語句 選擇要執行的多個程式碼塊之一。它類似於 if-else-if 階梯語句。

switch (day) {     
   case 1: 
   // code block         
   break;
   case 2: 
   // code block
   break;
   default:
   // code block
}

for 迴圈

Java for 迴圈 用於迭代指定次數的程式碼塊。

for (int i = 0; i < 10; i++) { 
   // code block 
}

while 迴圈

Java while 迴圈 用於在條件為真時迭代程式碼塊。

while (x < 10) {
   // code block 
} 

break 語句

Java break 語句 用於在指定條件下終止程式的當前流程。

public class BreakExample {  
   public static void main(String[] args) {  
      for(int i=1;i<=10;i++){  
         if(i==5){  
            //Using Break Statement 
            break;  
         }  
      System.out.println(i);  
      }  
   }  
}

continue 語句

Java continue 語句 用於繼續程式的當前流程。它用於跳轉到程式的下一部分。

public class ContinueExample {  
   public static void main(String[] args) {  
      //for loop  
      for(int i=1;i<=10;i++){  
         if(i==5){  
            continue;//it will jump to the next statement  
         }
         System.out.println(i);
      }
   }  
}

Java 面向物件概念

1. 類和物件

  • - 建立物件的藍圖。
  • 物件 - 類的例項。

2. 繼承

繼承 允許一個類繼承另一個類的欄位和方法。

示例

class Animal {
   void eat() {
      System.out.println("This animal eats food.");
   }
}
class Cat extends Animal {
   void meow() {
      System.out.println("Cat says meow!");
   }
}

public class Main {
   public static void main(String[] args) {
      Cat cat = new Cat();
      cat.eat(); // Output: This animal eats food.
      cat.meow(); // Output: Cat says meow!
   }
}

3. 多型

多型 允許方法根據其作用的物件執行不同的操作。

示例

class Animal {
   void sound() {
      System.out.println("Animal makes sound");
   }
}
class Dog extends Animal {
   void sound() {
      System.out.println("Dog barks");
   }
}
class Cat extends Animal {
   void sound() {
      System.out.println("Cat meows");
   }
}
public class Main {
   public static void main(String[] args) {
      Animal myDog = new Dog();
      Animal myCat = new Cat();
      myDog.sound(); // Output: Dog barks
      myCat.sound(); // Output: Cat meows
   }
}

4. 封裝

封裝 是將資料(變數)和程式碼(方法)包裝在一起作為單個單元的技術。

示例

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

   public double getBalance() {
      return balance;
   }
}
public class Main {
   public static void main(String[] args) {
      BankAccount account = new BankAccount();
      account.deposit(100.0);
      System.out.println("Balance: " + account.getBalance()); // Output: Balance: 100.0
   }
}

5. 抽象

抽象 是隱藏複雜實現細節並僅顯示物件基本特徵的概念。

示例

abstract class Shape {
   abstract void draw();
}
class Circle extends Shape {
   void draw() {
      System.out.println("Drawing a circle");
   }
}
class Rectangle extends Shape {
   void draw() {
      System.out.println("Drawing a rectangle");
   }
}
public class Main {
   public static void main(String[] args) {
      Shape circle = new Circle();
      Shape rectangle = new Rectangle();
      circle.draw(); // Output: Drawing a circle
      rectangle.draw(); // Output: Drawing a rectangle
   }
}

建構函式

在 Java 中,建構函式 是初始化新的類例項的程式碼塊。在建立物件時呼叫它,為其分配記憶體。

建構函式型別

  • 預設建構函式 - 此型別的建構函式不需要任何引數。如果在類中沒有顯式宣告建構函式,編譯器將自動生成一個沒有引數的預設建構函式。
  • 引數化建構函式 - 此型別的建構函式需要引數,用於在初始化期間為類的欄位分配自定義值。

陣列

陣列 是資料結構,用於在連續的記憶體位置儲存相同資料型別的多個值。

一維陣列

int arr[] = new int[20];
int[] arr = new int[20];

示例

public class SingleDimensional {
   public static void main(String[] args) {
      int[] arr = new int[5];
      arr[0] = 10;
      arr[1] = 20;
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50;
      for (int i = 0; i < arr.length; i++) {
         System.out.println("arr[" + i + "] : " + arr[i]);
      }
   }
}

多維陣列

陣列也可以是多維的,允許以矩陣格式儲存資料。

int[][] arr = new int[3][3];
int arr[][] = new int[3][3];

這是一個實現二維陣列的 Java 程式:

public class MultiDimensional {
   public static void main(String args[]) {
      int arr[][] = {
         { 1, 2, 3 },
         { 4, 5, 6 },
         { 7, 8, 9 }
      };
      for (int i = 0; i < arr.length; i++) {
         for (int j = 0; j < arr[i].length; j++) {
            System.out.print(arr[i][j] + " ");
         }
         System.out.println();
      }
   }
}

字串

Java 字串 表示一系列字元。

字串方法

字串連線

字串連線是將兩個或多個字串組合成單個字串的過程。

+ 運算子

String str1 = "Hello, ";
String str2 = "world!";
String result = str1 + str2;

concat() 方法

String str1 = "Hello, ";
String str2 = "world!";
String result = str1.concat(str2);

字串比較

在 Java 中比較字串時,需要注意比較字串引用和字串內容的區別。

使用 equals() 方法

String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = str1.equals(str2);

使用 == 運算子

String str1 = new String("Hello");
String str2 = new String("Hello");
boolean areSameReference = (str1 == str2);

使用 compareTo() 方法

String str1 = "apple";
String str2 = "banana";
int comparisonResult = str1.compareTo(str2);

異常處理

Java 異常處理 是處理執行時錯誤以維持程式流程的過程。

Java try-catch 塊

Try-catch 塊用於處理可能丟擲異常的程式碼。

語法

try { 
   // code that may throw an exception 
} catch (Exception e) { 
   // code to handle the exception 
}

Java finally 塊

finally 塊用於執行無論是否處理異常都要執行的特定程式碼。

示例

public class FinallyExample {
   public static void main(String[] args) {
      try {
         System.out.println("Inside try block.");
         int result = 10 / 0; // This will cause an exception
      } catch (ArithmeticException e) {
         System.out.println("Caught an exception: " + e.getMessage());
      } finally {
         System.out.println("This block always executes.");
      }
   }
}

Java throw 異常

Java throw 關鍵字 用於顯式丟擲異常。

語法

throw new exception_class("error statement ");

示例

public class ThrowExample {
   public static void main(String[] args) {
      try {
         checkAge(15); // This will throw an exception
      } catch (IllegalArgumentException e) {
         System.out.println("Caught an exception: " + e.getMessage());
      }
   }
   static void checkAge(int age) {
      if (age < 18) {
         throw new IllegalArgumentException("Age must be 18 or older.");
      }
      System.out.println("Age is valid.");
   }
}
廣告