菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻

Java 字符串创建/长度

原创
05/13 14:22 更新

Java数据类型教程 - Java字符串创建/长度

创建字符串对象

String类包含许多可用于创建String对象的构造函数。

默认构造函数创建一个以空字符串作为其内容的String对象。

例如,以下语句创建一个空的String对象,并将其引用分配给emptyStr变量:

String  emptyStr = new String();

String类包含一个构造函数,它接受另一个String对象作为参数。

String str1 = new String();
String str2 = new String(str1); // Passing a  String as  an  argument

现在str1代表与str2相同的字符序列。在这一点上,str1和str2都代表一个空字符串。我们也可以传递一个字符串字面量到这个构造函数。

String str3 = new String("");
String str4 = new String("Have fun!");

在执行这两个语句之后,str3将引用一个String对象,它有一个空字符串作为其内容,而str4将引用一个String对象,它有“Have fun!作为其内容。

字符串的长度

String类包含一个length()方法,该方法返回String对象中的字符数。

方法length()的返回类型是int。空字符串的长度为零。

public class Main {
  public static void main(String[] args) {
    String str1 = new String();
    String str2 = new String("Hello");

    // Get the length of str1 and str2 
    int len1 = str1.length();
    int len2 = str2.length();

    // Display the length of str1 and str2
    System.out.println("Length of  \"" + str1 + "\" = " + len1);
    System.out.println("Length of  \"" + str2 + "\" = " + len2);
  }
}

上面的代码生成以下结果。
图片.png

综合评分:9.9 评分 请对本文进行纠错,及学习过程中有困难疑惑可在此进行讨论