目录
2.18 String、StringBuilder、StringBuffer
一、基础
1.1 驼峰原则
即第二个首字母大写
1.2 变量
- long 8个字节
- double 8个字节
- int 4个字节
1.3 常量
用final修饰常量称为符号常量,通常为大写,在这个层面上相当于c++ const
1.4 基本数据类型
- 整型
byte是一个字节,8位二进制数,理论范围是
,但要表示正负,最高位是符号位,所以是
- 浮点型
浮点型是不精确的
如果要精确使用java.math下的BigDecimal
public class Test {
public static void main(String[] args) {
BigDecimal value = BigDecimal.valueOf(1.0);
//减去0.1
value = value.subtract(BigDecimal.valueOf(0.1));
value = value.subtract(BigDecimal.valueOf(0.1));
value = value.subtract(BigDecimal.valueOf(0.1));
System.out.println(value);
System.out.println(1.0-0.1-0.1-0.1);
//0.7
//0.7000000000000001
}
}
1.5 强制类型转换
1.6 获得键盘输入
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
//获得输入的一行内容
String str = scanner.nextLine();
System.out.println(str);
}
}
1.7 内存分析
- 栈为线程私有
- 堆为线程共享
- 方法区又称静态区,来存放固定不变的东西,属于堆的一部分
1.8 垃圾回收机制
1.9 static
- 静态变量和静态方法不能用this调用
- 静态函数不能使用非静态变量,因为static修饰的数据会放在方法区。
1.10 静态初始化块
- 类初始化的时候就执行静态块里面的内容
public class Test {
public static void main(String[] args) {
Person p=new Person();
//我是人
}
}
class Person{
String name;
static {
System.out.println("我是人");
}
}
二、面型对象
2.1 Instance
- 判断一个类是否属于另一个类
public class Test {
public static void main(String[] args) {
Cat cat = new Cat();
System.out.println(cat instanceof Animal);
System.out.println(cat instanceof Object);
//true
//true
}
}
class Animal{
}
class Cat extends Animal{
}
2.2 重写
- 若返回值的类型是Person,它的子类是Student,父类是Object,则子类重写时,返回类型可以是Person、Student但不能是Object。
- 若访问权限是public,则则子类重写时,访问权限只能是public,而不能是protected或private
2.3 equals
public class Test {
public static void main(String[] args) {
Animal a1 = new Animal("猫");
Animal a2 = new Animal("猫");
System.out.println(a1 == a2);
System.out.println(a1.equals(a2));
//false
//true
}
}
class Animal{
int age;
String name;
Animal(String name){
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Animal animal = (Animal) o;
return name.equals(animal.name);
}
}
2.4 super()
- 使用父类的成员变量和成员方法
- 子类初始化时会默认调用父类的构造方法(无参构造),即使不加super(),编译器也会默认加上
public class Test {
public static void main(String[] args) {
Student student = new Student();
//我是人
//我是学生
//18
}
}
class Person{
public int age;
public Person(){
System.out.println("我是人");
age = 18;
}
}
class Student extends Person{
public Student(){
super();
System.out.println("我是学生");
System.out.println(super.age);
}
}
2.5 多态
public class Test {
public static void main(String[] args) {
test(new Person());
test(new Student());
test(new Teacher());
//我是Person
//我是Student
//我是Teacher
}
static void test(Person p){
p.myName();
}
}
class Person{
public void myName(){
System.out.println("我是Person");
}
}
class Student extends Person{
public void myName(){
System.out.println("我是Student");
}
}
class Teacher extends Person{
public void myName(){
System.out.println("我是Teacher");
}
}
2.6 转型
public class Test {
public static void main(String[] args) {
Person s = new Student(); //此时s被当作Person,只能调用myName() 自动向上转型
s.myName();
//s.myAge(); 错误
((Student) s).myAge(); //强制向下转型
//我是Student
//永远18岁
}
}
class Person{
public void myName(){
System.out.println("我是Person");
}
}
class Student extends Person{
public void myName(){
System.out.println("我是Student");
}
public void myAge(){
System.out.println("永远18岁");
}
}
2.7 final修饰的方法和类
2.8 abstract
public class Test {
public static void main(String[] args) {
}
static void test(Person p){
p.myName();
}
}
abstract class Person{
abstract public void myName();
public void myAge(){
}
}
class Student extends Person{
@Override
public void myName() {
System.out.println("我是Student");
}
}
2.9 接口
public class Test {
public static void main(String[] args) {
Person person = new Student();
person.myName();
((Student)person).myAge();
//小明
//18
}
}
interface Person{
void myName();
}
//接口只能存放固定不变的东西
interface Human{
int age=18; //默认为public static final修饰
void myAge(); //默认为public abstract
}
//接口可以多实现
class Student implements Person,Human{
@Override
public void myName() {
System.out.println("小明");
}
@Override
public void myAge() {
System.out.println(age);
}
}
2.10 非静态内部类
public class Test {
public static void main(String[] args) {
//创建内部类
Person.Student student = new Person().new Student();
student.show();
//18
}
}
//内部类生来就是为外部类服务的
class Person{
private int age=18;
class Student{
public void show(){
System.out.println(Person.this.age);
}
}
}
2.11 静态内部类
public class Test {
public static void main(String[] args) {
//创建内部类
Person.Student student = new Person.Student();
}
}
class Person{
static class Student{
}
}
2.12 匿名内部类
- 特点:只使用一次
public class Test {
public static void main(String[] args) {
test(new Person() {
@Override
public void myName() {
System.out.println("小明");
}
});
//小明
}
public static void test(Person person){
person.myName();
}
}
interface Person{
void myName();
}
2.13 String常用api
public class Test {
public static void main(String[] args) {
String s1 = "Core Java";
String s2 = "core java";
//忽略大小写比较
System.out.println(s1.equalsIgnoreCase(s2));
//true
//返回第一个相比配的元素的下表,如果没有返回-1
System.out.println(s1.indexOf("Java"));
System.out.println(s1.replace('a','A'));
//Core JAvA
//[0,2)
System.out.println(s1.substring(0,2));
//Co
System.out.println(s1.charAt(0));
//C
}
}
2.14 arraycopy
public class Test {
public static void main(String[] args) {
String[] s1={"aa","bb","cc","dd","ee"};
String[] s2= new String[10];
//要拷贝的数组 起始下标 要拷贝到的数组 起始下标 长度
System.arraycopy(s1,1,s2,0,3);
}
}
2.15 Arrays
public class Test {
public static void main(String[] args) {
int[] s={1,5,4,3,2};
System.out.println(Arrays.toString(s));
//[aa, bb, cc, dd, ee]
Arrays.sort(s);
System.out.println(Arrays.toString(s));
//[1, 5, 4, 3, 2]
//[1, 2, 3, 4, 5]
}
}
2.16 包装类
public class Test {
public static void main(String[] args) {
Integer a = new Integer(2);
//字符串转int
Integer b = new Integer("2");
Integer e = Integer.parseInt("123");
//int转double
double d = b.doubleValue();
//int转String
String s = a.toString();
}
}
2.17 自动装箱、自动拆箱
public class Test {
public static void main(String[] args) {
//自动装箱
Integer i = 1; //编译器会编译成 Integer i = Integer.valueOf(1);
//自动拆箱
int j = i; ///编译器会编译成 int j = i.intValue();
}
}
2.18 String、StringBuilder、StringBuffer
- String源码中 final char[ ] ch 字符串不可变
- StringBuilder源码中 char[ ] ch 字符串可变
- StringBuilder效率高但线程不安全
- StringBuffer效率低但线程安全
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("123");
System.out.println(sb.hashCode());
//856419764
sb.setCharAt(0,'2');
System.out.println(sb.hashCode());
//856419764
}
}
2.19 枚举
- 默认public static final修饰
public class Test {
public static void main(String[] args) {
Week w = Week.周一;
System.out.println(w);
//周一
}
enum Week{
周一,周二,周三
}
}
三、异常
3.1 异常分类
3.2 自定义异常
public class Test {
public static void main(String[] args) {
int age = -10;
if(age<0){
throw new IllegalAgeException("年龄小于0");
}
//Exception in thread "main" Test.IllegalAgeException: 年龄小于0
}
}
class IllegalAgeException extends RuntimeException{
public IllegalAgeException(){
}
public IllegalAgeException(String msg){
super(msg);
}
}
四、容器
4.1 容器基本分类
4.2 ArrayList(手写)
public class MyArrayList <E>{
private static final int DEFAULT_SIZE = 10;
private Object [] ElementData;
private int size;
public MyArrayList(){
ElementData = new Object[DEFAULT_SIZE];
}
//添加元素
public void add(E obj){
//扩容
if(size == ElementData.length){
Object[] newArray = new Object[ElementData.length+ElementData.length/2];
System.arraycopy(ElementData,0,newArray,0,ElementData.length);
ElementData = newArray;
}
ElementData[size++] = obj;
}
//打印类时会调用
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
for(int i=0;i<size;i++){
builder.append(ElementData[i]);
builder.append(",");
}
builder.setCharAt(builder.length()-1,']');
return builder.toString();
}
//获取元素
public E get(int index){
checkRange(index);
return (E)ElementData[index];
}
//替换元素
public void set(int index,E element){
checkRange(index);
ElementData[index] = element;
}
//检查索引合法性
public void checkRange(int index){
if(index<0||index<=ElementData.length){
throw new RuntimeException("索引不合法"+index);
}
}
}
public class Test {
public static void main(String[] args) {
MyArrayList<String> list = new MyArrayList<String>();
list.add("aa");
list.add("bb");
list.add("bb");
System.out.println(list);
//[aa,bb,cc]
System.out.println(list.get(0));
//aa
list.set(0,"dd");
System.out.println(list);
//[dd,bb,bb]
}
}
Vector是ArrayList的线程安全的实现
4.3 Map
4.4 迭代器
public class Test {
public static void main(String[] args){
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
for(Iterator<String> iterator=list.iterator();iterator.hasNext();){
String temp = iterator.next();
System.out.println(temp);
//a
//b
//c
}
Map<Integer,String> map = new HashMap<>();
map.put(1,"a");
map.put(2,"b");
map.put(3,"c");
Set<Map.Entry<Integer, String>> set = map.entrySet();
for(Iterator<Map.Entry<Integer, String>> iterator = set.iterator(); iterator.hasNext();){
Map.Entry<Integer,String> temp = iterator.next();
System.out.println(temp.getKey()+"-"+temp.getValue());
//1-a
//2-b
//3-c
}
}
}
4.5 collections工具类
public class Test {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0;i<5;i++){
list.add(i);
}
//反转
Collections.reverse(list);
System.out.println(list);
//[4, 3, 2, 1, 0]
//排序
Collections.sort(list);
System.out.println(list);
//[0, 1, 2, 3, 4]
//打乱顺序(随机)
Collections.shuffle(list);
System.out.println(list);
//[3, 4, 0, 1, 2]
//二分查找
System.out.println(Collections.binarySearch(list,3));
//3
}
}
五、IO
5.1 File
public class Test {
public static void main(String[] args) {
File file = null;
String path = "D:/桌面/test.txt";
String path1="D:/桌面";
file = new File(path);
file = new File("D:/桌面","test.txt");
file = new File(new File(path1),"test.txt");
}
}
public class Test {
public static void main(String[] args) throws IOException {
File file = null;
String path = "D:/桌面/test.txt";
String path1 = "D:/桌面/testtt.txt";
file = new File(path);
System.out.println(file.getName());
//test.txt
System.out.println(file.getPath());
//D:\桌面\test.txt
System.out.println(file.getAbsolutePath());
//D:\桌面\test.txt
System.out.println(file.getParent());
//D:\桌面
System.out.println(file.isFile());
//true
System.out.println(file.exists());
//true
System.out.println(file.isDirectory());
//false
System.out.println(file.length());
//1207
//只有当次路径的文件不存在时才会创建
file = new File(path1);
file.createNewFile();
file.delete();
}
}
5.2 InputStream
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
try {
InputStream is = new FileInputStream(file);int len = 0;
while ((len = is.read())!=-1){
System.out.print((char)len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
InputStream is = null;
byte[] buffer = new byte[1024];
try {
is = new FileInputStream(file);int len = 0;
while ((len = is.read(buffer))!=-1){
//如果不指定可能会乱码
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.3 OutputStream
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test01.txt");
OutputStream os = null;
try {
os = new FileOutputStream(file);
String msg = "我是人!";
os.write(msg.getBytes(),0,msg.getBytes().length);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(os !=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.4 Reader
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
Reader reader = null;
try {
reader = new FileReader(file);
char[] buffer = new char[1024];
int len = 0;
while ((len = reader.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5.5 Writer
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test01.txt");
Writer writer = null;
try {
writer = new FileWriter(file);
String msg = "我是人!";
writer.write(msg);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(writer !=null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.6 字节数组流
以上四个都是通过操作系统实现的,因此需要关闭,而字节数组流是Java虚拟机实现的,直接读取到内存中去,由垃圾回收器释放。
- 区别:源头不同,InputStream,OutputStream,Reader,Writer的源头是文件
- ByteArrayInputStream和ByteArrayOutputStrem的源头是内存,所以读取的数据不要太大
public class Test {
public static void main(String[] args){
ByteArrayInputStream inputStream = null;
byte[] msg = "我是人!".getBytes();
byte[] buffer = new byte[5];
try{
inputStream = new ByteArrayInputStream(msg);
int len = 0;
while ((len=inputStream.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args){
ByteArrayOutputStream outputStream = null;
//因为输出到内存,由虚拟机管理
outputStream = new ByteArrayOutputStream();
byte[] buffer = "我是人".getBytes();
outputStream.write(buffer,0,buffer.length);
System.out.println(outputStream.toString());
}
}
5.7 字节缓冲流
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int len = 0;
while ((len=bis.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5.8 字符缓冲流
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
char[] buffer = new char[1024];
int len = 0;
while ((len = reader.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5.9 转换流
将字节流转换成字符流
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
InputStream in = null;
try {
in = new FileInputStream(file);
//转换流
InputStreamReader reader = new InputStreamReader(in,"utf-8");
char[] buffer = new char[1024];
int len=0;
while ((len=reader.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.10 数据流
传输基本数据类型
public class Test {
public static void main(String[] args){
ByteArrayOutputStream by = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(by);
try {
dos.writeDouble(3.14);
dos.writeBoolean(true);
dos.flush();
DataInputStream in = new DataInputStream(new ByteArrayInputStream(by.toByteArray()));
//必须按写入顺序读出
double v = in.readDouble();
boolean b = in.readBoolean();
System.out.println(v);
System.out.println(b);
//3.14
//true
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.11 对象流
传输对象
public class Test {
public static void main(String[] args){
ByteArrayOutputStream by = new ByteArrayOutputStream();
ObjectOutputStream dos = null;
try {
dos = new ObjectOutputStream(by);
dos.writeDouble(3.14);
dos.writeBoolean(true);
dos.writeObject("对象");
dos.flush();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(by.toByteArray()));
//必须按写入顺序读出
double v = in.readDouble();
boolean b = in.readBoolean();
Object object = in.readObject();
System.out.println(v);
System.out.println(b);
System.out.println(object);
//3.14
//true
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
5.12 打印流
public class Test {
public static void main(String[] args){
File file = new File("D:/桌面/test.txt");
PrintStream ps = System.out;
ps.println("123");
//123
try {
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
ps.println("123");
ps.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
5.13 commons-io的使用
public class Test {
public static void main(String[] args){
try {
//读取文件内容
String msg = FileUtils.readFileToString(new File("D:/桌面/test.txt"),"utf-8");
System.out.println(msg);
//读取一行
List<String> list = new ArrayList<>();
list = FileUtils.readLines(new File("D:/桌面/test.txt"),"utf-8");
System.out.println(list.get(0));
//关雎
//写出到文件 字符集后加true表示追加文件
FileUtils.write(new File("D:/桌面/test.txt"),"我是人","utf-8");
FileUtils.writeByteArrayToFile(new File("D:/桌面/test.txt"),"我是人".getBytes("utf-8"));
List<String> li = new ArrayList<>();
li.add("s1");
li.add("s2");
li.add("s3");
FileUtils.writeLines(new File("D:/桌面/test.txt"),li,"-");
//s1-s2-s3-
} catch (IOException e) {
e.printStackTrace();
}
}
六、网络编程
6.1 Udp
传输方
public class Test {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8881);
String msg = "我爱你";
byte[] buffer = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,new InetSocketAddress("localhost",8882));
socket.send(packet);
socket.close();
}
}
接收方
public class Test01 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8882);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String str = new String(data,0,data.length);
System.out.println(str);
System.out.println("传输结束");
socket.close();
}
}
6.2 Tcp
服务器
public class Test {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8881);
Socket socket = server.accept();
OutputStream outputStream = socket.getOutputStream();
String msg = "我爱你";
byte[] data = msg.getBytes();
outputStream.write(data,0,data.length);
server.close();
}
}
客户端
public class Test01 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost",8881);
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
System.out.println("成功接收");
while ((len = inputStream.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
}
}
七、虚拟机
7.1 类加载机制
基本过程
加载->链接->初始化