【Java】三大特殊类之------String类

三大特殊类

  • String类
  • Object类
  • 包装类
    String类:
    final class String
    被final修饰的类不能被继承(为保证所有用户用到的String类都一样,只能使用,不能修改)

1.实例化方式

  • 直接赋值
String str = "hello world";
  • 通过构造方法赋值
String str = new String("hello world");

例子:

public class Test{
    public static void main(String[] args) {
        //直接赋值
        Test test = new Test();
        String str = "hello world";
        //通过构造方法赋值
        String str1 = new String("hello world");
        System.out.println(str);
        System.out.println(str1);
    }
}

2.字符串的相等比较

“==”操作符用于比较两个变量的值是否相等,对于基本类型而言,比较的就是数值的大小;
对于引用类型而言,比较的实际上是保存的地址是否相等而不会比较内容。

所以在字符串内容比较时,需要使用String类提供的equals()方法。(equals对象,区分大小写)

str1.equals(str2);
equalsIngoreCase() //不区分大小写比较

举例:

public class Test{
    public static void main(String[] args) {
        //直接赋值
        Test test = new Test();
        String str = "hello world";
        //通过构造方法产生对象
        String str1 = new String("hello world");
        System.out.println(str);
        System.out.println(str1);
        System.out.println(str.equals(str1));//比较的是内容,不是地址
        System.out.println(str.equalsIgnoreCase(str1));
    }
}

运行结果:
在这里插入图片描述

3.String类的匿名对象

——没有任何栈内存指向的对象(没有名字的对象),所有字符串常量(“ ”)都是String类的匿名对象。
在比较字符串是否等于特定字符串时,将字符串常量写在equals前,通过字符串常量来比较。

"hello world".equals(str);

举例:

public class Test{
    public static void main(String[] args) {
        String str = new St
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值