之前面试的时候被问到有没有看过String类的源码,楼主当时就慌了,回来赶紧补一课。

1.构造器(构造方法)

String类提供了很多不同的构造器,分别对应了不同的字符串初始化方法,此处从源码中摘录如下:

其中蓝色的实心三角表示no modifier(没有修饰符,friendly),表示只能被同一个包中的所有类访问,而不同包中的类不能访问。

这里举了一些示例,来说明这些构造器的用法:

         String string = new String();
System.out.println(string.isEmpty());

         String string = new String("hello world");
System.out.println(string);

         char[] arr = {'A','B', 'C', '1', '2', '3'};
String arrString = new String(arr);
System.out.println(arrString);

         char[] arr = {'A','B', 'C', '1', '2', '3'};
String arrString = new String(arr, 1, 4);
System.out.println(arrString);

         int[] codepoints = {101, 97, 98, 99};
String string = new String(codepoints, 0, 3);
System.out.println(string);

        StringBuffer buffer = new StringBuffer("hello");
2        buffer.append(" world");
3        String string = new String(buffer);
4        System.out.println(string);

         StringBuilder builder = new StringBuilder("hello");
builder.append(" world");
String string = new String(builder);
System.out.println(string);

这里提到构造器,笔者想补充一个问题:构造器真的没有返回值吗?既然没有返回值,那么为什么不能用void关键字来修饰?

解析:其实这只是Java语法上的一个规定。实际上,类的构造器是有返回值的,当我们用new关键字来调用构造器时,会返回一个该类的实例对象,并将这个实例对象在堆内存中的地址赋给了一个该类类型的引用变量。因此,构造器的返回值类型总是当前类,所以就无须定义返回值类型。但必须注意的是,不能在构造器里显式地使用return关键字来返回当前类的对象,因为构造器的返回值是隐式的。

2.成员方法

  • charAt(int index)   返回字符串中下标为index的字符,返回值为char型
         String string = new String("hello world");
System.out.println(string.charAt(0));

  • codePointAt(int index)  返回下标为index的字符的unicode码
  • codePointBefore(int index)  返回下标为index-1的字符的unicode码
  • codePointCount(int beginIndex, int endIndex)   返回下标从beginIndex到endIndex的字符数
         String string = "hello world";
System.out.print(string.charAt(4)+" ");
System.out.println(string.codePointAt(4));
System.out.print(string.charAt(4)+" ");
System.out.println(string.codePointBefore(5));
System.out.println(string.codePointCount(0, 6));

  • equals(Object obj)  比较两个字符串是否相同,返回值为true或者false,此外还有equalsIgnoreCase(String anotherString),即忽略大小写的比较

    注意:1.字符串之间的比较时,比较的是字符串的内容而不是地址,并且只能用于比较String类型,因为StringBuffer和StringBuilder都没有equals()方法;

       2.非字符串之间的比较时,比较的是引用的地址而不是内容,可以用于StringBuffer和StringBuilder类型。

         String string = "hello";
System.out.println(string.equals("hello")); //true String s1 = "hello";
System.out.println(string.equals(s1)); //true String s2 = new String("hello");
String s3 = new String("hello");
System.out.println(s2.equals(s3)); //true /* 注意:StringBuffer和StringBuilder都没有equals()方法
所以调用equals()方法时,比较的是引用变量的地址,所以结果均为false*/
StringBuffer s4 = new StringBuffer("hello");
StringBuilder s5 = new StringBuilder("hello");
StringBuffer s6 = new StringBuffer("hello");
StringBuilder s7 = new StringBuilder("hello");
System.out.println(s1.equals(s4)); //false
System.out.println(s2.equals(s5)); //false
System.out.println(s4.equals(s5)); //false
System.out.println(s4.equals(s6)); //false
System.out.println(s5.equals(s7)); //fals
         String string = "hello";
System.out.println(string.equalsIgnoreCase("Hello")); //true
  • toCharArray()  字符串转换为数组,返回值为一个char类型的数组

    注意:字符数组转换为字符串可以用构造器String(char[]) 实现

         String string = "hello world";
char[] charArr = string.toCharArray();
for(char ch: charArr){
System.out.print(ch+" ");
}

  • 此外,String类还有很多成员方法,这里简单列举一些常用的:

startsWith(String prefix)  endsWith(String suffix)  indexOf(int ch)  indexOf(int ch, int fromIndex)  lastIndexOf(int ch)  lastIndexOf(int ch, int fromIndex)  indexOf(String str)  indexOf(String str, int fromIndex)  substring(int beginIndex)  substring(int beginIndex, int endIndex)  replace(char oldChar, char newChar)  matches(String regex)  contains(CharSequence s)    replaceAll(String regex, String replacement)  split(String regex)  toLowerCase()  toUpperCase()  trim()

String类的源码分析的更多相关文章

  1. JDK中String类的源码分析(二)

    1.startsWith(String prefix, int toffset)方法 包括startsWith(*),endsWith(*)方法,都是调用上述一个方法 public boolean s ...

  2. JDK中String类的源码分析(一)

    1.String类是final的,不允许被继承 /** The value is used for character storage. */ private final char value[]; ...

  3. Spring-MongoDB 关键类的源码分析

    本文分析的是 spring-data-mongodb-1.9.2.RELEASE.jar 和 mongodb-driver-core-3.2.2.jar. 一.UML Class Diagram 核心 ...

  4. Set集合架构和常用实现类的源码分析以及实例应用

    说明:Set的实现类都是基于Map来实现的(HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的). (01) Set 是继承于Collection的接口.它是一个不允许 ...

  5. String,StringBuffer,StringBuilder源码分析

    1.类结构 String Diagrams StringBuffer Diagrams StringBuilder Diagrams 通过以上Diagrams可以看出,String,StringBuf ...

  6. Mybatis Mapper接口是如何找到实现类的-源码分析

    KeyWords: Mybatis 原理,源码,Mybatis Mapper 接口实现类,代理模式,动态代理,Java动态代理,Proxy.newProxyInstance,Mapper 映射,Map ...

  7. java类uuid源码分析

    通用唯一识别码(英语:Universally Unique Identifier,简称UUID)是一种软件建构的标准,亦为自由软件基金会组织在分散式计算环境领域的一部份.UUID的目的,是让分散式系统 ...

  8. 【Cocos2d-x 3.x】 动作类Action源码分析

    游戏设计中,动作是不可缺少的,Cocos2d-x中所有的动作都继承自Action类,而Action类继承自Ref和Clonable类,整个动作类继承体系如图: FiniteTimeAction是所有瞬 ...

  9. String、StringBuffer、StringBuilder源码分析

    利用反编译具体看看"+"的过程 1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 int ...

随机推荐

  1. 【Spring 核心】AOP 面向切面编程

    一.什么是面向切面编程? 二.通过切点来选择连接点 三.使用注解创建切面 四.在XML中声明切面 五.注入AspectJ切面

  2. BotVS开发基础—Python API

    代码 import json def main(): # python API列表 https://www.botvs.com/bbs-topic/443 #状态信息 LogStatus(" ...

  3. Javaweb向服务器上传文件以及从服务器下载文件的方法

    先导入jar包 点击下载 commons-fileupload是Apache开发的一款专门用来处理上传的工具,它的作用就是可以从request对象中解析出,用户发送的请求参数和上传文件的流. comm ...

  4. ID3算法(1)

    1 简述1.1    id3是一种基于决策树的分类算法,由J.Ross Quinlan在1986年开发.id3根据信息增益,运用自顶向下的贪心策略建立决策树.信息增益用于度量某个属性对样本集合分类的好 ...

  5. linux(一)之linux简介

    其实在前几天我使用的是csdn来写博客,尝试了一下,发现真的太浪费时间了.可能是自己不太习惯的原因吧.所以最后还是换回使用博客园.接下来给大家带来的是linux,大家听到这里linux感觉很神秘的样子 ...

  6. 共享Visio和project的下载链接

    好东西就应该共享  下面的是最新版的Visio和project的百度云链接 Visio的链接:http://pan.baidu.com/s/1o8UJq4M 密码:sltu project的链接:ht ...

  7. 最近完成的AndroidStudio项目实现思路及应用技术

    主要内容: Android Studio的介绍 AS中个Gradle及Groovy介绍 AS中的依赖管理 Maven以及Nexus私库管理依赖 Gradle对变种代码的管理以及多渠道打包 eclips ...

  8. 项目管理svn

    https://nchc.dl.sourceforge.net/project/tortoisesvn/1.9.6/Application/TortoiseSVN-1.9.6.27867-x64-sv ...

  9. 在centos6上实现编译安装lamp和wordpress,并编译xcache

    author:JevonWei 版权声明:原创作品 软件环境: centos6.9 httpd-2.4.27.tar.bz2 apr-1.5.2.tar.bz2 apr-util-1.5.4.tar. ...

  10. C语言格式化输入输出

    %i和%d之间的区别 作为匹配整数的转换说明,printf格式串中两者并没有区别,但是在scanf格式串中%d只能匹配十位制整数,而%i可以匹配八进制(前缀为0,如086).十进制或十六进制(前缀0x ...