String 类常见问题比较

来源:互联网 发布:java 等待1秒 编辑:程序博客网 时间:2024/05/21 22:39

程序一

java 代码
  1. package org.danlley.util;   
  2.   
  3. /***********************************************************************  
  4.  * Module:  MyClass.java  
  5.  * Author:  danlley  
  6.  * Modified: 2006年7月31日 11:03:58  
  7.  * Purpose: Defines the class MyClass  
  8.  ***********************************************************************/  
  9.   
  10. public class MyClass{   
  11.     static String s1="I am unique!";   
  12.   
  13.     public static void main(String args[]){   
  14.         String s2="I am unique!";   
  15.         String s3=new String(s1);   
  16.         System.out.println(s1==s2);   
  17.         System.out.println(s1.equals(s2));   
  18.         System.out.println(s3==s1);   
  19.         System.out.println(s3.equals(s1));   
  20.         System.out.println(TestClass.s4==s1);   
  21.     }   
  22. }   
  23.   
  24. class TestClass{   
  25.     static String s4="I am unique!";   
  26. }   



A. line 8 and 10
B. line 10 only
C. line 6 and 8
D. none of these
++++++++++++++++++++++++++++++++++++++
正确答案:D
++++++++++++++++++++++++++++++++++++++

 

 


 

程序二:

java 代码
  1. String s1 = new String("Test");   
  2. String s2 = new String("Test");   
  3. if (s1==s2) System.out.println("Same");   
  4. if (s1.equals(s2)) System.out.println("Equals");  

 


 

A. same equal
B. equals
C. same
D. compile but nothing is displayed upon exception
E. the code fails to compile.
++++++++++++++++++++++++++++++
正确答案:B
++++++++++++++++++++++++++++++


 

分析:

首先要明白 String 类是一个最终类,无法进行继承和派生。还有一个概念就是字面量。字面量是 String 类的特殊变量。其特点是一旦在使用中申明了其值,就意味着该字面量的地址已经确定,而且我们将无法改变储存在该地址中的数据。而且,对于字面量值相同的数据均是同一个地址中的数据(这样就保证了字面量不会重复定义),我们可以将一个字面量的地址引用传给任意多个String 对象。但是,我们无法通过改变其中某些 String 对象的值来改变源字面量所在地址中存放的数据。打个比方:

1>String a="My First String Object ! ";
2>String b="My First String Object ! ";

以上两行代码中,Java虚拟机会在字面量 "My First String Object ! " 第一次声明(如1>所示)时为其分配一个确定的内存空间。而以后再需要使用时,可以采用(2>)的方式。

但是,是不是所有的字面量都是引用传递(值传递)呢,不尽然。看看下面的两行代码。

String str=new String ("My First String Object ! ");
String str_ot="My First String Object ! ";

比较这两行代码,第二种是将对象包含值的地址共享出来。任何对象都可以对其进行引用。而第一种方式则是,为String对象重新定义了一个内存空间,然后将字面量 "My First String Object ! "作为实参存入新分配的内存地址中。这时 str 与 str_ot 尽管值是相同的,但是拥有不同的内存地址空间。

接下来就是 equals 与 == 的区别了,equals仅仅比较的是变量值是否相同,而 == 必须保证值的地址也完全相同。

0 0
原创粉丝点击