Java学习笔记(一)——关于java中的String类

【前面的话】

      毕业将近6个月了,试用期也快要过去了,期待接下来的日子。在金融类性质的机构,最痛苦的是也许就是大部分系统外包,所以比较少写代码,在这六个月中只写了1个月左右的代码,然后每天都在做一些比较杂的事情,希望有机会可以写一写代码,提高技术。

      前段时间做了一下开发,最近马上也要过年了,时间相对就比较多了,所以又回过头来看看书,巩固一下基础知识,做一些笔记,看看自己的思维,主要目的是为了自己积累,所以都是很基础、很基础的知识,请自行选择如果看到这里要走了,祝新年快乐,也不枉进来一趟。

【知识汇总】

  •  String类的定义:String在java中是一个比较特殊的类,因为其自己可以做一种数据类型直接定义变量,如下:
  1. String str = "hello";
  2. String str = new String ("hello");
  • String两种不同定义地理解:
  1. String str = "hello"; //可以把str理解为一个char*,str指向数据段中的字符串"hello"。
  2. String str = new String ("hello");//是new了一个对象,堆空间分配了一块内存,把对象放在里面,str 指向这个对象
  • 上面两者的区别:
  1. String str 1= "hello";
  2. String str 2= "hello";

     //当定义str2的时候,系统会先检测数据段里是否已经有了“hello”,如果有了那么str2直接指向这个“hello”,这是系统的优化。也就是说不会单独再在数据段中存储“hello”,str1和str2指向的是同一个数据段,也就是str1和str2代表的数据段地址也是一样的。

     //改正哈,下面1楼指出了这里有误哈:可以参见1楼。

  1. String str 3= new String ("hello");
  2. String str 4= new String ("hello");

     //str4是重新new的一个对象,是在堆空间又单独存储的,也就是说str3和str4的地址是不一样的,但是存储内容是一样的。读者可以运行一下下面的代码:

        代码:

String s1="hello";
String s2="hello";
System.out.println(s1==s2);
String s3=new String("hello");
String s4=new String("hello");
System.out.println(s3==s4);
System.out.println(s3.equals(s4));

      运行结果:

true
false
true
  • 对于String类对象是不可变字符的理解:
  1. String str1="hello";
  2. str1=str1.substring(0, 3)+” p!”;

      //首先substring(0, 3)表示提取字符串第一个到第三个的字母。

      //对于不可变的理解就是说,存储“hello”的地方永远存储的是“hello”,除非系统自动收回,是永远不会变的。对于str1提取子串,只是让str1再次指向“hello”的引用,对于这个引用再进行改变,而原来存储“hello”的地方是不变的。读者可以运行一下下面的代码:

    代码:

String str1="hello";
String str2=str1;
str1=str1.substring(0, 3)+"p!";
System.out.println(str1);
System.out.println(str2);

    运行结果:

help!
hello

   //因为第2行代码是让str1和str2指向了同一个地址段,后面改变了str1的指向,而str2指向的东西是没有改变的。

java代码】

public class Text {
    public static void main(String[] args){        
//说明了s1和s2指向的同一个地址段,s3和s4指向的是不同的地址段,而存储内容是一样的
        String s1="hello";
        String s2="hello";
        System.out.println(s1==s2);
        String s3=new String("hello");
        String s4=new String("hello");
        System.out.println(s3==s4);
        System.out.println(s3.equals(s4));
//说明了str1和str2指向同一个地址段,而后面改变的str1只是对"hello"的一个引用的改变
        String str1="hello";
        String str2=str1;
        str1=str1.substring(0, 3)+"p!";
        System.out.println(str1);
        System.out.println(str2);
    }
}

【运行结果】

true
false
true
help!
hello

【后面的话】

     将看到的、学到的东西写出来的感觉还是非常好的,一方面可以锻炼自己的思维能力,另一方面可以更加好的理解所学。

     这几天看到了几句话分享一下:

  1. 你养兰花不是今天用来生气的。
  2. 昨日黄土陇头送白骨,今宵红灯帐底卧鸳鸯。
  3. 我认为这些真理是不言自明了,人人生来平等,造物主赋予他们一定的不可让与的权利,这些权利有生活的权利、自由的权利和追求幸福的权利。为了取得这些权利,人类创建了政府,政府则从被治理的同意中得到权利。任何政府形式一但有背这些目的,人民就有权改变或废除它,组织新的政府······                                                                                                         

——《独立宣言》

                                                                                                                                ——TT

原文地址:https://www.cnblogs.com/xt0810/p/3530840.html