文章目錄
字符串
字符串的特點
- 字符串的內容永不可變。【重點】
- 正是因爲字符串不可改變,所以字符串是可以共享使用的。【節省內存】
- 字符串效果上相當於char[]字符數組,但是底層原理是byte[]字節數組。
字符串的常見3+1種方式
三種構造方法:
public String():創建一個空白字符串,不含有任何內容。
public String(char[] array):根據字符數組的內容,來創建對應的字符串。
public String(byte[] array):根據字節數組的內容,來創建對應的字符串。
一種直接創建:
String str = “Hello”;
【注意】直接寫上雙引號,就是字符串對象。
public class Demo01String {
public static void main(String[] args) {
//使用空參構造
String str1 = new String();
System.out.println("第一個字符串:" + str1);
//根據字符數組創建字符串
char[] chararray = {'a', 'b', 'c'};
String str2 = new String(chararray);
System.out.println("第二個字符串:" + str2);
//根據字節數組來創建字符串
byte[] bytearray = {97, 98, 99, 100};
String str3 = new String(bytearray);
System.out.println("第三個字符串:" + str3);
//直接創建
String str4 = "Hello";
System.out.println("第四個字符串:" + str4);
}
}
字符串的常量池
字符串常量池:程序當中直接寫上的雙引號字符串,就在字符串常量池中
對於基本類型來說,==是進行數值的比較。
對於引用類型來說,==是進行【地址值】的比較。
內存圖
字符串常用方法
字符串之間的比較
==是進行對象的地址比較,如果確實需要字符串的內容比較,可以使用兩個方法:
public boolean equals(Object obj):參數可以是任何對象,只有參數是一個字符串並且內容相同的纔會給true,否則返回false
注意事項:
- 任何對象都能用Object進行接收
- equals方法具有對稱性,也就是a.equals(b)和b.equals(a)效果一頁
- 如果比較雙方一個常量一個變量,推薦把常量字符串寫在前面
public boolean equalsIgnoreCase(String str),忽略大小寫,進行內容比較
public class Demo01StringEquals {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(charArray);
System.out.println(str1.equals(str2)); //true
System.out.println(str2.equals(str3)); //true
System.out.println(str3.equals("Hello")); //true
System.out.println("Hello".equals(str3)); //true 這個更推薦!
String str4 = null;
System.out.println("abc".equals(str4));//false
// System.out.println(str4.equals("abc"));//報錯:空指針異常
String strA = "Java";
String strB = "java";
System.out.println(strA.equals(strB)); //false
System.out.println(strA.equalsIgnoreCase(strB)); //true
}
}
字符串的獲取相關方法
String當中與獲取相關的常用方法有:
public int length():獲取字符串當中含有的字符個數,拿到字符串長度
public String concat(String str):將當前字符串和參數字符串拼接,返回值新的字符串。
public char charAt(int index):獲取制定索引位置的單個字符(索引從0開始)
public int indexOf(String str):查找參數子字符串在本字符當中首次出現的索引位置,如果沒有返回-1
public class Demo02StringGet {
public static void main(String[] args) {
int length = "dasfgjkshgfa".length();
System.out.println("字符串長度:" + length);
//拼接字符串
String str1 = "Hello";
String str2 = "World";
String str3 = str1.concat(str2);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
//獲取指定索引的單個字符
char ch = "Hello".charAt(1);
System.out.println("在1號索引位置的字符:"+ch);
String original = "HelloWorldHelloWorld";
int ind = original.indexOf("llo");
System.out.println(ind);
}
}
字符串的截取方法
有兩種重載形式
public String substring(int index):截取從參數位置一直到字符串末尾,返回新字符串
public String substring(int begin,int end):截取從begin開始,一直到end結束,中間的字符串,包含左邊,不包含右邊
public class Demo03StringCut {
public static void main(String[] args) {
String str1 = "HelloWorld";
String str2 = str1.substring(5);
System.out.println(str2);
String str3 = str1.substring(5,8);
System.out.println(str3);
}
}
字符串的轉換相關方法
public char[] toCharArray():將當前字符串拆分成爲字符數組作爲返回值
public byte[] getBytes():獲取當前字符串底層的字節數組
public String replace(CharSequence oldString, CharSequence newString):
將所有出現的老字符串替換成新字符串,返回替換之後的結果新字符串
public class Demo04StringConvert {
public static void main(String[] args) {
//字符串拆分成字符數組
char[] chars = "Hello".toCharArray();
System.out.println(chars[2]);
//轉換爲字節數組
byte[] bytes = "abc".getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);
}
//字符串的內容替換
String str1 = "How do you do?";
String str2 = str1.replace("o","*");
System.out.println(str1);
System.out.println(str2);
}
}
字符串的分割方法
public String[] split(String regex):按照參數的規則,將字符串切分成若干部分
注意事項:
split方法的參數其實是一個正則表達式
如果按照英文句點.劃分,應該寫成\.
public class Demo05StringSplit {
public static void main(String[] args) {
String str1 = "aaa,bbb,ccc";
String[] array = str1.split(",");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
String str3 = "XXX.YYY.ZZZ";
String[] array3 = str3.split("\\.");//切不出來
for (int i = 0; i < array3.length; i++) {
System.out.println(array3[i]);
}
}
}
static關鍵字——數據共享
如果一個成員變量使用了static關鍵字,那麼這個變量不再屬於對象自己,而是屬於所在的類,多個對象共享同一份數據
舉個例子說明使用用途:
static關鍵字修飾成員
代碼實現:
public class Student {
private int id;
private String name;
private int age;
static String room;
private static int idCounter = 0;//學號計數器,每當new了一個新對象的時候,計數器++
public Student() {
idCounter++; //新建一個對象,就會調用構造方法,計數器+1
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.id = ++idCounter;//新建一個對象,就會調用構造方法,計數器+1
}
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
創建對象並使用
public class Demo01StaticField {
public static void main(String[] args) {
Student one = new Student("郭靖",19);
one.room = "101教室"; //多個對象共享同一個數據
Student two = new Student("黃蓉",16);
System.out.println("姓名:"+one.getName()+" 年齡:"+one.getAge()+" 教室:"+one.room);
System.out.println("姓名:"+two.getName()+" 年齡:"+two.getAge()+" 教室:"+one.room);
}
}
static關鍵字修飾成員方法
一旦使用static修飾成員方法,那麼就成了靜態方法,靜態方法不屬於對象,而是屬於類的
如果沒有static關鍵字,那麼必須首先創建對象,然後通過對象才能使用它
如果有了static關鍵字,那麼不需要創建對象,直接就能通過類名稱來使用它
無論是成員變量,還是成員方法,如果有了static,都推薦用類名稱進行調用
靜態變量:類名稱.靜態變量
靜態方法:類名稱.靜態方法()
【注意事項】
- 靜態不能直接訪問非靜態
原因:因爲在內存當中是【先】有靜態內容,【後】有非靜態內容 - 靜態方法當中不能用this
原因:this代表當前對象,通過誰調用的方法,誰就是當前對象
public class MyClass {
int num; //成員變量
static int numStatic; //靜態變量
// 成員方法
public void method(){
System.out.println("這是一個成員方法");
//成員方法可以訪問成員變量
System.out.println(num);
//成員方法可以訪問靜態變量
System.out.println(numStatic);
}
// 靜態方法
public static void methodStatic(){
System.out.println("這是一個靜態方法");
//靜態方法可以訪問靜態變量
System.out.println(numStatic);
//靜態不能直接訪問非靜態
// System.out.println(num);
// System.out.println(this);//錯誤
}
}
public class Demo02StaticMethod {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.method();
//對於靜態方法來說,可以通過對象名進行調用,也可以通過類名稱來調用
obj.methodStatic();//正確,不推薦,這種寫法在編譯之後也會被javac翻譯成爲“類名稱.靜態方法名”
MyClass.methodStatic();//正確,推薦
// 對於本類當中的靜態方法,可以省略類名稱
myMethod();
Demo02StaticMethod.myMethod();//完全等效
}
public static void myMethod(){
System.out.println("自己的方法");
}
}
靜態static的內存圖
靜態代碼塊
靜態代碼塊的格式:
public class 類名稱{
static{
//靜態代碼塊的內容
}
}
特點:
當第一次用到本類時,靜態代碼塊執行唯一的一次
原因:靜態內容總是優先於非靜態,所以靜態代碼塊比構造方法先執行
靜態代碼塊的典型用途:
用來一次性的對靜態成員變量進行賦值。
public class Person {
static{
System.out.println("靜態代碼塊執行!");
}
public Person(){
System.out.println("靜態方法執行!");
}
}
public class Demo04Static {
public static void main(String[] args) {
Person one = new Person();
Person two = new Person();
}
}
結果
數組工具類Arrays
java.util.Arrays是一個與數組相關的工具類,裏面提供了大量靜態方法,用來實現數組常見的操作
public static String toString(數組):將參數數組變成字符串(按照默認格式:[元素1,元素2,元素3,…])(感覺一般都是爲了便於打印)
public static void sort(數組):按照默認升序(從小到大)對數組的元素進行排序
備註:
- 如果是數值,sort默認按升序從小到大
- 如果是字符串,sort默認按照字母升序
- 如果是自定義的類型,那麼這個自定義的類需要有Comparable或者Comparator接口的支持。
public class Demo01Arrays {
public static void main(String[] args) {
int[] intArray = {10, 20, 30};
String intStr = Arrays.toString(intArray);
System.out.println(intStr);
int[] array1 = {2,4,1,4,2,3};
Arrays.sort(array1);
System.out.println(Arrays.toString(array1));
String[] array2 = {"bbb","aaa","ccc"};
Arrays.sort(array2);
System.out.println(Arrays.toString(array2));
}
}
數學工具類math
java.util.Math類是數學相關的工具類,裏面提供了大量的靜態方法,完成於數學運算相關的操作
public static double abs(double num):獲取絕對值
public static double ceil(double num):向上取整
public static double floor(double num):向下取整
public static long round(double num):四捨五入
Math.PI代表近似圓周率
public class Demo03Math {
public static void main(String[] args) {
System.out.println(Math.abs(-2.3));
System.out.println(Math.round(2.3));
System.out.println(Math.ceil(2.3));
System.out.println(Math.floor(2.3));
System.out.println(Math.PI);
}
}