zoukankan      html  css  js  c++  java
  • Java String使用总结

    1 == 与 equals()

    使用==来比较两个primitive主数据类型在意义上相等(是否带有相同的字节组合),或者判断两个引用(如String变量)是否引用同一个对象。使用equals()来判断两个对象是否在值(内容)上相等。

    int a = 3;
    byte b = 3;
    if (a==b) { //true }

    2 String在使用匿名对象字符串或初始化赋值字符串引用变量时会采用对象池策略,相同内容的字符串,会共用同一段堆内存

    3 String在new实例化方式创建字符串对象时会开辟不同的堆内存存储字符串内容,即便是相同的内容。

    4 字符串的内容不可改变,即便是对一个字符串变量赋予新的内容,但是与此同时也只会开辟新的堆内存空间来存储,并不会改变原来的堆内存空间的内容。而短时间内JVM还来不及回收前面所创造的垃圾内存空间,这可能会造成不好的影响。

    下面的例子是对以上内容的应用:

    StringDemo.java

    package test.string;
    
    public class StringDemo {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		boolean b11 = false;
    		boolean b12 = false;
    		boolean b21 = false;
    		boolean b22 = false;
    		boolean b31 = false;
    		boolean b32 = false;
    		boolean b41 = false;
    		boolean b42 = false;
    		
        if ("hello"=="hello"){
          b11 = true;
        }
        if("hello".equals("hello")){
        	b12 = true;
        }
        System.out.println(b11);//true
        System.out.println(b12);//true
        //===================================
        String str1 = "Hello";
        String str2 = "Hello";
        if(str1 == str2){
        	b21 = true;
        }
        if(str1.equals(str2)){
        	b22 = true;
        }
        System.out.println(b21);//true
        System.out.println(b22);//true
        //==================================
        String str3 = "Hello";
        String str4 = new String("Hello");
        String str5 = new String("Hello");
        if(str3 == str4){
        	b31 = true;
        }
        if(str3.equals(str4)){
        	b32 = true;
        }
        if(str5 == str4){
        	b41 = true;
        }
        if(str5.equals(str4)){
        	b42 = true;
        }
        System.out.println(b31);//false
        System.out.println(b32);//true
        System.out.println(b41);//false
        System.out.println(b42);//true
        //==================================
        String str = "hello ";//generate the first heap memory: hello
        str = str + "world";// generate the second heap memory : hello world
        System.out.println(str);//use the second heap memory, and the first heap memory is waiting to be GC
    	}
    }
    

      

  • 相关阅读:
    django中间件和常用模块
    django之forms组件
    django和ajax、分页器、批量插入数据
    django之模型层ORM操作
    (专题三)02-1 程序和程序设计流程-选择结构
    (专题三)01 程序和程序设计流程-顺序结构
    (专题二)05 矩阵的存储方式
    (专题二)04 矩阵的处理-矩阵的特征值
    [代码片段]YEAH!连通域标记和计数
    TTL和CMOS
  • 原文地址:https://www.cnblogs.com/ioveNature/p/6665000.html
Copyright © 2011-2022 走看看