Java笔记--常用类

每个人都会有缺陷,就像被上帝咬过的苹果,有的人缺陷比较大,正是因为上帝特别喜欢他的芬芳。

                                                                                                        --托尔斯泰《战争与和平》

一、Object类

1、Object类概念:

Object类是Java中所有类的父类,包括数组

  • Object类是属于java.lang包下的,将来使用的时候不需要导包
  • 构造方法只有一个无参的构造方法
  • 方法都不是静态的,意味着要有对象才可以调用

2、成员方法:

  • public int hashCode()
  • public final Class getClass() 获取类在内存中的Class对象(字节码文件对象),全局唯一
  • public String toString()

            - com.shujia.day10.Demo1@4554617c
            - getClass().getName() + '@' + Integer.toHexString(hashCode())

案例:

package day10;

class Demo1{

}

class Student1{
    private String name;
    private int age;

    public Student1() {
    }

    public Student1(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class ObjectDemo1 {
    public static void main(String[] args) {
        Demo1 demo1 = new Demo1();
        System.out.println(demo1.hashCode());//1163157884理解为地址值的另外一种体现,int类型形式体现
        Demo1 demo2 = new Demo1();
        System.out.println(demo2.hashCode());//1956725890

        Class c1 = demo1.getClass();//调用Object类中的getClass方法获取class文件在内存中的唯一Class对象
        System.out.println(c1.getName());//调用Class类中的getName方法,获取类的名称。

        System.out.println(demo1.toString()); //day10.Demo1@4554617c
        System.out.println(demo2.toString()); //day10.Demo1@74a14482

        //直接输出对象的名字,默认是输出对象调用父类Object中的toString()的结果
        System.out.println(demo1);// day10.Demo1@4554617c

        Student1 s1 = new Student1("张三",20);
        //System.out.println(s1.toString());//day10.Student1@1540e19d

        System.out.println(s1);
    }
}
  • public boolean equals(Object obj)
  • protected void finalize() 是做垃圾回收的,不是立刻就做回收
  • protected Object clone()

 知识点:

        (1)==比较,如果比较的基本数据类型,直接比较具体的数值是否相等,若比较的是引用数据类型,比较的是地址值是否一样

        (2)Object类中的equals方法默认直接使用==比较两个对象,若地址不一样,就是false

案例:

package day10;

class Demo2 extends Object {
    int a;

    @Override
    public String toString() {
        return "Demo2{" +
                "a=" + a +
                '}';
    }

    @Override
    public boolean equals(Object o){
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Demo2 demo2 = (Demo2) o;
        return this.a == demo2.a;
    }
}

public class ObjectDemo2 {
    public static void main(String[] args) {
        //创建第一个Demo2对象
        Demo2 demo1 = new Demo2();
        demo1.a = 100;
        System.out.println(demo1);

        //创建第二个Demo2对象
        Demo2 demo2 = new Demo2();
        demo2.a = 100;
        System.out.println(demo2);

        //Object中的equals方法默认比较的是地址值
        System.out.println(demo1.equals(demo2));//false;类重写equals方法后,比较的就是成员变量值:true
        String s1 = new String("hello");//堆内存中
        String s2 = "hello";
        System.out.println(s1 == s2);//false
        System.out.println(s1.equals(s2));//true 说明String类中重写equals方法,比较的是内容
        System.out.println(s1);
    }
}

Object类中的clone方法

  •     不是任何一个类都可以调用clone方法的,如果此对象的类不实现接口Cloneable ,则抛出CloneNotSupportedException
  •     只有实现了Cloneable接口的类创建出来的对象,才可以调用clone方法
  •     我们观察Cloneable接口文档发现,这个接口源码什么都没有,像这样的接口,称之为标记接口。

    在IT行业中,克隆分两种克隆,克隆有个专业的称呼:拷贝
        深拷贝:拷贝后对象中的引用数据类型也会单独复制一份
        浅拷贝:Object中的clone方法指的是浅拷贝,不会拷贝新的引用成员变量值

案例:

package day10;

class Demo3{
    int a = 10;
}

class Dog implements Cloneable{
    String name;
    int age;
    Demo3 demo3;

    public Dog(){
    }

    public Dog(String name, int age, Demo3 demo3) {
        this.name = name;
        this.age = age;
        this.demo3 = demo3;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", demo3=" + demo3 +
                '}';
    }

    @Override
    public Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}

public class ObjectDemo3 {
    public static void main(String[] args) throws Exception {
        Demo3 demo3 = new Demo3();

        //创建一个狗狗对象
        Dog d = new Dog("史努比",3,demo3);
        System.out.println("d: "+d+", d的地址值是:"+d.hashCode()+"d1中demo3对象的a的值:"+d.demo3.a);
        Object c1 = d.clone();
        Dog c2 = (Dog) c1;
        System.out.println("c1: "+c1+", c1的地址值是:"+c1.hashCode()+"c1中demo3对象的a的值:" + c2.demo3.a);
//        System.out.println(d1==c1); //克隆出来的地址值是不一样的

        c2.demo3.a = 20;
        System.out.println(d.demo3.a);
        System.out.println(c2.demo3.a);

    }
}

插入知识点 

在另一篇文章中(Java笔记--封装)介绍了一个正常类的3.0版本,现在学习了toString函数的重写,可以将3.0版本晋升为4.0版本(目前最终版)

   * 一个标准类的4.0版本:
         *  成员变量:使用private修饰
         *  构造方法:一个无参,一个有参
         *  成员方法:getXxx()和setXxx()以及重写toString()方法

二、Scanner类

1、Scanner类的概述

Scanner:主要用于键盘录入的

构造方法:

Scanner(InputStream source) 构造一个新的 Scanner ,产生从指定输入流扫描的值。

 Scanner:

1、next()和nextLine()区别

2、hasNextXxx()的使用,避免报错

案例:

package day11;

import java.util.Scanner;

public class ScannerDemo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);


        //接收键盘输入的字符串
        String line = sc.next();//不会接收特殊字符,如空格回车这样的符号
        System.out.println(line);

        //接受键盘输入的字符串
        String line1 = sc.nextLine();//能够接收特殊字符,比如空格回车这样的符号
        System.out.println(line1);

        int number = sc.nextInt();//要保证输入的内容能够转成对应的类型,否则报错InputMismatchException
        System.out.println(number);

        sc.reset();
        Scanner sc2 = new Scanner(System.in);
        String line3 = sc2.nextLine();
        System.out.println(line3);

        //hasNextXxx()  判断下一次输入的内容是否符合对应类型
        if(sc.hasNext()){
            int num = sc.nextInt();
            System.out.println("输入的数字为:" + num);
        }else {
            System.out.println("您输入的内容无法转成int类型");
        }

        System.out.println("over");
    }
}

三、String类

String:字符串

解释:

        白话文:使用一个串将一个一个字符串起来的串叫字符串。

        专业术语:使用双引号将若干个字符括起来的字符序列。

官网的概述:

        String类代表字符串。
        Java程序中的所有字符串文字(例如"abc" )都被实现为此类的对象。
        字符串不变; 它们的值在创建后不能被更改。
        字符串缓冲区支持可变字符串。
        因为String对象是不可变的,它们可以被共享。

概述:

        1、字符串可以看成是字符数组。

        2、字符串是由多个字符组成的一串数据(字符序列)。

        3、字符串一旦被创建,就不能被改变。

构造方法:

        public String()
        public String(byte[] bytes)
        public String(byte[] bytes,int offset,int length)
        public String(char[] value)
        public String(char[] value,int offset,int count)
        public String(String original)

 案例:

package day11;
public class StringDemo1 {
    public static void main(String[] args) {
//        String s = "abc";
//        System.out.println(s);
//        s = "qwer";
//        System.out.println(s);

        //public String()
        String s1 = new String();//创建一个没有字符的字符串
        System.out.println("s1: "+s1);//String类中重写的toString()方法

        //public String(btye[] bytes) 将一个字节数组转成一个字符串
        byte[] bytes = {97,98,99,100,101};
        String s2 = new String(bytes);
        System.out.println("s2: "+ s2);

        //public String(byte[] bytes, int index, int length) 将字节数组的一部分转成字符串
        String s3 = new String(bytes,1,3);
        System.out.println("s3: "+ s3);

        // public String(char[] value) 将一个字符数组转成一个字符串
        char[] chars = {'世','界','和','平'};
        String s4 = new String(chars);
        System.out.println("s4: "+ s4);

        // public String(char[] value,int offset,int count)将字符数组的一部分转成字符串
        String s5 = new String(chars,2,2);//长度不能超过
        System.out.println("s5: "+s5);
        
        //public String(String original)  将字符串转字符串
        String s6 = new String("hello");
        System.out.println("s6: " + s6);
        
        String s7 = "hello";
        /*
        * s6和s7是有区别的
        * s7的值就是“hello”在常量池中的地址值。
        * s6是在堆中创建一个对象,在对象中调用“hello”在常量池中的地址值。
        * */
    }
}

 注意事项:

(1) 字符串一旦被创建就不能被修改了,指的是常量池中的字符串值本身不能被修改。

package day11;

/*
    String s = “hello”; s += “world”; 问s的结果是多少?

    字符串一旦被创建就不能被修改了,指的是常量池中的字符串值本身不能被修改。
 */
public class StringDemo2 {
    public static void main(String[] args) {
        String s = "hello";
        s += "world";
        System.out.println("s: " + s);
    }
}

(2) String s = new String(“hello”)和String s = “hello”;的区别?

package day11;

/*
    String s = new String(“hello”)和String s = “hello”;的区别?
 */
public class StringDemo3 {
    public static void main(String[] args) {
        String s = new String("hello"); // 在堆内存中
        String s1 = "hello"; // 在常量池中
        String s2 = "hello"; // 在常量池中

        System.out.println(s==s1);
        System.out.println(s1==s2);
    }
}

 String类中的判断功能

boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
boolean contains(String str)
boolean startsWith(String str)
boolean endsWith(String str)
boolean isEmpty()

案例:

package day11;

// 方法报黄是可能为空,可以不用管

public class StringDemo2 {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HelLO";

        //boolean equals(Object obj)
        boolean b1 = s1.equals(s2);//String类中的equals是重写父类Object中的equals方法,比较的是内容
        System.out.println(b1);

        //boolean equalsIgnoreCase(String str)
        boolean b2 = s1.equalsIgnoreCase(s2);//忽略大小写比较字符串的内容
        System.out.println(b2);

        //boolean contains(String str)//判断大字符串中是否有小字符串
        String s3 = "helljavao worjavald";
        String s4 = "java";
        boolean b3 = s3.contains(s4);
        System.out.println(b3);

        //boolean startsWith(String str) // 判断字符串是否以指定字符串开头
        boolean b4 = s3.startsWith("hell");
        System.out.println(b4);
        boolean b5 = s3.startsWith("123");
        System.out.println(b5);

        //boolean endsWith(String str)//判断字符串是否以指定字符串结尾
        boolean b6 = s3.endsWith("ld");
        System.out.println(b6);

        // boolean isEmpty() 判断字符串是否为空字符串
        boolean b7 = s3.isEmpty();
        System.out.println(b7);
        s3 = "";
        System.out.println(s3.isEmpty());
        //s3=null
//        System.out.println(s3.isEmpty());
    }
}

String类的获取功能

int length()
char charAt(int index)
int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch,int fromIndex)
int indexOf(String str,int fromIndex)
String substring(int start)
String substring(int start,int end)

案例:

package day11;

public class StringDemo3 {
    public static void main(String[] args) {
        String s1 = "hello world!";

        //int length() 获取字符串中的字符个数
        int length = s1.length();
        System.out.println(length);

        //一个字符串可以被看成一个字符数组,索引是从0开始的
        //char charAt(int index)根据索引获取对应的字符
        System.out.println(s1.charAt(6));
        //一般情况下,在Java中和索引有关的操作,若提供不存在的索引,一般都会直接报错
//        System.out.println(s1.charAt(20));//StringIndexOutOfBoundsException

        //int indexOf(int ch)传入字符对应的ascii码值,返回字符从左到右第一次找到的对应的位置索引
        System.out.println(s1.indexOf(119));
//        System.out.println(s1.indexOf(10000));//-1  若找不到就返回-1

        //int indexOf(int ch,int fromIndex)从fromindex索引开始找该字符,若找到了该字符,返回该字符在整个字符串中的位置索引
        String s2 = "hello wojavarld nijavahao java";//查询o的ascii值
        System.out.println(s2.indexOf(111,1));

        //int indexOf(String str,int fromIndex)从fromIndex索引开始找该字符串,若找到了该字符串,返回该字符串的第一个字符在整个大字符串中的位置索引
        String s3 = "hello wojavarld nijavahao java";
        System.out.println(s3.indexOf("java",10));

        //String substring(int start)从指定索引位置开始截取字符串,返回截取后的字符
            String s4 = "今天是疯狂星期四,v我50可好?";
            String s5 = s4.substring(9);
            System.out.println(s5);


        // String substring(int start,int end) 截取从start开始到end结束之间的字符串,返回截取后的字符串 [start, end)
            String s6 = s3.substring(5, 8);
            System.out.println(s5);
    }
}

String类的转换功能

byte[] getBytes()
char[] toCharArray()
static String valueOf(char[] chs)
static String valueOf(int i)
String toLowerCase()
String toUpperCase()
String concat(String str)

案例:

package day11;


/*
String类的转换功能:
        byte[] getBytes()
        char[] toCharArray()
        static String valueOf(char[] chs)
        static String valueOf(int i)
        String toLowerCase()
        String toUpperCase()
        String concat(String str)
*/

import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class StringDemo4 {
    public static void main(String[] args) {
        String s1 = "hello WoRlD";

//        byte[] getBytes()将字符串转成一个字节数组
        byte[] bytes = s1.getBytes();
        for(int i = 0;i <bytes.length;i++){
            System.out.print(bytes[i]+" ");
        }


        System.out.println("=============================");
        //char[] toCharArray()将字符串转成一个字符数组
        char[] chars = s1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]+" ");
        }


        System.out.println("========================");
        //static String valueOf(char[] chs)直接使用String类名的方式进行调用,将字符数组转成字符串
        char[] chars1 = {'我','爱','美','丽','的','中','国'};
        String s2 = String.valueOf(chars1);
        System.out.print(s2);


        System.out.println("===========================");
        //static String valueOf(int i)
        String s3 = String.valueOf(100);//将整数100转成字符串100
        System.out.println(s3);// 100 --> "100"


        //String toLowerCase()//将字符串中的字符字母全部转小写
        String s4 = s1.toLowerCase();
        System.out.println(s4);


        //String toUpperCase()将字符串中的字母全部转大写
        String s5 = s1.toUpperCase();
        System.out.println(s5);


        //String concat(String str)字符串的拼接
        String s6 = "hard work";
        String s7 = " java";
        String s8 = s6.concat(s7);
        System.out.println(s8);
    }
}

String类的其他功能

 替换功能
            String replace(char old,char new)
            String replace(String old,String new)
去除字符串两空格
            String trim()
按字典顺序比较两个字符串
            int compareTo(String str)
            int compareToIgnoreCase(String str) //自己测试

案例:

package day11;

/*
    String类的其他功能:
        替换功能:
        String replace(char old,char new)
        String replace(String old,String new)
        去除字符串两空格
        String trim()
        按字典的顺序去比较两个字符串
        int compareTo(String str)
        int compareToIgnoreCase(String str)//自己测试
 */


public class StringDemo5 {
    public static void main(String[] args) {
        String s1 = "今天的天java气十分的炎热,每java走一步都java在出汗!";

        //String replace(char old,char new)将字符串中所有的旧字符使用新字符进行替换,返回新的字符串

        String res1 = s1.replace('a','_');
        System.out.println("s1: " +s1);
        System.out.println("res1: "+res1);

        System.out.println("----------------------");
        //String replace(String old,String new)将字符串所有的旧字符串使用新字符串进行替换,返回新的字符串
        String res2 = s1.replace("java","hadoop");
        System.out.println("s1: "+s1);
        System.out.println("res2: "+res2);


        System.out.println("----------------------------");
        //String trim()去除字符串两边的空白字符
        String s2 = "  hello world   ";
        String res3 = s2.trim();
        System.out.println("s2: "+s2);
        System.out.println("res3: "+res3);
        String res4 = s2.replace(" ","");
        System.out.println("res4: "+ res4);


        System.out.println("============================");
        //int compareTo(String str)比较两个字符串中的内容是否相同,当结果是0的时候,就说明比较的两个内容相同
        String s3 = "好好学习";
        String s4 = "天天向上";
        System.out.println(s3.compareTo(s4));//

        String s5 = "好好";
        System.out.println(s3.compareTo(s5));//

        String s6 = "天天向上";
        System.out.println(s4.compareTo(s6));


        //int compareToIgnoreCase(String str)//较两个字符串中的内容是否相同,当结果是0的时候,说明比较的两个内容相同
        //忽略对字符串大小的区分
        String s7 = "HELLO";
        String s8 = "hello";
        System.out.println(s7.compareToIgnoreCase(s8));

    }
}

 String类中comparaTo方法的源码

//s3.compareTo(s4)
class String{
    public int compareTo(String anotherString) {
            // value -- s3 -- "hello"
            // anotherString -- s4 -- "hel"
            int len1 = value.length; // 5
            int len2 = anotherString.value.length; // 3
            int lim = Math.min(len1, len2); // 3
            char[] v1 = value; // {'h','e','l','l','o'}
            char[] v2 = anotherString.value; // {'h','e','l'}
            int k = 0;


            while (k < lim) {
                char c1 = v1[k]; // 'h'  'e'  'l'
                char c2 = v2[k]; // 'h'  'e'  'l'
                if (c1 != c2) {
                    return c1 - c2; // 104 - 119 = -15
                }
                k++;
            }
            return len1 - len2; // 5-3=2
        }
}

四、StringBuffer类

StringBuffer:可变字符串,这个容器中只能存放字符

概述:

  • 线程安全,可变的字符序列。
  • 字符串缓冲区就像一个String,但是可以修改。
  • 在任何时间点,它包含一些特定的字符序列,但是可以通过某些方法调用来更改序列的长度和内容

构造方法: 

public StringBuffer()
public StringBuffer(int capacity)
public StringBuffer(String str)

package day11;
/*
    StringBuffer: 可变字符串,这个容器中只能存放字符
    概述:
        线程安全,可变的字符序列。
        字符串缓冲区就像一个String ,但可以修改。
        在任何时间点,它包含一些特定的字符序列,但可以通过某些方法调用来更改序列的长度和内容。

   构造方法:
        public StringBuffer()
        public StringBuffer(int capacity)
        public StringBuffer(String str)
 */


public class StringBufferDemo1 {
    public static void main(String[] args) {
        //public StringBuffer()
        StringBuffer sb1 = new StringBuffer();
        System.out.println("sb1:" + sb1);//StringBuffer类重写toString()方法,返回值是StringBuffer容器中的字符串内容

        //public int capacity()返回当前容量
        System.out.println(sb1.capacity());//16
        //public int length()返回长度(字符数)
        System.out.println(sb1.length());//0


        System.out.println("-------------------------------------");
        //public StringBuffer(int capacity)//自定义初始容量
        StringBuffer sb2 = new StringBuffer(100);
        //public int capacity()返回当前容量
        System.out.println(sb2.capacity()); // 100
        //public int length()返回长度(字符数)。
        System.out.println(sb2.length()); // 0


        System.out.println("----------------------------------------");
        //public StringBuffer(String str)创建一个StringBuffer,放入一个初始字符串
        StringBuffer sb3 = new StringBuffer("hello");
        //public int capacity()返回当前容量
        System.out.println(sb3.capacity());//21 = 16 + 5
        //public int length()返回长度(字符数)
        System.out.println(sb3.length());//5
    }
}

StringBuffer的功能:

添加功能

        public StringBuffer append(String str)

        public StringBuffer append(int offset,String str)

删除功能:

        public StringBuffer deleteCharAt(int index)

        public StringBuffer delete(int start,int end)        

替换功能

        public StringBuffer replace(int start,int end,String str)

反转功能

        public StringBuffer reverse()

package day11;

/*
    StringBuffer的功能:
        添加功能
            public StringBuffer append(String str)
            public StringBuffer insert(int offset,String str)
        删除功能
            public StringBuffer deleteCharAt(int index)
            public StringBuffer delete(int start,int end)
        替换功能
            public StringBuffer replace(int start,int end,String str)
        反转功能
            public StringBuffer reverse()

 */
public class StringBufferDemo2 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        System.out.println("sb: "+sb);


        System.out.println("--------------------");
        //public StringBuffer append(String str)在末尾处添加字符,返回自身
        //任何数据类型值一旦进入到StringBuffer中就是一个一个的普通字符
        sb.append(100);
        sb.append(12.345);
        sb.append(true);
        sb.append(1000L);
        sb.append("hello");
        System.out.println("sb: "+ sb);
        System.out.println("===========================");
        //public StringBuffer insert(int offset,String str)指定位置添加字符串,返回自身
        sb.insert(9,"________");
        System.out.println("sb: "+ sb);
        System.out.println("===========================");
        //10012.345________true1000hello
        //public StringBuffer deleteCharAt(int index) 根据索引删除某一个字符
//        sb.deleteCharAt(14);
//        System.out.println("sb: " + sb);
        System.out.println("-------------------------------------");
        //public StringBuffer delete(int start,int end) [start, end)
//        sb.delete(9,14);
//        System.out.println("sb: " + sb);


        System.out.println("-------------------------------------");
        //public StringBuffer replace(int start,int end,String str)使用一个新的字符串将一段字符串进行替换[start,end)
        sb.replace(9,14,"aaaaaaaa");
        System.out.println("sb: "+sb);
        System.out.println("======================================");
        //public StringBuffer reverse()
        StringBuffer sb2 = new StringBuffer("hello");
        sb2.reverse();
        System.out.println("sb2: "+sb2);
    }
}

 截取功能:

public String substring(int start)
public String substring(int start,int end)

package day11;


/*
    截取功能
        public String substring(int start)
        public String substring(int start,int end)
 */

public class StringBufferDemo3 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("helloworld");
        System.out.println("sb: "+sb);
        System.out.println("=============================");
        String res1 = sb.substring(4);
        System.out.println("sb: "+ sb);
        System.out.println("res1: "+ res1);
        System.out.println("--------------------------");
        //public String substring(int start,int end)截取一部分
        String res2 = sb.substring(4,7);
        System.out.println("sb: "+sb);
        System.out.println("res2: "+res2);
    }
}

 String和StringBuffer的互相转换:

package day11;

public class StringBufferDemo4 {
    public static void main(String[] args) {
        //String --> StringBuffer
        //可以通过构造方法来转换,将String作为参数传递
        String s1 = "hello";
        StringBuffer sb1 = new StringBuffer(s1);
        
        
        //StringBuffer --> String 
        //1、可以使用String类中的构造方法
        //public String(StringBuffer buffer)'
        StringBuffer sb2 = new StringBuffer("world");
        String s2 = new String(sb2);
        
        //2、调用StringBuffer中toString()方法
        String s3 = sb2.toString();
        
        //3、使用截取的方式将字符串取出来
        String s4 = sb2.substring(0);
    }
}

 把数组拼接成一个字符串:

package day11;

public class StringBufferDemo5 {
    public static void main(String[] args) {
        int[] arr = {11,22,33};

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            if (i == 0){
                sb.append("[").append(arr[i]).append(",");
            } else if (i==arr.length-1) {
                sb.append(arr[i]).append("]");
            }else {
                sb.append(arr[i]).append(",");
            }
        }
        
        String res = sb.toString();

        System.out.println(res);
    }
}

把字符串反转:

package day11;

import java.util.Scanner;

public class StringBufferDemo6 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个要反转的字符串:");
        String info = sc.next();
        System.out.println("反转前:" + info);

        // String -> StringBuffer
        StringBuffer sb = new StringBuffer(info);

        //调用StringBuffer中的反转方法
        sb.reverse();

        //StringBuffer->String
        String res = sb.toString();

        System.out.println("反转后:" + res);


        StringBuffer sb2 = new StringBuffer();
        sb2.append(100);

        StringBuilder sb3 = new StringBuilder();
        sb3.append(100);

    }
}

 看程序写结果:

package day11;

/*
    看程序写结果:
        String作为参数传递
        StringBuffer作为参数传递

 */
public class StringBufferDemo7 {
    public static void main(String[] args) {
//        String s1 = "hello";
//        String s2 = "world";
//        System.out.println("s1: " + s1 + ", s2: " + s2); // s1: hello, s2: world
//        fun1(s1, s2);
//        System.out.println("s1: " + s1 + ", s2: " + s2); // s1: hello, s2: world

        //StringBuffer作为参数传递
        StringBuffer sb1 = new StringBuffer("hello");
        StringBuffer sb2 = new StringBuffer("world");
        System.out.println("sb1: "+sb1+", sb2: "+sb2); // sb1: hello, sb2: world
        fun1(sb1,sb2);
        System.out.println("sb1: "+sb1+", sb2: "+sb2); // sb1: hello, sb2: worldworld

    }
    public static void fun1(StringBuffer sb1,StringBuffer sb2){
        sb1 = sb2;
        sb2.append(sb1);
        System.out.println("sb1: "+sb1+", sb2: "+sb2); // sb1: worldworld, sb2: worldworld
    }


    public static void fun1(String s1, String s2) {
        s1 = s2;
        s2 = s1 + s2;
        System.out.println("s1: " + s1 + ", s2: " + s2); // s1: world  s2: worldworld
    }
}

五、StringBuilder类

同四,唯一不同在于StringBuffer类偏向于注重安全,效率较低。

而StringBuilder类不考虑多线程情况,效率较高,但是不太安全。

两种类需要程序员依照项目要求做取舍。

六、Arrays类

概述:

Arrays:是java提供专门针对数据做操作的工具类,该类没有构造方法,且方法都是静态的

  • 针对数组进行操作的工具类。
  • 提供了排序、查找等功能。

成员方法:

public static String toString(int[] a)//将任意一个数组中的所有元素以字符串的形式拼接返回

public static void sort(int[] a)

public static int binarySearch(int[] a,int key)

package day12;
import java.util.Arrays;

public class ArraysDemo1 {
    public static void main(String[] args) {
        int[] arr = {11,22,33,44};
        System.out.println(Arrays.toString(arr));
        String s1 = Arrays.toString(arr);//底层其实就是使用StringBuilder对数组中元素做拼接
        System.out.println(s1);


        int[] arr2 = {32,1,53,16,73,12};
        String[] arr3 = {"apple","banana","grape","lemon","lychee"};
        //也可以对字符串元素数组进行排序,方式是字典顺序
        String[] arr4 = {"廉颇","李白","曹操","刘备","东皇太一","镜","Σ(っ °Д °;)っ"};
        System.out.println("排序前:"+Arrays.toString(arr2));
        Arrays.sort(arr2);
        System.out.println("排序后:"+Arrays.toString(arr2));
        System.out.println("排序前:"+Arrays.toString(arr3));
        Arrays.sort(arr3);
        System.out.println("排序后:"+Arrays.toString(arr3));
        System.out.println("排序前:"+Arrays.toString(arr4));
        Arrays.sort(arr4);
        System.out.println("排序后:"+Arrays.toString(arr4));


        //public static int binarySearch(int[] a,int key)
        //二分法查找元素,如果要保证结果正确的话,被查找的数组必须是有序的
        System.out.println(arr2);
        int index = Arrays.binarySearch(arr2,73);//
        System.out.println(index);
    }
}

七、基本类型包装类

概述:

        为了让基本数据类型的变量像引用数据类型那样可以调用方法,处理对应值,java针对每一种基本数据类型都提供了对应的引用数据类型,这些引用数据类型统称为包装类。

    byte        --      Byte
    short       --      Short
    int         --      Integer
    long        --      Long
    float       --      Float
    double      --      Double
    boolean     --      Boolean
    char        --      Character

    这些包装类的特点基本一致,主要是使用对应的类将基本数据进行进行包装,提供对应的方法来操作对应值。

package day12;
public class IntegerDemo1 {
    public static void main(String[] args) {
        int a = 10;
        String s1 = "abc";

        //创建一个Integer的对象
        //Integer(int value)构造一个新分配的Integer对象,该对象表示指定的int值
        Integer i1 = new Integer(100);

        //Integer(String s)构造一个新分配 Integer对象,表示 int由指示值 String参数。
        Integer i2 = new Integer("200");
        System.out.println("i1: "+i1);
        System.out.println("i2: "+i2);
        
        Integer i3 = 300;//自动装箱
        System.out.println(i3+11);//自动拆箱
    }
}

 Integer的成员方法:

public int intValue()
public static int parseInt(String s)
public static String toString(int i)
public static Integer valueOf(int i)
public static Integer valueOf(String s)

package day12;
/*
Integer的成员方法:
    public int intValue()
    public static int parseInt(String s)
    public static String toString(int i)
    public static Integer valueOf(int i)
    public static Integer valueOf(String s)

 */

public class IntegerDemo2 {
    public static void main(String[] args) {
        Integer i1 = new Integer(100);

        //public static intValue()将包装的基本数据类型值取出来
        int i2 = i1.intValue();
        System.out.println(i2);

        //public static int parseInt(String s)//String -> int
        int i = Integer.parseInt("100");//"100" -> 100
        System.out.println(i);

        //public static String toString(int i)//int -> String
        String s1 = Integer.toString(200);//200->"200"
        System.out.println(s1);

        //public static Integer valueOf(int i)//int ->Integer
        Integer i3 = Integer.valueOf(300);

        //public static Integer valueOf(String s)String -> Integer
        Integer i4 = Integer.valueOf("400");

        //public static String toBinaryString(int i)
        System.out.println(Integer.toBinaryString(100));
        //public static String toOctalString(int i)
        System.out.println(Integer.toOctalString(100));
        //public static String toHexString(int i)
        System.out.println(Integer.toHexString(100));

        Integer x = null;
//        System.out.println(x+10); // 若包装类使用null赋值,将来做自动拆箱的时候,会报空指针异常

    }
}

八、Random类

Random:Java针对随机数功能专门提供了一个类

package day12;

import java.util.Random;

/*
    Random: java针对随机数功能专门提供了一个类


 */
public class RandomDemo1 {
    public static void main(String[] args) {
        Random random = new Random();
        //public int nextInt(int n)
        //between zero (inclusive) and bound (exclusive)
        //[0, 100)
        int i = random.nextInt(100) + 1;
        System.out.println(i);


    }
}

九、System类

 System类:和系统相关操作的类

public static void gc()  垃圾回收的
public static void exit(int status)  强制结束java进程
public static long currentTimeMillis() 获取当前系统的时间戳,毫秒形式

package day12;

/*
    System类:和系统相关操作的类
    public static void gc()  垃圾回收的
    public static void exit(int status)  强制结束java进程
    public static long currentTimeMillis() 获取当前系统的时间戳,毫秒形式


 */
public class SystemDemo1 {
    public static void main(String[] args) {
//        for(int i=0;i<10;i++){
//            if(i==5){
                break;
                continue;
//                System.exit(0); // 结束整个java进程
//            }
//            System.out.println("hello world "+i);
//        }
//
//        System.out.println("我真帅!");

        long time1 = System.currentTimeMillis();
//        System.out.println(time1);


        for (int i = 0; i < 1000000; i++) {
            System.out.println("hello world " + i);
        }

        long time2 = System.currentTimeMillis();
        System.out.println("共耗时:" + ((time2 - time1) / 1000) + "秒");


    }
}

十、日期相关

日期相关的类:Date

构造方法:

public Date()

public Date(long date) 

日期格式化类:

SimpleDateFormat
    构造方法:
        SimpleDateFormat(String pattern) 使用给定模式 SimpleDateFormat并使用默认的 FORMAT语言环境的默认日期格式符号。

package day12;

import java.text.SimpleDateFormat;
import java.util.Date;

/*
    日期相关的类:Date
    构造方法:
        public Date()
        public Date(long date)

    日期格式化类:SimpleDateFormat
    构造方法:
        SimpleDateFormat(String pattern) 使用给定模式 SimpleDateFormat并使用默认的 FORMAT语言环境的默认日期格式符号。


 */
public class DateDemo1 {
    public static void main(String[] args) throws Exception{
        //public Date()
        Date date1 = new Date(); // 获取当前时间的Date类型格式
        System.out.println(date1);


//        Date date2 = new Date(1723171643928L); // 获取指定时间戳的Date类型格式
//        System.out.println(date2);

        // 2024-08-09 10:55:25    "yyyy-MM-dd HH:mm:ss"
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒 a");
        String time1 = sdf.format(date1); // Date -> String
        System.out.println("格式化后的时间:"+time1);


        Date d1 = sdf.parse("2024年08月09日 11时01分15秒 上午"); // String -> Date
        System.out.println(d1);

    }
}

 十一、练习

package day11;

import java.util.Scanner;

public class HomeWork01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = "woai javawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        char[] ch = str.toCharArray();
        int count = 0;
        for (int i = 0; i < str.length()-3; i++) {
            if(ch[i]=='j' && ch[i+1]=='a' && ch[i+2]=='v' && ch[i+3]=='a'){
                    count++;
            }
        }
        System.out.println(count);


        String bigStr = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        String smallStr = "java";

        int num = 0;
        int index = -1;

        do{
            index = bigStr.indexOf(smallStr);
            bigStr = bigStr.substring(index+smallStr.length());
            if(index != -1){
                num++;
            }
        }while(index != -1);
        System.out.println(smallStr + "共出现了:"+ count +"次");



    }
}
  • 20
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值