03-02 String類、static、Arrays類、Math類

第一章String類


1.1 String類概述


概述

java.lang.String類代表字符串。Java程序中所有的字符串文字(例如"abc")都可以被看作是實現(xiàn)此類的實例。
String中包括用于檢查各個字符串的方法,比如用于比較字符串,搜索字符串,提取子字符串以及創(chuàng)建具有翻 譯為大寫小寫的所有字符的字符串的副本。

特點
  1. 字符串不變:字符串的值在創(chuàng)建后不能被更改。
String s1 = "abc"; 
s1 += "d";
System.out.println(s1); // "abcd"
//內(nèi)存中有"abc", "abed"兩個對象,si從指向"abc",改變指向,指向了"abed"。
  1. 因為String對象是不可變的,所以它們可以被共享。
String s1 = "abc";
String s2 = "abc";
//內(nèi)存中只有—個"abc"對象被創(chuàng)建,同時被s1和s2共享。

3."abc"等效于 char[ ] data={ ' a' , ' b' , ' c' }。

例如:
String str = "abc";

相當(dāng)于:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
// St ring底層是靠字符數(shù)組實現(xiàn)的。

1.2 使用步驟


  • 查看類
    • java.lang.String:此類不需要導(dǎo)入。
  • 查看構(gòu)造方法
    • public String():初始化新創(chuàng)建的String對象,以使其表示空字符序列。
    • public String(char[] value):通過當(dāng)前參數(shù)中的字符數(shù)組來構(gòu)造新的String。
    • public String(byte[] bytes):通過使用平臺的默認(rèn)字符集解碼當(dāng)前參數(shù)中的字節(jié)數(shù)組來構(gòu)造新的 String。
    • 構(gòu)造舉例,代碼如下:
// 無參構(gòu)造
String str = new String();

// 通過字符數(shù)組構(gòu)造
char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);

// 通過字節(jié)數(shù)組構(gòu)造
byte bytes[] = { 97, 98, 99 };
String str3 = new String(bytes);

1.3 常用方法


判斷功能的方法
  • public boolean equals (Object anObject):將此字符串與指定對象進(jìn)行比較。
  • public boolean equalsIgnoreCase (String anotherString):將此字符串與指定對象進(jìn)行比較,忽略大小
    寫。
    方法演示,代碼如下:
public class String_Demo01 {
    public static void main(String[] args) {
        // 創(chuàng)建字符串對象
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "HELLO";

        // boolean equals(Objec t obj):比較字符串的內(nèi)容是否相同         
        System.out.println(s1.equals(s2)); // true 
        System.out.println(s1.equals(s3)); // false
        System. out. println ("----------");

        //boolean equalsIgnoreCase(S tring st r):比較字符串的內(nèi)容是否相同,忽略大小寫 
        System.out.println(s1.equalsIgnoreCase(s2)); // true 
        System.out.println(s1.equalsIgnoreCase(s3)); // true
        System. out. println ("----------");
    }
}

Object 是"對象"的意思,也是一種引用類型。作為參數(shù)類型,表示任意對象都可以傳遞到方法中。

獲取功能的方法
  • public int length ():返回此字符串的長度。
  • public String concat (String str):將指定的字符串連接到該字符串的末尾。
  • public char charAt (int index):返回指定索引處的 char值。
  • public int indexOf (String str):返回指定子字符串第一次出現(xiàn)在該字符串內(nèi)的索引。
  • public String substring (int beginIndex):返回一個子字符串,從beginlndex開始截取字符串到字符 串結(jié)尾。
  • public String substring (in t beginIndex, int endindex):返回一個子字符串,從 beginlndex 到 endlndex截取字符串。含beginlndex,不含endlndex。
    方法演示,代碼如下:
public class String_Demo02 {
    public static void main(String[] args) { 
        //創(chuàng)建字符串對象
        String s = "helloworld";

        // int length():獲取字符串的長度,其實也就是字符個數(shù)     
        System.out.println(s.length());
        System.out.println("----------");

        // String concat (String str):將指定的字符串連接至該字符串的末尾. 
        String s = "helloworld";
        String s2 = s.concat("**hello itheima"); 
        System.out.println(s2);// helloworld**hello itheima

        // char charAt(int index): 獲取指定索引處的字符         
        System.out.println(s.charAt(0));         
        System.out.println(s.charAt(i));
        System.out.println("-----------");

        // int indexOf(S tring st r):獲取s tr在字符串對象中第一次出現(xiàn)的索引,沒有返回-1 
        System.out.println(s.indexOf("l"));
        System.out.println(s.indexOf("owo")); 
        System.out.println(s.indexOf("ak"));
        System.out.println("------------");

        // String subs tring(int st ar t):從start開始截取字符串到字符串結(jié)尾 
        System.out.println(s.substring(0));
        System.out.println(s.substring(5));
        System.out.println("------------");

        // String substring(int start, int end):從 start 到 end 截取字符串。含 start,不含 end。
        System.out.println(s.substring(0, s.length()));
        System.out.println(s.substring(3,8));
    }
}
轉(zhuǎn)換功能的方法
  • public char[] toCharArray ():將此字符串轉(zhuǎn)換為新的字符數(shù)組。
  • public byte[] getBytes ():使用平臺的默認(rèn)字符集將該String編碼轉(zhuǎn)換為新的字節(jié)數(shù)組。
  • public St ring replace (CharSequence targe t, CharSequence replacemen t):將與target 匹配的字符串使
    用replacement字符串替換。
    方法演示,代碼如下:
public class String_Demo03 {
    public static void main(String[] args) { 
        //創(chuàng)建字符串對象
        String s = "abcde";

        // char[] toCharArray():把字符串轉(zhuǎn)換為字符數(shù)組 
        char[] chs = s.toCharArray();
        for(int x = 0; x < chs.length; x++) {
            System.out.println(chs[x]);
        }
        System.out.println("----------");

        // byte[] getBytes (): 把字符串轉(zhuǎn)換為字節(jié)數(shù)組 
        byte[] bytes = s?getBytes();
        for(int x = 0; x < bytes?length; x++) { 
            System.out.println(bytes[x]);
        }
        System.out.println("-------------");

        //替換字母it為大寫IT
        String str = “itcast itheima“;
        String replace = str.replace("it", "IT");
        System.out.println(replace); // ITcast ITheima
        System.out.println("------------");
    }
}

Char Sequence是一個接口,也是一種引用類型。作為參數(shù)類型,可以把String對象傳遞到方法中。

分割功能的方法
  • public String[] split(String regex):將此字符串按照給定的regex (規(guī)則)拆分為字符串?dāng)?shù)組。
    方法演示,代碼如下:
public class String_Demo03 {
    public static void main(String[] args) {
        // 創(chuàng)建字符串對象
        String s = “aa|bb|cc“;
        String[] strArray = s.split(“|“); // [“aa“,“bb“,“cc“]
        for(int x = 0; x < strArray.length; x++) {
            System.out.println(strArray[x]); // aa bb cc
        }
    }
}

1.4 String類的練習(xí)


拼接字符串

定義一個方法,把數(shù)組{1,2,3}按照旨定個格式拼接成一個字符串。格式參照如下:[word1#word2#word3]。

public class StringTest1 {
    public static void main(String[] args) {
        // 定義一個 int 類型的數(shù)組 
        int[] arr = {1, 2, 3};

        // 調(diào)用方法
        String s = arrayToString(arr);

        // 輸出結(jié)果
        System.out.println(“s:“ + s);
    }

    /*
        * 寫方法實現(xiàn)把數(shù)組中的元素按照旨定的格式拼接成一個字符串
        * 兩個明確:
        * 返回值類型:String
        * 參數(shù)列表:int[] arr
    */
    public static String arrayToString(int[] arr) {
        // 創(chuàng)建字符串 s?
        String s = new String("[");
        // 遍歷數(shù)組,并拼接字符串
        for (int x = 0; x < arr.length; x++) {
            if (x == arr?length - 1) {
                s = s.concat(arr[x] + "]");
              } else {
                s = s?concat(arr[x] + "#");
            }
        }
        return s;
    }
}
統(tǒng)計字符個數(shù)

鍵盤錄入一個字符,統(tǒng)計字符串中大小寫字母及數(shù)字字符個數(shù)

public class StringTest2 { 
    public static void main(String[] args) {
        // 鍵盤錄入一個字符串?dāng)?shù)據(jù)
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一 字符串?dāng)?shù)據(jù):"); 
        String s = sc?nextLine();

        // 定義三個統(tǒng)計變量,初始化值都是 0
        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;

        //遍歷字符串,得到每一個字符
        for(int x=0; x<s.length(); x++){ 
            char ch = s.charAt(x);
            //拿字符進(jìn)行判斷
            if(ch>='A'&&ch<='Z') {
                bigCount++;
            }else if(ch>='a'&&ch<='z') { 
                smallCount++;
            }else if(ch>='0'&&ch<='9') {     
                numberCount++;
            }else {
                System.out.println("該字符"+ch+"非法");
            }
        }

        //輸出結(jié)果
        System.out?println("大寫字符:"+bigCount+"個");
        System.out.println("小寫字符:"+smallCount+"個");
        System.out?println("數(shù)字字符:"+numberCount+"個"); }
    } 
}

第二章 static關(guān)鍵字


2.1 概述


關(guān)于static關(guān)鍵字的使用,它可以用來修飾的成員變量和成員方法,被修飾的成員是屬于類的,而不是單單是屬 于某個對象的。也就是說,既然屬于類,就可以不靠創(chuàng)建對象來調(diào)用了。

2.2定義和使用格式


類變量

當(dāng)static修飾成員變量時,該變量稱為類變量。該類的每個對象都共享同一個類變量的值。任何對象都可以更改 該類變量的值,但也可以在不創(chuàng)建該類的對象的情況下對類變量進(jìn)行操作。

  • 類變量:使用static關(guān)鍵字修飾的成員變量。
    定義格式:

static 數(shù)據(jù)類型 變量名;

舉例:

static int numberID;

比如說,基礎(chǔ)班新班開班,學(xué)員報到?,F(xiàn)在想為每一位新來報到的同學(xué)編學(xué)號(Sid),從第一名同學(xué)開始,Sid為1,以此類推。學(xué)號必須是唯一的,連續(xù)的,并且與班級的人數(shù)相符,這樣以便知道,要分配給下一名新同學(xué)的學(xué)號是多少。這樣我們就需要一個變量,與單獨的每一個學(xué)生對象無關(guān),而是與整個班級同學(xué)數(shù)量有關(guān)。
所以,我們可以這樣定義一個靜態(tài)變量numberOfStudent,代碼如下:

public class Student {
    private String name;
    private int age;
    //學(xué)生的id
    private int sid;
    // 類變量,記錄學(xué)生數(shù)量,分配學(xué)號
    public static int numberOfStudent = 0;

    public Student(String name, int age){
        this.name = name;
        this.age = age;
        // 通過 numberOfStudent 給學(xué)生分配學(xué)號
        this.sid = ++numberOfStudent;
    }

    // 打印屬性值 public void show() {     
    System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid );
    }
}
 
public class StuDemo {
    public static void main(String[] args) { 
        Student s1 = new Student(“張三“,23);
        Student s2 = new Student(“李四“,24);
        Student s3 = new Student(“王五“,25); 
        Student s4 = new Student(“趙六“,26);
    }
}

靜態(tài)方法
當(dāng)static修飾成員方法時,該方法稱為類方法。靜態(tài)方法在聲明中有static,建議使用類名來調(diào)用,而不需要創(chuàng)建類的對象。調(diào)用方式非常簡單。

  • 類方法:使用static關(guān)鍵字修飾的成員方法,習(xí)慣稱為靜態(tài)方法。
    定義格式:

修飾符 static 返回值類型 方法名(參數(shù)列表){
// 執(zhí)行語句
}

舉例:在Student類中定義靜態(tài)方法

public static void showNum() {
    System.out.println("num:" + numberOfStudent);
}
  • 靜態(tài)方法調(diào)用的注意事項:
    • 靜態(tài)方法可以直接訪問類變量和靜態(tài)方法。
    • 靜態(tài)方法不能直接訪問普通成員變量或成員方法。反之,成員方法可以直接訪問類變量或靜態(tài)方法。
    • 靜態(tài)方法中,不能使用this關(guān)鍵字。

小貼士:靜態(tài)方法只能訪問靜態(tài)成員。

調(diào)用格式

被static修飾的成員可以并且建議通過類名直接訪問。雖然也可以通過對象名訪問靜態(tài)成員,原因即多個對象均屬于一個類,共享使用同一個靜態(tài)成員,但是不建議,會出現(xiàn)警告信息。
格式:

// 訪問類變量
類名. 類變量名;

// 調(diào)用靜態(tài)方法 類名.靜態(tài)方法名(參數(shù));

調(diào)用演示,代碼如下:

public class StuDemo2 { 
    public static void main(String[] args) {
        // 訪問類變量
        System.out.println(Student.numberOfStudent);
        // 調(diào)用靜態(tài)方法
        Student.showNum();
    }
}

2.3 靜態(tài)原理圖解


static修飾的內(nèi)容:

  • 是隨著類的加載而加載的,且只加載一次。
  • 存儲于一塊固定的內(nèi)存區(qū)域(靜態(tài)區(qū)),所以,可以直接被類名調(diào)用。
  • 它優(yōu)先于對象存在,所以,可以被所有對象共享。

2.4 靜態(tài)代碼塊


  • 靜態(tài)代碼塊:定義在成員位置,使用static修飾的代碼塊{ }。
    • 位置:類中方法外。
    • 執(zhí)行:隨著類的加載而執(zhí)行且執(zhí)行一次,優(yōu)先于main方法和構(gòu)造方法的執(zhí)行。
      格式:
public class ClassName{ 
    static {
        // 執(zhí)行語句
    }
}

作用:給類變量進(jìn)行初始化賦值。用法演示,代碼如下:

public class Game {
    public static int number;
    public static ArrayList<String> list;
    static {
        // 給類變量賦值 number = 2;
        list = new ArrayList<String>();
        // 添加元素到集合中 
        list.add(" 張三 "); 
        list.add(" 李四 ");
    }
}

小貼士:
static 關(guān)鍵字,可以修飾變量、方法和代碼塊。在使用的過程中,其主要目的還是想在不創(chuàng)建對象的情況 下,去調(diào)用方法。下面將介紹兩個工具類,來體現(xiàn)static方法的便利。

第三章Arrays類


3.1 概述


java.util.Arrays此類包含用來操作數(shù)組的各種方法,比如排序和搜索等。其所有方法均為靜態(tài)方法,調(diào)用起來 非常簡單。

3.2 操作數(shù)組的方法


  • public static String toString(in t[] a):返回指定數(shù)組內(nèi)容的字符串表示形式。
public static void main(String[] args) {
    // 定義 int 數(shù)組
    int[] arr = {2,34,35,4,657,8,69,9};
    // 打印數(shù)組 , 輸出地址值
    System.out.println(arr); // [I@2ac1fdc4
    // 數(shù)組內(nèi)容轉(zhuǎn)為字符串
    String s = Arrays.toString(arr);
    // 打印字符串 , 輸出內(nèi)容
    System.out.println(s); // [2, 34, 35, 4, 657, 8, 69, 9]
} 
  • public static void sort (in t[] a):對指定的int型數(shù)組按數(shù)字升序進(jìn)行排序。
public static void main(String[] args) {
    // 定義 int 數(shù)組
    int[] arr ={24, 7, 5, 48, 4, 46, 35, 11, 6, 2};
    System.out.println(“排序前:“+ Arrays.toString(arr)); // 排序前:[24, 7, 5, 48, 4, 46, 35, 11, 6,
2]
    // 升序排序
    Arrays.sort(arr);
    System.out.println("排序后:"+ Arrays.toString(arr));// 排序后:[2, 4, 5, 6, 7, 11, 24, 35, 46,48]
}

3.3 練習(xí)


請使用Arrays相關(guān)的API,將一個隨機(jī)字符串中的所有字符升序排列,并倒序打印。

public class ArraysTest {
    public static void main(String[] args) {
    // 定義隨機(jī)的字符串
    String line = "ysKUreaytWTRHsgFdSAoidq";
    // 轉(zhuǎn)換為字符數(shù)組
    char[] chars = line?toCharArray();

    // 升序排序
    Arrays.sort(chars);
    // 反向遍歷打印
    for (int i = chars ?length-1; i >= 0 ; i--) { 
        System?out?print(chars[i]+“ “); // y y t s s r q o i g e d d a W U T S R K H F A
    }
  }
}

第四章Math類


4.1 概述


java.lang.Math類包含用于執(zhí)行基本數(shù)學(xué)運算的方法,如初等指數(shù)、對數(shù)、平方根和三角函數(shù)。類似這樣的工具類,其所有方法均為靜態(tài)方法,并且不會創(chuàng)建對象,調(diào)用起來非常簡單。

4.2 基本運算的方法


  • public static double abs(double a):返回 double 值的絕對值。

double d1 = Math. abs(-5); //d1 的值為 5
double d2 = Math. abs(5); //d2 的值為 5

  • public static double ceil(double a):返回大于等于參數(shù)的最小的整數(shù)。

double di = Math. ceil(3.3); //di 的值為 4.0
double d2 = Math. ceil(-3.3); //d2 的值為 -3.0
double d3 = Math.ceil(5.1); //d3的值為 6.0

  • public static double floor(double a):返回小于等于參數(shù)最大的整數(shù)。

double di = Math. floor(3.3); //di 的值為3.0
double d2 = Math. floor(-3.3); //d2 的值為-4.0
double d3 = Ma th. floor(5.1); //d3 的值為 5.0

  • public static long round(double a):返回最接近參數(shù)的long。(相當(dāng)于四舍五入方法)

long d1 = Math.round(5.5); //d1的值為6.0
long d2 = Math.round(5.4); //d2的值為5.0

4.3 練習(xí)


請使用Math相關(guān)的API,計算在-10.85.9之間,絕對值大于6或者小于2.1的整數(shù)有多少個?

public class MathTest {
    public static void main(String[] args) {
        // 定義最小值
        double min = -i0.8;
        // 定義最大值
        double max = 5.9;
        // 定義變量計數(shù)
        int count = 0;
        // 范圍內(nèi)循環(huán)
        for (double i = Math.ceil(min); i <= max; i++) {
            // 獲取絕對值并判斷
            if (Math.abs(i) > 6 || Math.abs(i) < 2.i) {
            // 計數(shù)
            count++;
            }
          }
          System.out.println("個數(shù)為:"+ count + "個");
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容