栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中的String类:构造方法和常用的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中的String类:构造方法和常用的方法

一.构造方法

1.  直接使用字符串初始化。

//"hello"对象存放在方法区的字符串常量池中,s1和s2在栈区中,存放的是"hello"的地址,故两者存放的内
//容相同
String s1="hello";
String s2="hello";

2. new String(字符串)构造方法。

"hello"对象存放在方法区的字符串常量池中;new String()新建对象在堆区,有两次,所以有两个对象在堆区中;s1和s2在栈区。s1和s2分别存储的是堆区中两个对象的地址,堆区中两个String对象存放的是"hello"的地址。

String s1=new String("hello");
String s2=new String("hello");

3. new String(byte数组)

byte[] bytes={97,98,99};
String s1=new String(bytes);
String s2=new String(bytes,0,2);//第二个参数代表起始位置,第三个参数代表终止位置

4. new String(char数组)

char[] ch={'1','2','3','4'};
String s3=new String(ch,1,3);//第二个参数代表起始位置,第三个参数代表终止位置
String s4=new String(ch);
       

二.  常用方法

public class StringTest03 {
    public static void main(String[] args) {
        System.out.println("中国人".charAt(1));
        int a="xyz".compareTo("yxz");
        System.out.println(a);
        System.out.println("helloword".contains("llo"));
        System.out.println("test.txt".endsWith("txt"));
        System.out.println("test.txt".endsWith("java"));
        System.out.println("abc".equals("abc"));
        System.out.println("-----------");
        System.out.println("ABC".equalsIgnoreCase("abc"));
        byte[] by="abcdef".getBytes();
        for (int i = 0; i  

以上这些方法在jdk说明文档中都可以找到,要是有什么不明白的可以去看看。

我上面的写的不全,但是都是经常用的,写文章只是为了做一个自己的学习记录,如果有人有疑问可以私信我或者评论区,我不高冷,都会回复的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/863380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号