Java 中 String 的构造方法
String 对于所有 Java 程序员来说都不会陌生,几乎每天甚至每个程序都会和 String 打交道,因此将 String 的常用知识汇集在此,方便查阅。
概叙:
Java 中是如此定义 String 的:
public final class String extends Object implements Serializable, Comparable<String>, CharSequence
String 是 final 类型的,继续看下面的解释:
The String class represents character strings.
All string literals in Java programs, such as "abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created.
String 对象代表了字符的串或序列,Java 中所有字面量的字符串都是 String 的对象;
String 是常量,它的值一旦被创建就不能改变了。
String buffers support mutable strings. Because String objects are immutable they can be shared.
接下来说字符缓冲区支持可变的字符串,因为缓冲区里面的字符串对象们可以被共享(其实就是使对象的引用发生了改变)。
在 Java 中,提供了通过字符串连接符( + )号,将其他类型的对象转换成 String 类型:
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
int i = 123;String str2 = i + "abc";
/**
* 上面一句生成的 class 文件如下:
* String str2 = (new StringBuilder(String.valueOf(i))).append("abc").toString();
* String 对 “+” 的支持使用了 StringBuilder 以及它的 append 和 toString 方法。
*/
表面看似简单,其实运算复杂,不如直接用 String.valueOf 来的快:
int i = 1; String strNew = String.valueOf(1) + "abc";
构造方法:
1)无参构造方法
String()
Initializes a newly created String object so that it represents an empty character sequence.
该构造方法会创建空的字符序列,注意这个构造方法的使用,因为创造不必要的字符串对象是不可变的。因此不建议采取下面的创建 String 对象:
String str = new String() str = "sample";
这样的结果可想而知,产生了不必要的对象。
2)参数为字符串类型
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
源 String 的值不会影响目标 String 的值,但是用到比较少,或许结合 subString 方法使用:
String original = "1234567890"; String str = new String(original.subString(2, 5));
这样写是有必要的,当 original 是个大字符串时,这种截取方法可以使得新的字符串对象指向新的对象,而不是原来的 original,减少内存占用。
3)参数为 byte 数组类型
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
byte 是网络传输或存储的序列化形式,所以在很多传输和存储的过程中需要将 byte[] 数组和 String 进行相互转化。
有关 IO 流的代码中会出现这个构造方法,字符编码导致的乱码问题也是比较多的,这里需要注意:一旦看到 byte 数组,一定要想到编码问题。
经常会用到 getBytes(Charset charset) 方法:
try {
byte[] byteArr = strNew.getBytes("UTF-8");
String newString = new String(byteArr, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
4)参数为 char 数组类型
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
这里值得注意的是:当我们使用字符数组创建 String 的时候,会用到 Arrays.copyOf 方法或 Arrays.copyOfRange 方法。这两个方法是将原有的字符数组中的内容逐一的复制到 String 中的字符数组中。会创建一个新的字符串对象,随后修改的字符数组不影响新创建的字符串。
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
5)参数为 StringBuilder 或者 StringBuffer 类型
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
个人认为这种方式的构造方法用的比较少吧,如果是这两种类型的,用 toString 方法的更方便一些。
StringBuilder sbb = new StringBuilder();
sbb.append("hello ").append("world");
String str1 = sbb.toString();
特别感谢以下博文:
Java 中 String 的构造方法的更多相关文章
- java中String是对象还是类?详解java中的String
有很多人搞不懂对象和类的定义.比如说java中String到底是对象还是类呢? 有人说String 既可以说是类,也可以说是对象. 其实他这么说也没问题, 类和对象其实都是一个抽象的概念. 我们可以把 ...
- Java中String和byte[]间的转换浅析
Java语言中字符串类型和字节数组类型相互之间的转换经常发生,网上的分析及代码也比较多,本文将分析总结常规的byte[]和String间的转换以及十六进制String和byte[]间相互转换的原理及实 ...
- Java中String和byte[]间的 转换浅析
Java语言中字符串类型和字节数组类型相互之间的转换经常发生,网上的分析及代码也比较多,本文将分析总结常规的byte[]和String间的转换以及十六进制String和byte[]间相互转换的原理及实 ...
- Java中String和byte[]间的 转换
数据库的字段中使用了blob类型时,在entity中此字段可以对应为byte[] 类型,保存到数据库中时需要把传入的参数转为byte[]类型,读取的时候再通过将byte[]类型转换为String类型. ...
- java中string内存的相关知识点
(一):区别java内存中堆和栈: 1.栈:数据可以共享,存放基本数据类型和对象的引用,其中对象存放在堆中,对象的引用存放在栈中: 当在一段代码块定义一个变量时,就在栈中 为这个变量分配内存空间,当该 ...
- java中String的相等比较
首先贴出测试用例: package test; import org.junit.Test; /** * Created by Administrator on 2015/9/16. * */ pub ...
- java中String、StringBuffer、StringBuilder的区别
java中String.StringBuffer.StringBuilder是编程中经常使用的字符串类,他们之间的区别也是经常在面试中会问到的问题.现在总结一下,看看他们的不同与相同. 1.可变与不可 ...
- Java中String类的方法及说明
String : 字符串类型 一. String sc_sub = new String(c,3,2); // String sb_copy = new String(sb) ...
- java中String类型变量的赋值问题
第一节 String类型的方法参数 运行下面这段代码,其结果是什么? package com.test; public class Example { String str = new String( ...
随机推荐
- Git Note - git tag
git tag is used to create labels, usually for version numbers. Format: git tag <TagName> <r ...
- 窗口间传送数据wsprintf,WM_SETTEXT,SendMessage的理解
对wsprintf API函数的理解: int wsprintf ( LPTSTR lpOut, // pointer to buffer for output LPCTSTR lpFmt, // ...
- jQuery-关于Ajax请求async属性的说明及总结
在jquery的ajax中如果希望实现同步或者异步,我们可以设置async(默认true,表示异步请求),下面举例说明两种请求方式的区别. 1.后台代码 public JsonResult GetDa ...
- indows 2008 r2/做了SPS2007---2013后,发现添加原来域中的域组添加不上
根据上次的网络包的分析, 我们在AD中找到了wtc-beijing-it的组, 不过在SharePoint日志中我们没有发现搜索成功的记录. - SearchResultEntry: CN=WTC-B ...
- (转)最全正则表达式总结:验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等
什么是 RegExp? RegExp 是正则表达式(Regular expression)的缩写,作用是对字符串执行模式匹配. 通常用于格式验证.正则替换.查找子串等 各种编程语言的正则表达式基本相同 ...
- 未能加载文件或程序集“ICSharpCode.SharpZipLib, Version=0.86.0.518, Culture=neutral, PublicKeyToken=1b03e6acf116
最近项目新增需求批量通过Excel导入数据,果断想到NPOI,结果导入的时候突然跳出 未能加载文件或程序集“ICSharpCode.SharpZipLib, Version=0.86.0.518, C ...
- Python 错误和异常小结
1.Python异常类 Python是面向对象语言,所以程序抛出的异常也是类.常见的Python异常有以下几个,大家只要大致扫一眼,有个映像,等到编程的时候,相信大家肯定会不只一次跟他们照面(除非你不 ...
- “全栈2019”22篇Java异常学习资料及总结
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"22篇Ja ...
- forword和重定向有什么区别?
一.forword 1.请求只能从同一个web中转发,当前应用之外的找不到. 2.地址栏不变. 3.共享request对象,请求链不断. 4.永久性跳转,最常用. 5.客户端方法功能跳转 二.重定向 ...
- django入门-模型-part2
尊重作者的劳动,转载请注明作者及原文地址 http://www.cnblogs.com/txwsqk/p/6511177.html 完全翻译自官方文档 https://docs.djangoproje ...