reference:http://examples.javacodegeeks.com/core-java/lang/string/java-string-class-example/
1. Introduction
In this example we are going to discuss about the basic characteristics of Java String Class. String
is probably one of the most used types in Java programs. That’s why Java provides a number of API methods that make String
manipulation easy and efficient, straight out of the box. Strings
are so important that even in the latest Java releases (including 7 and 8), several changes have been made to its class methods and its internal representation, improving it even further in terms of performance and security.
2. String Class basic methods
A String
is simply a sequence of characters. As a matter of fact, a String
Object is backed by a char
array. Consequently, it is not null terminated, like in C/C++.
Here is how you can create a String
1 |
String str= "Hello World" ; |
"Hello World"
is called a String
literal. In a Java program, everything between two double quotes is a String
literal. Literals are implemented as instances of String class. As you can see, you can conveniently initialize a String
Object like a primitive type, e.g int i = 0;
.
There is no need to do:
1 |
String str = new String( "Hello World" ); |
There is a difference between these two initialization methods, although the result is the same : A String
with value “Hello World”. But more on that in just a bit.
For now, here is a simple main
with the most important String
API methods:
StringClassExample.java
001 |
package com.javacodegeeks.core.lang.string; |
003 |
public class StringClassExample { |
005 |
public static void main(String[]args){ |
006 |
//Initialization with literal |
007 |
String str1 = "Hello World" ; |
008 |
System.out.println( "str1:" +str1); |
010 |
//Initialization with char array |
011 |
char arr[] = { 'H' , 'e' , 'l' , 'l' , 'o' }; |
012 |
String str2 = new String(arr); |
013 |
System.out.println( "str2:" +str2); |
015 |
//Concatenation using + operator |
016 |
String str3 = "World" ; |
017 |
str3 = str2 + " " + str3; |
018 |
System.out.println( "str3:" +str3); |
020 |
//find out the length of a string |
021 |
System.out.println(str3.length()); |
023 |
//You can even apply that to literals, as with all String API methods |
024 |
//As we said. literals are implemented as String instances |
025 |
System.out.println( "Length: " + "abcdefg" .length()); |
027 |
//Substring from position 2 to position 10 |
028 |
String c = str1.substring( 2 , 10 ); |
029 |
System.out.println( "Substring :" +c); |
031 |
//Substring from position 1 to position 4 |
032 |
System.out.println( "Literal Substring :" + "abcdefghigklm" .substring( 1 , 4 )); |
034 |
// Get the charcter array of the string. |
035 |
char [] chars = c.toCharArray(); |
036 |
System.out.println( "Char array : [" +chars[ 0 ]+ "," +chars[ 1 ]+ "," +chars[ 2 ]+ "]" ); |
038 |
//find the first index of a char inside a string |
039 |
int i = str1.indexOf( 'W' ); |
040 |
System.out.println( "Index of 'W':" +i); |
042 |
//find the first index of a string inside another string after a certain position |
043 |
i = str1.indexOf( "orld" , 5 ); |
044 |
System.out.println( "Index of 'orld':" +i); |
046 |
//find the last index of a string inside another string |
047 |
i = str1.lastIndexOf( "l" ); |
048 |
System.out.println( "LAST Index of 'l':" +i); |
050 |
//find the last index of a string inside another string after a certain position |
051 |
// - like scanning the string backwards |
052 |
i = str1.lastIndexOf( "l" , 7 ); |
053 |
System.out.println( "LAST Index of 'l':" +i); |
055 |
//find a character in a certain position |
056 |
char cr = str1.charAt( 5 ); |
057 |
System.out.println( "Character at position 5:" +cr); |
060 |
System.out.println( "ABCEFAFA" .toLowerCase()); |
063 |
System.out.println( "abcasipasc" .toUpperCase()); |
065 |
//replace occurrences of a character |
066 |
str1 = str1.replace( 'o' , '0' ); |
067 |
System.out.println(str1); |
069 |
//Trim white spaces from the end and the beginning |
070 |
String str4 = " Java" ; |
071 |
System.out.println(str4); |
072 |
System.out.println(str4.trim()); |
075 |
String str5= "Java is great" ; |
076 |
String[] strArray = str5.split( " " ); |
078 |
System.out.println(strArray[ 0 ]+ "," +strArray[ 1 ]+ "," +strArray[ 2 ]); |
080 |
str5= "Java-is-great" ; |
081 |
strArray = str5.split( "-" ); |
082 |
System.out.println(strArray[ 0 ]+ "," +strArray[ 1 ]+ "," +strArray[ 2 ]); |
084 |
str5= "Java is great" ; |
085 |
strArray = str5.split( "/*" ); |
086 |
System.out.println(strArray[ 0 ]+ "," +strArray[ 1 ]+ "," +strArray[ 2 ]+ "," +strArray[ 3 ]+ "," +strArray[ 4 ]+ |
087 |
"," +strArray[ 5 ]+ "," +strArray[ 6 ]+ "," +strArray[ 7 ]+ "," +strArray[ 8 ]); |
089 |
//contains and equals |
090 |
System.out.println( "Contains :" + "qwerty" .contains( "ert" )); |
091 |
System.out.println ( "Equals :" +str5.equals( "java is great" )); |
092 |
System.out.println ( "Equals ignore case:" +str5.equalsIgnoreCase( "java is great" )); |
094 |
// Compare lexicographically two strings |
095 |
System.out.println ( "Compare:" +str5.compareTo( "abc" )); |
097 |
//comparison attempts |
099 |
String s3 = new String( "abc" ); |
101 |
System.out.println(s1==s3); |
102 |
System.out.println(s1.equalsIgnoreCase(s3)); |
This is the output of the above program:
str1:Hello World
str2:Hello
str3:Hello World
11
Length: 7
Substring :llo Worl
Literal Substring :bcd
Char array : [l,l,o]
Index of 'W':6
Index of 'orld':7
LAST Index of 'l':9
LAST Index of 'l':3
Character at position 5:
abcefafa
ABCASIPASC
Hell0 W0rld
Java
Java
Java,is,great
Java,is,great
,J,a,v,a, ,i,s,
Contains :true
Equals :false
Equals ignore case:true
Compare:-23
false
true
From the above program is clear that Java designers decided to treat Strings somewhat differently from other Objects. For example you can initialize them like a primitive, e.g String a="abc"
and you can concatenate two strings using +
operator, like you would add twoints
(looks like overloading + operator in C++).
The comparison attempts
section of the code might seem a little fuzzy, but it will get clear in the next section. What you should take away from it now, is that you SHOULD NEVER try to compare the contents of Strings using ==
operator. You are only comparing reference equality, not content equality. You MUST use equals
or equalsIgnoreCase
.
3. Other characteristics of String objects
String
objects are immutable. This means that once a String
is created, its contents cannot be changed. In the above example, every time we attempt to change its contents, e.g when concatenating, a new String
object is created representing the result. Additionally, String class is final, so you cannot override its behavior.
Immutability was mostly chosen for security reasons and for performance. It also means that two different thread can share the same String and manipulate it as they want, not having to synchronize anything, because every time they make a change in the original string, a new one is created, while the old one remains untouched.
Now let’s see this :
4 |
String s3 = new String( "abc" ); |
6 |
System.out.println(s1==s2); |
7 |
System.out.println(s1==s3); |
This outputs:
true
false
Literals are stored in a special place in memory, called a String pool
, of course in the form of String
Objects. In that pool, a String
object with value “abc” is only created and stored once. Any other String
that gets the value “abc” (statically – hard coded) will reference the same String
object. So, every time you create a String
using a literal, the system will search that pool and checks if the value of the literal exists in an object of the pool. If it does, it sends back the reference to that matching object, if not it creates a new Object and stores it in the pool. So, String
references, initialized with the same literals, will point to the same String
object. This technique was used to save precious memory, as it shares as much common data as possible.
Now, you can also see another reason why Strings are immutable. Imagine thread A creating a local string “abc” and then a second thread B creating his own local string “abc”. These two threads will share the same String object… If String was mutable, then if A changed the string, the change would affect thread B, but in a meaningless (put catastrophic) way.
When creating a String
using new
, you explicitly create a brand new object in the heap. This is also the case for non hard codedString
initialization, for example, if you are reading input Strings
from a source. These String
Objects will not be stored in the pool. Imagine that you create an application that has to hold addresses for users living in Greece. There are four million people living in Athens, so consider the massive waste of space should you store four million String objects with value “Athens”. In order to pool those non hard coded Strings
, there is an API method called intern
, and can be used like so:
04 |
String s3 = new String( "abc" ); |
06 |
System.out.println(s1==s2); |
07 |
System.out.println(s1==s3); |
10 |
System.out.println(s1==s3); |
This will now output:
true
false
true
When calling intern, the system follows the same procedure as if we did s3 = "abc"
, but without using literals.
But be careful. Before Java 7, this pool was located in a special place in the Java Heap, called PermGen. PermGen is of fixed size, and can only hold a limited amount of string literals. So, interning should be used with ease. From Java 7 onward, the pool will be stored in the normal heap, like any other object (making them eligible for garbage collection), in a form of a hashmap and you can adjust its size using -XX:StringTableSize
option. You could create your own String pool for that matter, but don’t bother.
This is only one of the aspects that Java creators changed in the String class. Even more radical changes ware made, including the internal String representation (it now has two less static fields).
Download the Eclipse Project
This was an example of Java String Class. You can download the Eclipse Project of this example here : StringClassExample.zip
- 自己挖坑自己跳 之JsonMappingException: (was java.lang.NullPointerException) (through reference chain:)
在Web项目中,我们经常会设计一些与界面相对应的JavaBean作为Entity,而为了兼容前台传入的空值,有些字段我们会用包装类型而不是基本类型.可是往往我的Entity已经设计完成,很多时候我们会 ...
- 通过反编译深入理解Java String及intern(转)
通过反编译深入理解Java String及intern 原文传送门:http://www.cnblogs.com/paddix/p/5326863.html 一.字符串问题 字符串在我们平时的编码工作 ...
- 通过反编译看Java String及intern内幕--费元星站长
通过反编译看Java String及intern内幕 一.字符串问题 字符串在我们平时的编码工作中其实用的非常多,并且用起来也比较简单,所以很少有人对其做特别深入的研究.倒是面试或者笔试的时候,往 ...
- Java String 字符串类细节探秘
一. 字符串基本知识要点 字符串类型String是Java中最常用的引用类型.我们在使用Java字符串的时候,通常会采用两种初始化的方式:1. String str = "Hello Wor ...
- Java String.replaceAll() 与后向引用(backreference)
问题 昨天看到一篇博文,文中谈到一道 Java 面试题: 给定一字符串,若该字符串中间包含 "*",则删除该 "*":若该字符串首字符或尾字符为 "* ...
- 从Java String实例来理解ANSI、Unicode、BMP、UTF等编码概念
转(http://www.codeceo.com/article/java-string-ansi-unicode-bmp-utf.html#0-tsina-1-10971-397232819ff9a ...
- Java String.split()小点
java String.split(); 别的不说,单说其中一个问题,这个函数去切分空字符串时,得到的结果: public static void main(String[] args) {// St ...
- Java总结篇系列:Java String
String作为Java中最常用的引用类型,相对来说基本上都比较熟悉,无论在平时的编码过程中还是在笔试面试中,String都很受到青睐,然而,在使用String过程中,又有较多需要注意的细节之处. 1 ...
- java String.split()函数的用法分析
java String.split()函数的用法分析 栏目:Java基础 作者:admin 日期:2015-04-06 评论:0 点击: 3,195 次 在java.lang包中有String.spl ...
随机推荐
- flex编译命令相关
最近碰到几次flex组件集版本问题,mx容器包含s组件,错误百出,会一直提示皮肤文件错误,上网查了一下,只要在工程属性中--->Flex编译器--->附加的编译参数中加入如下命令行即可:- ...
- 启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误
原因1:给定目录下jvm.dll不存在. 对策:(1)重新安装jre或者jdk并配置好环境变量.(2)copy一个jvm.dll放在该目录下. 原因2:eclipse的版本与jre或者jdk版本不一致 ...
- 北信源VRVEIS网管软件测试
650) this.width=650;" border="0" alt="" src="http://img1.51cto.com/att ...
- hdu 1199 Color the Ball
http://acm.hdu.edu.cn/showproblem.php?pid=1199 Color the Ball Time Limit: 2000/1000 MS (Java/Others) ...
- Python字典 (dictionary)
字典dict,是Python唯一的标准mapping类型,也是内置在Python解释器中的. mapping object把一个可哈希的值(hashable value)映射到一个任意的object上 ...
- c++,windows中的字符问题
string与char*的转换方法 string a; char *b=a.c_str(); string a=new String(b); a=b; LPCWSTR是unicode的字符串,LPCS ...
- Unable to load dll 的解决方案
前几天在做项目时,需要用到一个非托管的 dll 库,其实使用 .Net 的互操作技术可以很方便地调用非托管 dll 文件中的函数,但是在执行时出现了“Unable to load dll HRESUL ...
- poj1584
题意:已知一个多边形的n个顶点坐标,然后再给一个钉子,给定钉子的半径和圆心坐标,首先判断多边形是否为凸多边形,若为凸多边形,再判断钉子是否可以放到凸多边形内部. 思路: 1.由于顶点给出的顺序可能为逆 ...
- Spring+jpa+access
========访问数据库的属于文件============ driver=com.hxtt.sql.access.AccessDriverurl=jdbc:access:/D:/eclipse/pr ...
- C#扫描仪编程、条形码识别编程资料
扫描仪编程资料:http://www.cnblogs.com/wubh/archive/2011/11/07/2239178.html 图片条形码识别资料:http://www.codeproject ...