Java面向對象----String對象的聲明和創建
阿新 • • 發佈:2018-11-08
bubuko back http 機制 回收 stat 垃圾回收 內存地址 -c
String a="abcd" 相等 String b="abcd"
String a=new String("abcd") 不等於 String b=new String("abcd") 字符串池內存地址不同
對象不可變 常量
"abcd"+"a" 拼接 等於新創建了對象 abcda
面向對象的優點
- 便於程序模擬現實世界中的實體
- 隱藏細節
- 可重用
java對象的內存管理機制
java垃圾回收器:回收堆內存的空間
案例:
package com.tanlei.newer; public class Employee { public String name; public int age; @Override public String toString() { return "我的名字叫"+name+",今年"+age+"歲"; } /* * src 朋友啊朋友,你是我最好的朋友 * dst 朋友 */ //在指定的字符串中查找相應的字符串出現的次數 public int countContent(String src,String dst) { int count=0;//計算器 int index=0;//保存找到朋友的下標 index=src.indexOf(dst); //當首次出現的下標不為-1 while(index!=-1) { count++; index+=dst.length();//指定從哪個下標找 index=src.indexOf(dst,index); } return count; } public static void main(String[] args) { Employee employee=new Employee(); employee.name="張三"; employee.age=30; System.out.println(employee.toString()); String src= "朋友啊朋友,你是我最好的朋友"; String dst= "朋友"; System.out.println(employee.countContent(src, dst)); } }
Java面向對象----String對象的聲明和創建