[零基础学JAVA]Java SE面向对象部分.面向对象基础(02)

String类

 

 JAVA:
public class StringTest{

    public static void main(String args[]){

        //尽量避免使用new,这样会产生内存垃圾

        String name = new String("zsf");
        String welcome= "hello world";
        String hello  = "hello world";
        //对于直接赋值,会将字符串保存在内存池中,不会新开内存
        //new 刚不同。
        //字符串一旦声明,就无法更改,如果出现下面情况,则内存开销相当大

        for (int i = 0;i<100;i++)
            hello += i;

        System.out.println(hello);

        //此hello要不断的断开已有的连接,重新指向新的连接100次,
        //即hello要重新开100次内存,并重连接。

        String str = name ;//通过构造方法完成

        System.out.println(name);
        System.out.println(welcome);
        System.out.println(str);

        if(str.equals(name)){
            System.out.println("true");
        }
        if(str==name){
            System.out.println("true");
        }

        if("zsf".equals(name)){
            System.out.println("true");
        }

    }
}
c++:

 

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;



int main(int argc,char *argv[]){


    string *name = new string("zsf");

    string welcome= "hello world";
    string come= "hello world";

    cout<<*name<<endl;
    //重新分内存,与 java 不同
    cout<<&welcome<<endl;
    cout<<&come<<endl;

    for (int i =0;i<10;i++)
      come+=i;

    //在原来基础上新开内存,若是new出的内存刚不行
    cout<<&come<<endl;
    cout<<come<<endl;

    delete name;

    return 0;
}
 

 

posted on 2013-09-21 16:59  凌峰布衣  阅读(259)  评论(0编辑  收藏  举报

导航