1. 程式人生 > >04-課堂作業總結歸納

04-課堂作業總結歸納

case http 會有 ras 只讀 目標 images get ont

1請運行以下示例代碼StringPool.java,查看其輸出結果。如何解釋這樣的輸出結果?從中你能總結出什麽?

源代碼:

public class StringPool {

public static void main(String args[])

{

String s0="Hello";

String s1="Hello";

String s2="He"+"llo";

System.out.println(s0==s1);//true

System.out.println(s0==s2);//true

System.out.println(new String("Hello")==new String("Hello"));//false

}

}

第一個so==s1和第二個s0==s2比較的都是字符串的內容(java語言定義“+”運算符可用於兩個字符串的連接操作),所以是true。第三個用new創建了兩個對象,當直接使用new關鍵字創建字符串對象時,雖然值一致(都是“Hello”),但仍然是兩個獨立的對象。

2、

技術分享

為什麽會有上述的輸出結果?從中你又能總結出什麽?

給字串變量賦值意味著:兩個變量(s1s2)現在引用同一個字符串對象“a”!

String對象的內容是只讀的,使用“+”修改s1變量的值,實際上是得到了一個新的字符串對象,其內容為“ab”,它與原先s1所引用的對象”a”無關,所以,s1==s2返回false

代碼中的

ab”字符串是一個常量,它所引用的字符串與s1所引用的“ab”對象無關。

String.equals()方法可以比較兩個字符串的內容。

3、請查看String.equals()方法的實現代碼,註意學習其實現方法。

源代碼:

public class StringEquals {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

String s1=new String("Hello")

String s2=new String("Hello");

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

System.out.println(s1.equals(s2));

String s3="Hello"

String s4="Hello";

System.out.println(s3==s4)

System.out.println(s3.equals(s4));

}

}

技術分享

4String類的方法可以連續調用:

String str="abc";

String result=str.trim().toUpperCase().concat("defg");

請閱讀JDKString類上述方法的源碼,模仿其編程方式,編寫一個MyCounter類,它的方法也支持上述的“級聯”調用特性,其調用示例為:

MyCounter counter1=new MyCounter(1);

MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

public class MyCounter

{public static void main(String[] args)

{ String s="aqz";

String result=s.trim().toUpperCase().concat("qwe");

System.out.println(result);

}

}

5、整理String類的Length()charAt()getChars()replace()toUpperCase()toLowerCase()trim()toCharArray()使用說明

Length():獲取字串長度

charAt():獲取指定位置的字符

getChars():獲取從指定位置起的子串復制到字符數組中

replace():子串替換

toUpperCase() toLowerCase():大小寫轉換

trim():去除頭尾空格

toCharArray():將字符串對象轉換為字符數組

length():public int length()//用來求字符串長度

String s=”dwfs”;

System.out.println(s.length());

charAt():public charAt(int index)//index 是字符下標,返回字符串中指定位置的字符

String s=”Hello”;

System.out.println(s.charAt(3));

getChars():public int getChars()//將字符從此字符串復制到目標字符數組

String s= "abc";

Char[] ch = new char[8];

str.getChars(2,3,ch,0);

replace():public int replace()//替換字符串

String s=”****”;

System.out.println(s.replace(“****”,”***”));

toUpperase():public String toUpperCase()//將字符串全部轉換成大寫

System.out.println(new String(“hello”).toUpperCase());

toLowerCse():public String toLowerCase()//將字符串全部轉換成小寫

System.out.println(new String(“HELLO”).toLowerCase());

trim():public String trim()//是去兩邊空格的方法

String x=” a bc ”;

System.out.println(x.trim());/

toCharArray(): String x=”abcd”;// 將字符串對象中的字符轉換為一個字符數組

char myChar[]=x.toCharArray();

System.out.println(“myChar[1]”+myChar[1]);

04-課堂作業總結歸納