java入门基础
概述
- 强类型静态语言
- 编译型语言,运行性能比较高
- 运行时内存安全,拥有一套GC机制
- 后端语言
- 主要web,爬虫等场景
环境安装
$ java -version
openjdk version "17.0.2" 2022-01-18
OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8)
OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode, sharing)
- 配置vscode环境
- 安装language support for java插件然后重启ide
- 配置包管理
$ mv -f apache-maven-3.8.4 /usr/local/
export MAVEN_HOME=/usr/local/apache-maven-3.8.4
export PATH=${PATH}:${MAVEN_HOME}/bin
$ source ~/.bash_profile
$ mvn -v
Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537)
Maven home: /usr/local/apache-maven-3.8.4
Java version: 17.0.2, vendor: Eclipse Adoptium, runtime: /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home
Default locale: zh_CN_
OS name: "mac os x", version: "10.15.7", arch: "x86_64", family: "mac"
$ vim /usr/local/apache-maven-3.8.4/conf/settings.xml
...
<localRepository>~/.m2/repository</localRepository>
...
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
...
创建第一个项目
$ mvn archetype:generate
...
Choose archetype:
1: internal -> org.apache.maven.archetypes:maven-archetype-archetype (An archetype which contains a sample archetype.)
...
6: internal -> org.apache.maven.archetypes:maven-archetype-profiles ()
7: internal -> org.apache.maven.archetypes:maven-archetype-quickstart (An archetype which contains a sample Maven project.)
...
10: internal -> org.apache.maven.archetypes:maven-archetype-webapp (An archetype which contains a sample Maven Webapp project.)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 7:
Define value for property 'groupId': com.xxx
Define value for property 'artifactId': lijc
Define value for property 'version' 1.0-SNAPSHOT: :
Define value for property 'package' com.xxx: :
$ tree
.
├── pom.xml
├── readme.md
└── src
├── main
│ └── java
│ └── com
│ └── xxx
│ └── App.java
└── test
└── java
└── com
└── xxx
└── AppTest.java
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>13</java.version>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
$ mvn clean package
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.xxx.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
$ cd target/classes/ && java com.xxx.App
Hello World!
mvn项目依赖
-
在java中使用maven来管理项目
-
第三方库查询地址
-
添加依赖
<dependency>
<groupId>net.dongliu</groupId>
<artifactId>requests</artifactId>
<version>5.0.8</version>
</dependency>
package com.xxx;
import net.dongliu.requests.Requests;
public class App {
public static void main(String[] args) {
String resp = Requests.get("https://www.baidu.com/").send().readToText();
System.out.println(resp);
}
}
- 添加jar包插件
- 该插件作用将依赖一起打包为jar,一般需要运行的jar包才需要该插件,如果作为库,则不需要
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.xxx.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
变量
type identifier [ = value][, identifier [= value] ...] ;
package com.xxx;
public class Var1 {
public static void test() {
String name = "xiaohong";
int age = 12;
boolean ok = true;
double d = 3.14;
System.out.println(name);
System.out.format("%s %d %f %b\n", name, age, d, ok);
}
}
运算符
package com.xxx;
public class Comput {
public static void test() {
int a = 1;
a++;
System.out.println(a);
a--;
System.out.println(a);
a = a * 2;
System.out.println(a);
a = a / 2;
System.out.println(a);
a += 10;
System.out.println(a);
a = a % 2;
System.out.println(a);
System.out.println(a > 1);
a = 10;
System.out.println(a >> 2);
System.out.println(a > 1 && true);
}
}
布尔类型
package com.xxx;
public class Bool {
public static void test() {
boolean ok = true;
System.out.println(ok);
}
}
数字类型
package com.xxx;
public class Number {
public static void test() {
int a = 12;
System.out.println(a);
}
}
指针或内存地址或引用
package com.xxx;
public class Point {
public static void change(String[] arr) {
arr[0] = "c";
}
public static void test() {
String[] arr = { "a", "b" };
change(arr);
System.out.println(arr[0]);
}
}
字符串类型
package com.xxx;
public class String1 {
public static void test() {
String s = "中国";
System.out.println(s.length());
s += " hello";
s.concat("!!");
System.out.println(s);
int num = 1;
String new_s = String.format("%d %s", num, s);
System.out.println(new_s);
System.out.println(new_s.lastIndexOf("hello1"));
}
}
数组或元组类型
package com.xxx;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class Arr {
public static void test() {
String[] arr = { "abc", "hello","a" };
System.out.println(Arrays.deepToString(arr));
System.out.println(arr[0]);
System.out.println(arr.length);
Arrays.sort(arr);
System.out.println(Arrays.deepToString(arr));
ArrayList<String> arrl = new ArrayList<>();
arrl.add("hello");
arrl.add("world");
System.out.println(arrl.toString());
System.out.println(arrl.size());
System.out.println(arrl.toArray()[0]);
System.out.println(arrl.get(0));
arrl.remove(0);
System.out.println(arrl.toString());
LinkedList<String> arrll = new LinkedList<>();
arrll.add("hello");
arrll.add("world");
System.out.println(arrll.toString());
System.out.println(arrll.size());
System.out.println(arrll.toArray()[0]);
System.out.println(arrll.get(0));
arrll.remove(0);
System.out.println(arrll.toString());
}
}
对象类型
package com.xxx;
interface B {
public String name();
}
abstract class A {
public String name() {
return "A class";
}
}
class C implements B {
private int age;
public String name;
protected int sex;
C(String name) {
this.name = name;
this.sex = 1;
this.age = 20;
}
@Override
public String name() {
return "C class";
}
static void printHello() {
System.out.println("hello");
}
void printName(){
System.out.println(this.name);
}
}
public class Obj {
public static void test() {
C c = new C("china");
c.printName();
System.out.println(c.sex);
System.out.println(c.name());
C.printHello();
}
}
枚举类型
package com.xxx;
enum Color {
red,green,white
}
public class Enum1 {
public static void test() {
System.out.println(Color.red);
}
}
变量作用域
map/集合/向量类型
package com.xxx;
import java.util.HashMap;
import java.util.HashSet;
public class Collection {
public static void test() {
HashMap<String,String> person = new HashMap<>();
person.put("name", "xiaohong");
person.put("age", "123");
System.out.println(person);
System.out.println(person.get("age"));
person.remove("age");
System.out.println(person);
System.out.println(person.size());
person.put("age", "123");
System.out.println(person.keySet());
System.out.println(person.values());
HashSet<Integer> score = new HashSet<>();
score.add(1);
score.add(10);
score.add(4);
System.out.println(score);
score.remove(4);
System.out.println(score);
}
}
继承或多态
package com.xxx;
import java.util.function.Supplier;
interface A1 {
public void eat();
}
interface A2 {
public void read();
}
abstract class All implements A1, A2 {
String name;
All(String name) {
this.name = name;
}
@Override
public void eat() {
System.out.println("eat...");
}
@Override
public void read() {
System.out.println("read...");
}
}
public class Extends extends All {
Extends(String name) {
super(name);
super.eat();
}
public static void test() {
new Extends("xiaohong");
}
}
条件或循环
package com.xxx;
public class IfWhile {
public static void test() {
int a = 10;
if (a == 10) {
System.out.println("等于");
} else if (a < 10) {
System.out.println("小于");
} else {
System.out.println("大于");
}
String[] arr = {"1","2","0"};
for (var each : arr) {
System.out.println(each);
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
while (a < 20) {
a++;
System.out.println(a);
}
}
}
错误处理
package com.xxx;
import java.lang.Exception;
class MyException extends Exception {
}
public class Exception1 {
public static void test() {
try {
int a = 1 / 0;
}
catch (Exception e) {
System.out.println(e);
try {
throw new Exception("新的错误");
} catch (Exception e1) {
System.out.println(e1);
}
}
finally {
System.out.println("ok");
}
}
}
并发机制
package com.xxx;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import net.dongliu.requests.Requests;
class Bussiness {
public void deal(String url) {
String resp = Requests.get(url).send().readToText();
System.out.println(resp);
}
}
class TestThread extends Thread {
private String url;
private String desc;
TestThread(String url,String desc) {
super();
this.url = url;
this.desc = desc;
}
@Override
public void run() {
new Bussiness().deal(this.url);;
System.out.println(this.getName());
System.out.println(this.desc+Thread.currentThread());
}
}
class TestRunable implements Runnable {
private String url;
private String desc;
TestRunable(String url,String desc) {
super();
this.url = url;
this.desc = desc;
}
@Override
public void run() {
new Bussiness().deal(this.url);
;
System.out.println(Thread.currentThread().getName());
System.out.println(this.desc + Thread.currentThread());
}
}
public class Thread1 {
public static void test() {
ArrayList<String> urls = new ArrayList<>();
urls.add("https://www.baidu.com/");
urls.add("https://www.baidu.com/");
urls.add("https://www.baidu.com/");
urls.add("https://www.baidu.com/");
urls.add("https://www.baidu.com/");
urls.add("https://www.baidu.com/");
for (String url : urls) {
new TestThread(url,"继承Thread: ").start();
}
for (String url : urls) {
new Thread(new TestRunable(url,"实现Runnable: ")).start();
}
ExecutorService pool = Executors.newFixedThreadPool(10);
ThreadPoolExecutor executor = (ThreadPoolExecutor) pool;
executor.setCorePoolSize(5);
for (String url : urls) {
executor.execute(new TestRunable(url, "实现线程池: "));
}
System.out.println("ok");
System.out.println(executor.isTerminated());
executor.shutdown();
}
}
特性机制
- 在java中,也可以通过范型来表达抽象的类,以达到通用
package com.xxx;
class TestT<T> {
private T sex;
TestT(T sex) {
this.sex = sex;
}
public void printSex() {
System.out.println(this.sex.getClass() == String.class);
System.out.println(this.sex);
}
}
public class F {
public static void test() {
TestT<String> f1 = new TestT<String>("男");
f1.printSex();
TestT<Integer> f2 = new TestT<Integer>(1);
f2.printSex();
}
}