字符串的动手动脑问题

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

}


}

运行结果:

分析:在Java中,内容相同的字符串常量在保存一个以节约内存,所以s0,s1,s2实际上引用的是同一个对象。编译器在编译s2一句时,会去掉“+”号,直接把两个字串连接起来得一个字串,当直接使用new关键字创建字符串对象时,虽然值一致,但是仍然是两个独立的对象

给字符串变量复制意味着两个变量(s1,s2)现在引用同一个字符串对象,String对象的内容是只读的,使用“+”修改s1变量的值,实际上是得到了一个新的字符串对象,其内容为“ab”,他与原先s1所引用的对象无关,所以s1==s2返回false,可以用String.equals方法可以比较两个字符串的内容。

2.请查看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));

}


}

 

String.equals()判等条件:

若当前对象和比较的对象是同一个对象,即return true。也就是Object中的equals方法。

若当前传入的对象是String类型,则比较两个字符串的长度,即value.length的长度。

若长度不相同,则return false。

若长度相同,则按照数组value中的每一位进行比较,不同,则返回false。若每一位都相同,则返回true。

若当前传入的对象不是String类型,则直接返回false。

3. 整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

length():public int length()//求字符串长度

         String s=”dwfsdfwfsadf”;

         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 str = "abcdefghikl";

        Char[] ch = new char[8];

        str.getChars(2,5,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=”ax  c”;

         System.out.println(x.trim());//是去两边空格的方法

toCharArray(): String x=new String(“abcd”);// 将字符串对象中的字符转换为一个字符数组

           char myChar[]=x.toCharArray();

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

 

原文地址:https://www.cnblogs.com/2016excellent-3584/p/7739769.html