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到控制台:

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

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

public static void main

main()方法是JVM(Java虚拟机)开始执行Java程序的起点。

public static void main(String[] args)

输出 - System.out.println()

我们可以使用System.out.println()在Java中将内容打印到输出控制台。

Open Compiler
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 语句 用于在指定条件下终止程序的当前流程。

Open Compiler
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 语句 用于继续程序的当前流程。它用于跳转到程序的下一部分。

Open Compiler
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. 继承

继承 允许一个类继承另一个类的字段和方法。

示例

Open Compiler
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. 多态

多态 允许方法根据其作用的对象执行不同的操作。

示例

Open Compiler
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. 封装

封装 是将数据(变量)和代码(方法)包装在一起作为单个单元的技术。

示例

Open Compiler
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. 抽象

抽象 是隐藏复杂实现细节并仅显示对象基本特征的概念。

示例

Open Compiler
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];

示例

Open Compiler
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 程序:

Open Compiler
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 字符串 表示一系列字符。

字符串方法

  • length() - 返回字符串的长度。
  • charAt() - 返回指定索引处的字符。
  • substring() - 返回从指定索引到结尾的子字符串。
  • indexOf() - 返回指定子字符串第一次出现的索引。
  • toLowerCase() - 将字符串转换为小写。
  • toUpperCase() - 将字符串转换为大写。
  • trim() - 删除前导和尾随空格。

字符串连接

字符串连接是将两个或多个字符串组合成单个字符串的过程。

+ 运算符

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 块用于执行无论是否处理异常都要执行的特定代码。

示例

Open Compiler
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 ");

示例

Open Compiler
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."); } }
广告