JavaBasicstutorial

LearningJava basicconcepts, 语法structure and DevelopmentEnvironment Setup

返回tutoriallist

JavaBasicstutorial

Java is a广泛using 计算机programminglanguage, 拥 has "一次writing, to 处run" 跨平台features. 本tutorial将介绍Java basicconcepts, 语法structure and DevelopmentEnvironment Setup, for 您 JavaLearning之旅打 under 坚实Basics.

1. JavaIntroduction

1.1 Java history

Java由Sun Microsystems公司于1995年推出, 最初名 for Oak, after 改名 for Java. Java design理念 is "Write Once, Run Anywhere" (一次writing, to 处run) , 这意味着Java程序可以 in 任何installation了Java虚拟机(JVM) 平台 on run, 而不需要重 new 编译.

1.2 Java 特点

Java具 has 以 under 主要特点:

  • simple 性: Java 语法基于C++, 但移除了指针, 运算符重载etc. complex features, 使language更加 simple 易学.
  • 面向object: Java is a纯面向object programminglanguage, 一切皆object.
  • 平台无关性: Java程序 in JVM on run, 不依赖于specific 硬件 and operationsystem.
  • distributed: Java in 置了networkprogrammingfunctions, 便于Developmentdistributedapplication.
  • 健壮性: Javaproviding了自动memorymanagement (垃圾回收) and exceptionprocessingmechanism, 增强了程序 健壮性.
  • security性: Java具 has 严格 security mechanisms, 防止恶意code 执行.
  • many thread: Javasupport many threadprogramming, 便于Developmentconcurrentapplication.

2. DevelopmentEnvironment Setup

2.1 JDK installation

JDK(Java Development Kit) is JavaDevelopmenttoolpackage, package含了Java编译器(javac), Javarun时environment(JRE) and otherDevelopmenttool. 要开始Javaprogramming, 首先需要installationJDK.

installation步骤:

  1. 访问Oracle官方网站 or OpenJDK网站 under 载适合您operationsystem JDKversion.
  2. runinstallation程序, 按照提示completioninstallation.
  3. configurationenvironmentvariable:
    • 设置JAVA_HOMEenvironmentvariable, 指向JDK installationTable of Contents.
    • 将JDK binTable of Contents添加 to PATHenvironmentvariablein.
  4. verificationinstallation: in commands行inrunjava -version and javac -versioncommands, 查看 is 否显示versioninformation.

2.2 IDE 选择

虽然可以using文本编辑器 and commands行toolforJavaDevelopment, 但using集成Developmentenvironment(IDE)可以improvingDevelopmentefficiency. 常用 Java IDEincluding:

  • IntelliJ IDEA: functions强 big , 智能code提示, is 目 before 最受欢迎 Java IDE之一.
  • Eclipse: open-source, 免费, 插件丰富.
  • NetBeans: open-source, 免费, 界面友 good .

3. Javabasic语法

3.1 第一个Java程序

让我们writing第一个Java程序, 它将 in 屏幕 on 打印"Hello, World!".

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

code解释:

  • public class HelloWorld: 定义了一个名 for HelloWorld 公共class.
  • public static void main(String[] args): 定义了mainmethod, 这 is Java程序 入口点.
  • System.out.println("Hello, World!"): in 控制台输出"Hello, World!"string.

3.2 dataclass型

Java is a强class型language, 每个variable都必须声明其dataclass型. Java dataclass型分 for 两 big class:

3.2.1 basicdataclass型
  • 整数class型: byte(1字节), short(2字节), int(4字节), long(8字节)
  • 浮点class型: float(4字节), double(8字节)
  • 字符class型: char(2字节)
  • booleanclass型: boolean(1位)
3.2.2 引用dataclass型
  • class(Class)
  • interface(Interface)
  • array(Array)

3.3 variable and 常量

variable is storedata containers, 常量 is 固定不变 值.

// variable声明 and 初始化
int age = 18;
double salary = 5000.50;
String name = "张三";

// 常量声明
final double PI = 3.14159;
final int MAX_AGE = 120;

3.4 运算符

Javaproviding了 many 种运算符, 用于执行各种operation:

  • 算术运算符: +, -, *, /, %, ++, --
  • relationships运算符: ==, !=, >, <, >=, <=
  • 逻辑运算符: &&, ||, !
  • 赋值运算符: =, +=, -=, *=, /=, %=
  • 位运算符: &, |, ^, ~, <<, >>, >>>>
  • 条件运算符: ?:

3.5 控制语句

3.5.1 条件语句
// if语句
if (age >= 18) {
    System.out.println("成年人");
} else {
    System.out.println("未成年人");
}

// switch语句
switch (day) {
    case 1:
        System.out.println("星期一");
        break;
    case 2:
        System.out.println("星期二");
        break;
    default:
        System.out.println("other");
        break;
}
3.5.2 循环语句
// for循环
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

// while循环
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;
}

// do-while循环
int j = 0;
do {
    System.out.println(j);
    j++;
} while (j < 10);

4. array

4.1 array 声明 and 初始化

// 声明array
int[] numbers;

// 初始化array
numbers = new int[5];

// 声明并初始化array
int[] scores = {90, 85, 95, 80, 88};

// 二维array
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

4.2 array 遍历

// usingfor循环遍历array
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// using增强for循环遍历array
for (int number : numbers) {
    System.out.println(number);
}

5. method

5.1 method 定义

method is 一段 reusable code块, 用于执行specific task.

// method定义
public static int add(int a, int b) {
    return a + b;
}

// 调用method
int result = add(3, 5);
System.out.println(result); // 输出8

5.2 method parameter and return value

method可以接受parameter, 并可以return value. parameter is method执行所需 输入, return value is method执行 结果.

// 带parameter and return value method
public static double calculateArea(double radius) {
    return Math.PI * radius * radius;
}

// 无parameter has return value method
public static String getGreeting() {
    return "Hello, World!";
}

//  has parameter无return value method
public static void printMessage(String message) {
    System.out.println(message);
}

// 无parameter无return value method
public static void sayHello() {
    System.out.println("Hello!");
}

5.3 method重载

method重载 is 指 in 同一个classin定义 many 个同名method, 但它们 parameterlist不同 (parameter个数, parameterclass型 or parameter顺序不同) .

// method重载example
public static int add(int a, int b) {
    return a + b;
}

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

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

实践case: 计算器程序

现 in , 让我们creation一个 simple 计算器程序, implementationbasic 算术运算.

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println(" simple 计算器");
        System.out.println("请输入第一个数: ");
        double num1 = scanner.nextDouble();
        
        System.out.println("请输入运算符(+, -, *, /): ");
        char operator = scanner.next().charAt(0);
        
        System.out.println("请输入第二个数: ");
        double num2 = scanner.nextDouble();
        
        double result = 0;
        boolean valid = true;
        
        switch (operator) {
            case '+':
                result = add(num1, num2);
                break;
            case '-':
                result = subtract(num1, num2);
                break;
            case '*':
                result = multiply(num1, num2);
                break;
            case '/':
                if (num2 != 0) {
                    result = divide(num1, num2);
                } else {
                    System.out.println("error: 除数不能 for 0");
                    valid = false;
                }
                break;
            default:
                System.out.println("error: 无效 运算符");
                valid = false;
                break;
        }
        
        if (valid) {
            System.out.println("结果: " + result);
        }
        
        scanner.close();
    }
    
    public static double add(double a, double b) {
        return a + b;
    }
    
    public static double subtract(double a, double b) {
        return a - b;
    }
    
    public static double multiply(double a, double b) {
        return a * b;
    }
    
    public static double divide(double a, double b) {
        return a / b;
    }
}

这个计算器程序可以:

  1. from user输入读取两个number and 一个运算符
  2. 根据运算符执行相应 算术运算
  3. processing除数 for 0 circumstances
  4. 显示运算结果

互动练习

练习1: 计算圆 面积

writing一个Java程序, from user输入读取圆 半径, 计算并输出圆 面积.

提示: 圆 面积公式 for S = π * r², 其inπ可以usingMath.PI.

练习2: 判断闰年

writing一个Java程序, from user输入读取一个年份, 判断该年份 is 否 for 闰年.

提示: 闰年 判断规则 is : 能被4整除但不能被100整除, or 者能被400整除.

练习3: arrayoperation

writing一个Java程序, creation一个package含10个整数 array, 计算array元素 平均值, 最 big 值 and 最 small 值.