Java技術指南:從基礎到進階的全面概覽
導讀:
Java是一種廣泛使用的程式語言,具有跨平台、物件導向和強大的生態系統等諸多優勢。本文將從基礎到進階逐步介紹Java的核心概念和主要技術,並提供具體的程式碼範例,幫助讀者快速入門並深入理解Java程式設計。
第一部分:Java基礎
int age = 25; double price = 12.5; char grade = 'A'; boolean isValid = true; String name = "John";
if (score >= 90) { System.out.println("优秀"); } else if (score >= 80) { System.out.println("良好"); } else { System.out.println("及格"); } for (int i = 0; i < 10; i++) { System.out.println(i); } while (count > 0) { System.out.println(count); count--; }
int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5; String[] names = {"Alice", "Bob", "Charlie"};
第二部分:物件導向程式設計
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public void sayHello() { System.out.println("Hello, my name is " + name); } } Person person = new Person("John", 25); person.sayHello();
public class Animal { public void makeSound() { System.out.println("Animal makes sound"); } } public class Cat extends Animal { @Override public void makeSound() { System.out.println("Cat says Meow"); } } Animal animal = new Cat(); animal.makeSound();
public interface Drawable { void draw(); } public abstract class Shape implements Drawable { protected int x; protected int y; public Shape(int x, int y) { this.x = x; this.y = y; } @Override public void draw() { System.out.println("Drawing shape at (" + x + ", " + y + ")"); } public abstract double area(); } public class Circle extends Shape { private double radius; public Circle(int x, int y, double radius) { super(x, y); this.radius = radius; } @Override public double area() { return Math.PI * radius * radius; } } Shape shape = new Circle(0, 0, 5); shape.draw(); System.out.println("Area: " + shape.area());
第三部分:Java高階特性
try { int result = divide(10, 0); System.out.println(result); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } public int divide(int num1, int num2) { if (num2 == 0) { throw new ArithmeticException("Divisor cannot be zero"); } return num1 / num2; }
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))) { writer.write("Hello, World!"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); }
public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); thread1.start(); thread2.start();
結語:
本文從Java基礎知識、物件導向程式設計到Java高階特性,對Java技術進行了全面概覽,並提供了具體的程式碼範例。希望本文能幫助讀者快速入門並深入理解Java編程,為進一步學習Java打下良好基礎。
以上是全面了解Java技術:從入門到精通的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!