类String
实现的接口:implents Serializable,Comparable<String>,CharSequence
字符串字面量" "
java中用" "括起来的都是String对象。不可变,保存在方法区的字符串常量池中。(原因是字符串使用太频繁,所以为了执行效率,有了字符串常量池)
下面这2行代码共创建三个字符串对象,都在字符串常量池中。把拼接好的新字符串"abcdefxy"对象的内存地址给了s2.
String s1="abcdef"; //s1保存的字符串对象"abcdef"的内存地址
String s2="abcdef"+"xy";//这一行的"abcdef",直接从字符串常量池中获取,"xy"需要新建
凡是双引号括起来的在字符串常量池中一定有一份。
在上面代码的基础上再加一行,继续分析jvm内存图
String s1="abcdef"; //s1保存的字符串对象"abcdef"的内存地址
String s2="abcdef"+"xy";//这一行的"abcdef",直接从字符串常量池中获取,"xy"需要新建
String s3=new String("xy");//new对象的时候一定在堆内存空间中开辟空间
那么这样呢
User user=new User(110,"张三");
返回boolean值的方法
contains---判断前面的字符串是否包含后面的字符串
System.out.println("HelloWorld.java".contains(".java"));//true
endsWith----判断当前字符串是否以某个字符串结尾
System.out.println("test.txt".endsWith(".txt"));//true
startsWith----判断当前字符串是否以某个字符串开始
System.out.println("http://www.baidu.com".startsWith("http"));//true
isEmpty---判断某个字符串是否为空串,
字符串s要是为null,这时候调用isEmpty就会报空指针异常了
String s=""; System.out.println(s.isEmpty());//true
equals()---比较字符串值是否相等
String str1=new String("a"); String str2=new String("a"); System.out.println(str1.equals(str2)); //true
返回int的方法
int length()---获取字符串的长度
要注意数组长度是length属性,字符串长度是length()方法
System.out.println("abc".length());//3
int indexOf(String str)---子字符串在当前字符串中第一次出现处的索引
System.out.println("oraclejavac++".indexOf("java"));//6
int compareTo()--比较字符串大小
要注意的是拿字符串的第一个字母和后面字符串的第一个字母比较,能分胜负就不再比较了
int result="abc".compareTo("abc");//0 int result2="abcd".compareTo("abce");//-1 前小后大返-1 int result3="abce".compareTo("abcd");//1
返回一个新的字符串
substring(int beginIndex)---一个参数的截取字符串
System.out.println("http://www.baidu.com".substring(7));//www.baidu.com
substring(int beginIndex,int endIndex) ----遵守“包头不包尾”原则。
System.out.println("http://www.baidu.com".substring(7,10));//www
toLowerCase()---转换为小写
System.out.println("ABCDef".toLowerCase());//abcdef
toUpperCase()---转换为大写
System.out.println("ABCDef".toUpperCase());//ABCDEF
replace(char oldChar, char newChar) ---字符替换
System.out.println();
replace(CharSequence target, CharSequence replacement)--CharSequence即字符串序列的意思,说白了也就是字符串
其他
String[ ] split(String regex)----拆分字符串,返回一个字符串数组
String[] ymd="198-10-11".split("-"); for (int i = 0; i < ymd.length; i++) { System.out.println(ymd[i]); }
ValueOf---String中只有这一个方法是静态的,不需要new对象。作用是把非字符串转换为字符串。
String s1=String.valueOf(true)
String s1=String.valueOf(100)
String s1=String.valueOf(3.14)
String s1=String.valueOf(new Customer())//自动调用该对象的toString方法。
//在没有重写toString之前,默认输出的是对象内存地址