10 Things Every Java Programmer Should Know about String
Strings are not null terminated in Java.
String are Object in Java and backed by character array. You can get the
character array used to represent String in Java by calling toCharArray() method of java.lang.String class of
JDK.
Strings are immutable and final in Java
content of String. If you modify it by using toLowerCase(), toUpperCase() or any
other method, It always result in new
String. Since String is final there is no way anyone can extend String or
override any of String functionality. Now if you are puzzled why
String is immutable or final in Java. checkout the link.
Strings are maintained in String Pool
e.g. "abc" (anything
which is inside double quotes are String literal in Java) are maintained in a
separate String pool, special memory location inside Java memory, more
precisely inside PermGen
Space. Any time you create a new String object using String literal, JVM
first checks String pool and if an object with similar content available, than
it returns that and doesn't create a new object. JVM doesn't perform String
pool check if you create object using new operator.
String name = "Scala"; // 1st String object
String name_1 = "Scala"; // same object referenced by name variable
String name_2 = new String("Scala"); // different String object
String name_3 = new String(name_1); // different String object
String name_4 = String.valueOf(name_1); // same object referenced by
// name variable // this will return true
if (name == name_1)
{
System.out.println("both name and name_1 is pointing to same string object");
} // this will return false
if (name == name_2)
{
System.out.println("both name and name_2 is pointing to same string object");
} // this will return true
if (name_3 == name_1)
{
System.out.println("both name3 and name_1 is pointing to same string object");
} // this will return true
if (name_4 == name)
{
System.out.println("both name4 and name is pointing to same string object");
}
if you compare name and name_1 using equality operator "==" it will return true because both are pointing to same object. While name==name_2 will return false because they are pointing to different string object. It's worth remembering that equality "==" operator compares object memory location and not characters of String. By default Java puts all string literal into string pool, but you can also put any string into pool by calling intern() method of java.lang.String class, like string created using new() operator.
Equals methods for comparing String in Java
which is based on characters, case and order. So if you want to compare two
String object, to check whether they are same or not, always use equals() method
instead of equality operator. Like in earlier example if we use equals
method to compare objects, they will be equal to each other because they
all contains same contents. Here is example of comparing String using equals
method.
You can also check my earlier post difference
between equals() method and == operator for more detail discussion on
consequences of comparing two string using == operator in Java.
indexOf() and lastIndexOf() or matches(String regex) method to search inside
String
convenient method to see if a character or sub-string or a pattern
exists in current String object. You can use indexOf() which will
return position of character or String, if that exist in current String object
or -1 if character doesn't exists in String. lastIndexOf is similar
but it searches from end. String.match(String regex) is even
more powerful, which allows you to search for a regular
expression pattern inside String. here is examples of indexOf, lastIndexOf and matches method
from java.lang.String class.
String str = "Java is best programming language"; if(str.indexOf("Java") != -1){
System.out.println("String contains Java at index :" + str.indexOf("Java"));
} if(str.matches("J.*")){
System.out.println("String Starts with J");
} str ="Do you like Java ME or Java EE"; if(str.lastIndexOf("Java") != -1){
System.out.println("String contains Java lastly at: " + str.lastIndexOf("Java"));
}
As expected indexOf will return 0 because characters
in String are indexed from zero. lastIndexOf returns
index of second “Java”, which starts at 23 and matches
will return true because J.* pattern is any String starting with character
J followed by any character because of dot(.) and any
number of time due to asterick (*).
non-intuitive. If you just put "Java" in matches
it will return false because String is not equals to
"Java" i.e. in case of plain text it behaves like equals method. See here
for more examples of String matches() method.
regex) String also has methods like startsWith() and endsWidth(), which can
be used to check an String if it starting or ending with certain character or
String.
SubString to get part of String in Java
be used to get parts of String. basically you specify start and end index and substring() method
returns character from that range. Index starts from 0 and goes till String.length()-1. By the
way String.length() returns you number of characters in String,
including white spaces like tab, space. One point which is worth remembering
here is that substring is also backed up by character array, which is used by
original String. This can be dangerous if original string object is very large
and substring is very small, because even a small fraction can hold reference
of complete array and prevents it from being garbage collected even if there is
no other reference for that particular String. Read How
Substring works in Java for more details. Here is an example of using SubString
in Java:
String str from index 0 to 12
"+" is overloaded for String concatenation
doesn't support Operator overloading but String is special and + operator
can be used to concatenate two Strings. It can even used to convert int, char, long or double to convert
into String by simply concatenating with empty
string "". internally + is implemented
using StringBuffer prior to Java 5 and StringBuilder from Java
5 onwards. This also brings point of using StringBuffer or StringBuilder for
manipulating String. Since both represent mutable object they can be used to
reduce string garbage created because of temporary String. Read more about StringBuffer
vs StringBuilder here.
trim() to remove white spaces from String
from both end of String. If trim() removes white spaces it
returns a new String otherwise it returns same String. Along with trim() String also provides replace() and replaceAll() method for
replacing characters from String. replaceAll method even
support regular expression. Read more about How to replace String in Java here.
split() for splitting String using Regular expression
take any String in form of regular expression and split the String based on
that. particularly useful if you dealing with comma separated file (CSV) and
wanted to have individual part in a String array. There are other methods also
available related to splitting String, see this Java
tutorial to split string for more details.
store sensitive data in String
passwords, SSN or any other sensitive information. Since String is immutable in
Java there is no way you can erase contents of String and since they are kept
in String pool (in case of String literal) they stay longer on Java heap ,which
exposes risk of being seen by anyone who has access to Java memory, like
reading from memory dump. Instead char[] should be
used to store password or sensitive information. See Why
char[] is more secure than String for storing passwords in Java for more
details.
11) Character Encoding and String
Apart from all these 10 facts about String in Java, the most critical thing to know is what encoding your String is using. It does not make sense to have a String without
knowing what encoding it uses. There is no way to interpret an String
if you don't know the encoding it used. You can not assume that "plain"
text is ASCII. If you have a String, in memory or stored in file, you
must know what encoding it is in, or you cannot display it correctly. By
default Java uses platform encoding i.e. character encoding of your
server, and believe me this can cause huge trouble if you are handling
Unicode data, especially if you are converting byte array to XML String.
I have faced instances where our program fail to interpret Strings from
European language e.g. German, French etc. because our server was not
using Unicode encodings like UTF-8 or UTF-16.
Thankfully, Java allows you to specify default character encoding for
your application using system property file.encoding. See hereto read more about character encoding in Java
Java, sometime even refer has God class. It has some unique feature like immutability, concatenation
support, caching etc, and to become a serious Java programmer,
detailed knowledge of String is quite important. Last but not the least don't
forget about character
encoding while converting a byte array into String in Java. Good knowledge of java.lang.String is must for good Java developers.
10 Things Every Java Programmer Should Know about String的更多相关文章
- Top 10 Methods for Java Arrays
作者:X Wang 出处:http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/ 转载文章,转载请注明作者和出处 The ...
- 10个使用Java最广泛的现实领域
10个使用Java最广泛的现实领域 如果你是一个初学者,刚刚开始学习Java,你可能会想Java有什么用呢?除了Minecraft貌似也看不到其他用Java写的游戏,像Adobe Acrobat和Mi ...
- 在 Ubuntu 13.10 中搭建Java开发环境 - 懒人版
本文记录我在Ubuntu 13.10中搭建Java开发环境. 本文环境: Ubuntu 13.10 x64运行在Win7下的VMware Workstation 10中. 1. 安装JDK与JRE s ...
- Yet Another 10 Common Mistakes Java Developers Make When Writing SQL (You Won’t BELIEVE the Last One)--reference
(Sorry for that click-bait heading. Couldn’t resist ;-) ) We’re on a mission. To teach you SQL. But ...
- macOs升级到10.13.1Beta || JAVA升级到最新版之后PhpStorm菜单栏问题
macOs升级到10.13.1Beta || JAVA升级到最新版之后PhpStorm菜单栏会消失,估计不止出现在PhpStorm,一系列jetbrains的产品可能都会有这个问题,包括eclipis ...
- 20172319 2018.10.19《Java程序设计教程》第7周课堂实践(补写博客)
20172319 2018.10.19 <Java程序设计教程>第7周课堂实践 课程:<程序设计与数据结构> 班级:1723 学生:唐才铭 学号:20172319 指导老师:王 ...
- 20172319 2018.10.12《Java程序设计教程》第6周课堂实践(补写博客)
20172319 2018.10.12 <Java程序设计教程>第6周课堂测验 课程:<程序设计与数据结构> 班级:1723 学生:唐才铭 学号:20172319 指导老师:王 ...
- 10个用Java谋生非常有趣的方式
令我惊讶的是,有些人觉得编程并不令人兴奋——只将它当作是一份枯燥的工作.不过,虽然可能的确有很多无聊的编程工作,但这并不意味着你不得不接受这些工作中的一个.程序员有各种各样的机会,运用他们的技能去做一 ...
- 【翻译】Java Array的排名前十方法(Top 10 Methods for Java Arrays)
这里列举了Java Array 的前十的方法.他们在stackoverflow最大投票的问题. The following are top 10 methods for Java Array. The ...
随机推荐
- 【读书笔记】iOS网络-Cookie
Cookie是HTTP协议在首个版本之后加入的一个重要组件.它向服务器提供了追踪会话状态的能力,同时又无须维持客户端与服务器之间的连接.在浏览器客户端,Cookie值是由服务器通过请求提供的,,然后被 ...
- iOS做新浪微博sso授权登录遇到的一些坑
新浪微博sso授权第三方登录,这里没有借助第三方框架,如shareSKD和友盟等,直接参考新浪官方SDK和文档. 过程中遇到几个坑,找了很久,好歹最后解决了,记录如下 问题1: _NSInlineDa ...
- CEF3可行性
Chromium Embedded Framework 顾名思义,内嵌式CHROME,详细的介绍参阅 http://yogurtcat.com/posts/cef/hello-cef.html 为什么 ...
- iis中限制访问某个文件或某个类型的文件配置方法
Note:此处不是权限设置问题,此处不是权限设置问题,此处不是权限设置问题!只是出于数据或者网络安全,禁止扫描工具直接扫描到某些包含敏感信息的文件,尤其比如日志.配置等 默认ASP.NET已经考虑到了 ...
- The Accidental DBA
The Accidental DBA (Day 1 of 30): Hardware Selection: CPU and Memory Considerations 本文大意: 全篇主要讲 ...
- PowerBI通过gateway连接多维数据库
简介 Microsoft Power BI 是由微软推出的商业智能的专业分析工具,给用户提供简单且丰富的数据可视化及分析功能.个人非常喜欢,有免费版和Pro的付费版,今天主要是介绍下通过gatew ...
- MySQL入门(四)
我好久没有写这个系列了,也确实不知道写什么.回首我学习数据库的路,最开始搞Oracle的时候其实没有搞懂Oracle,也不知道学了什么,后来学习MySQL尤其是InnoDB才大概入了门了.我最开始学习 ...
- 学习myBatis - 如何配置myBatis
这篇文章主要学习如何配置myBatis. 要学习新东西要讲究方法,要从三个层面去理解它:它是什么(what),为什么要学它(why),怎么用它(how).有了学习方法学习的效率才高. 1.myBati ...
- 摆脱npm的网络问题: 淘宝npm镜像
在使用npm install的时候, 经常会因为网络问题, 各种安装不顺利, 一个字'烦躁'. 自从遇上淘宝npm之后,执行cnpm install之后, 怎一个'快'字了得. 闲话不多说, 直接上干 ...
- dpdk在虚拟机上出错处理
目录 1. 所用系统与软件版本 2. 虚拟机配置 3. Ubuntu 12.04上的配置 3.1 准备 3.2 通过setup脚本进行配置 3.3 通过命令配置 4. CentOS 7.0上的配置 4 ...