Java Basic
Contents
Java
配置settings
默认读取位置
- ~/.m2
curl -O https://repo1.maven.org/maven2/archetype-catalog.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>/home/sugar/.m2/repository</localRepository>
<mirrors>
<mirror>
<id>alimaven</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>https://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>archetype-catalog</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<archetypeCatalog>file:///Users/sugar/.m2/archetype-catalog.xml</archetypeCatalog>
</properties>
</profile>
</profiles>
</settings>
# 手动下载依赖
mvn -B -f pom.xml -s /usr/share/maven/ref/settings.xml dependency:resolve
# 打包
mvn package
一、基础
1、helloworld
java 的包名需要和目录一致,类名需要与文件名一致
[sugar@Sugar java]🐳 tree .
.
└── Hello
└── Hello.java
1 directory, 1 file
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
[root@Sugar j1]🐳 java Hello.java
Hello, world!
2、变量定义
int n = 100;
n = 200; // 变量n赋值为200
int i2 = -2147483648;
int i3 = 2_000_000_000; // 加下划线更容易识别
int i4 = 0xff0000; // 十六进制表示的16711680
int i5 = 0b1000000000; // 二进制表示的512
long n1 = 9000000000000000000L; // long型的结尾需要加L
long n2 = 900; // 没有加L,此处900为int,但int类型可以赋值给long
int i6 = 900L; // 错误:不能把long型赋值给int
float f1 = 3.14f;
float f2 = 3.14e38f; // 科学计数法表示的3.14x10^38
float f3 = 1.0; // 错误:不带f结尾的是double类型,不能赋值给float
double d = 1.79e308;
double d2 = -1.79e308;
double d3 = 4.9e-324; // 科学计数法表示的4.9x10^-324
boolean b1 = true;
boolean b2 = false;
boolean isGreater = 5 > 3; // 计算结果为true
int age = 12;
boolean isAdult = age >= 18; // 计算结果为false
final double PI = 3.14; // PI是一个常量
double r = 5.0;
double area = PI * r * r;
var sb = new StringBuilder();
String s = "hello";
final double PI = 3.14; // PI是一个常量
// 初始化一个对象
Pet dog = new Pet();
// 初始化一个数组
int[] arr = new int[10];
String wepublic = "github";
String wepublic = new String();
String wepublic = new String("github");
public class RunoobTest {
// 成员变量
private int instanceVar;
// 静态变量
private static int staticVar;
public void method(int paramVar) {
// 局部变量
int localVar = 10;
// 使用变量
instanceVar = localVar;
staticVar = paramVar;
System.out.println("成员变量: " + instanceVar);
System.out.println("静态变量: " + staticVar);
System.out.println("参数变量: " + paramVar);
System.out.println("局部变量: " + localVar);
}
public static void main(String[] args) {
RunoobTest v = new RunoobTest();
v.method(20);
}
}
三元运算
public class Main {
public static void main(String[] args) {
int n = -100;
int x = n >= 0 ? n : -n;
System.out.println(x);
}
}
数组
public class Main {
public static void main(String[] args) {
// 5位同学的成绩:
int[] ns;
ns = new int[] { 68, 79, 91, 85, 62 };
System.out.println(ns.length); // 5
ns = new int[] { 1, 2, 3 };
System.out.println(ns.length); // 3
}
}
流程控制
public class Main {
public static void main(String[] args) {
System.out.print("A,");
System.out.print("B,");
System.out.println("END");
}
}
// 格式化输出
public class Main {
public static void main(String[] args) {
double d = 3.1415926;
System.out.printf("%.2f\n", d); // 显示两位小数3.14
System.out.printf("%.4f\n", d); // 显示4位小数3.1416
}
}
// 输入
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // 创建Scanner对象
System.out.print("Input your name: "); // 打印提示
String name = scanner.nextLine(); // 读取一行输入并获取字符串
System.out.print("Input your age: "); // 打印提示
int age = scanner.nextInt(); // 读取一行输入并获取整数
System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
}
}
// if
public class Main {
public static void main(String[] args) {
int n = 70;
if (n >= 60) {
System.out.println("及格了");
} else {
System.out.println("挂科了");
}
System.out.println("END");
}
}
// switch
// switch
public class Main {
public static void main(String[] args) {
int option = 1;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
System.out.println("Selected 2");
break;
case 3:
System.out.println("Selected 3");
break;
}
switch (grade / 10) {
case 10,9 -> System.out.println("该学生成绩优秀");
case 8 -> System.out.println("该学生成绩良好");
case 7 -> System.out.println("该学生成绩中等");
case 6 -> System.out.println("该学生成绩基本合格");
default -> System.out.println("该学生成绩不合格");
}
}
// while
public class Main {
public static void main(String[] args) {
int sum = 0;
int m = 20;
int n = 100;
// 使用while计算M+...+N:
while (false) {
}
System.out.println(sum);
}
}
// do-while
public class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1;
do {
sum = sum + n;
n ++;
} while (n <= 100);
System.out.println(sum);
}
}
// for
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<=100; i++) {
sum = sum + i;
}
System.out.println(sum);
}
}
// 不设置结束条件:
for (int i=0; ; i++) {
...
}
// 不设置结束条件和更新语句:
for (int i=0; ;) {
...
}
// 什么都不设置:
for (;;) {
...
}
// for each
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
for (int n : ns) {
System.out.println(n);
}
}
}
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 4, 5, 6, 9, 10};
for (int number : numbers) {
System.out.print(number + "\t");
}
}
}
数组操作
int[] ns = { 1, 1, 2, 3, 5, 8 };
for (int n : ns) {
System.out.print(n + ", ");
}
// 遍历数组
import java.util.Arrays;
// 标准库操作
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 1, 2, 3, 5, 8 };
System.out.println(Arrays.toString(ns));
}
}
public class EnforceTraverseTest {
public static void main(String[] args) {
String[] arr = new String[5];
arr = new String[]{"村雨遥", "海贼王", "进击的巨人", "鬼灭之刃", "斗罗大陆"};
int index = 0;
for (String name : arr) {
System.out.println("第 " + (index + 1) + " 个元素:" + name);
index++;
}
}
}
面向对象
// 构造方法
public class Main {
public static void main(String[] args) {
Person p = new Person("Xiao Ming", 15);
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
// 构造方法,与类名相同
class Person {
public Person() {
}
}
// 多个构造方法
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this(name, 18); // 调用另一个构造方法Person(String, int)
}
public Person() {
this("Unnamed"); // 调用另一个构造方法Person(String)
}
}
// 方法重载 Overload
class Hello {
public void hello() {
System.out.println("Hello, world!");
}
public void hello(String name) {
System.out.println("Hello, " + name + "!");
}
public void hello(String name, int age) {
if (age < 18) {
System.out.println("Hi, " + name + "!");
} else {
System.out.println("Hello, " + name + "!");
}
}
}
// 继承
class Person {
private String name;
private int age;
public String getName() {...}
public void setName(String name) {...}
public int getAge() {...}
public void setAge(int age) {...}
}
class Student extends Person {
// 不要重复name和age字段/方法,
// 只需要定义新增score字段/方法:
private int score;
public int getScore() { … }
public void setScore(int score) { … }
}
// 重写
class Student extends Person {
@Override
public void run() {
System.out.println("Student.run");
}
}
java核心类
// String
String
// StringBuilder
// 链式操作
public class Main {
public static void main(String[] args) {
var sb = new StringBuilder(1024);
sb.append("Mr ")
.append("Bob")
.append("!")
.insert(0, "Hello, ");
System.out.println(sb.toString());
}
}
// StringJoiner
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
String[] names = {"Bob", "Alice", "Grace"};
var sj = new StringJoiner(", ");
for (String name : names) {
sj.add(name);
}
System.out.println(sj.toString());
}
}
枚举类
public class Weekday {
public static final int SUN = 0;
public static final int MON = 1;
public static final int TUE = 2;
public static final int WED = 3;
public static final int THU = 4;
public static final int FRI = 5;
public static final int SAT = 6;
}
public class Color {
public static final String RED = "r";
public static final String GREEN = "g";
public static final String BLUE = "b";
}
// exception
public class Main {
public static void main(String[] args) {
try {
process1();
} catch (Exception e) {
e.printStackTrace();
}
}
static void process1() {
process2();
}
static void process2() {
Integer.parseInt(null); // 会抛出NumberFormatException
}
}
list使用
// 拼接字符串
List<String> dd = new ArrayList<>();
dd.add(aa);
String msg = String.join("-", dd);
public class EnhanceForTest {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
for (Integer element : list) {
System.out.println(element);
}
}
}
// 迭代器
public class IterTest {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
map 使用
-
HashMap
:无序,允许 null 键和多个 null 值,性能最好。 -
TreeMap
:有序(根据 key 的自然顺序或自定义 Comparator)。 -
LinkedHashMap
:按插入顺序排列。 -
ConcurrentHashMap
:线程安全的高性能并发 Map。
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
map.put("orange", 2);
System.out.println(map); // 输出: {orange=2, banana=5, apple=3}(无序)
}
}
// 获取值
int count = map.get("banana"); // 5
Integer missing = map.getOrDefault("grape", 0); // 如果没有就返回默认值
// 遍历map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// 遍历 key
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
// 遍历 value
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
// 判断key是否存在
map.containsKey("apple"); // true
map.containsValue(5); // true
// 删除元素
map.remove("banana"); // 删除 banana 对应的键值对
set
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // 被忽略
System.out.println(set); // [banana, apple](顺序不保证)
队列
Queue<String> queue = new LinkedList<>();
queue.offer("apple");
queue.offer("banana");
System.out.println(queue.poll()); // apple
System.out.println(queue.poll()); // banana
try-catch
try{
xxxx;
}catch (IOException e) {
throw e;
}
// try-catch 加条件判断
try("aaa"=="aaa"){
xxxx;
}catch (IOException e) {
throw e;
}