Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java String, Java String Class

Handling character strings in Java is supported through two final classes: String class and StringBuffer class. The Java String class implements immutable character strings, which are read-only once the string has been created and initialized, whereas the StringBuffer class implements dynamic character strings. All string literals in Java programs, are implemented as instances of String class. Strings in Java are 16-bit Unicode.

Note : In JDK 1.5+ you can use StringBuilder , which works exactly like StringBuffer , but it is faster and not thread-safe.

The easiest way of creating a Java String object is using a string literal:

String str1 = "I cant be changed once created!";

A Java string literal is a reference to a String object. Since a Java String literal is a reference, it can be manipulated like any other String reference. i.e. it can be used to invoke methods of String class.

For example,
int myLenght = "Hello world".lenght();

The Java language provides special support for the string concatenation operator ( + ), which has been overloaded for Java Strings objects. String concatenation is implemented through the StringBuffer class and its append method.

For example,
String finalString = "Hello" + "World";

Would be executed as
String finalString = new StringBuffer().append("Hello").append("World").toString();

The Java compiler optimizes handling of string literals. Only one String object is shared by all string having same character sequence. Such strings are said to be interned, meaning that they share a unique String object. The Java String class maintains a private pool where such strings are interned.

For example,
String str1="Hello";
String str2="Hello";
If(str1 == str2)
System.out.println("Equal");

Would print true when run.
Since the Java String objects are immutable. Any operation performed on one String reference will never have any effect on other references denoting the same object.

String Constructor >>
 
Your rating: None Average: 1 (1 vote)
Share this
Anonymous's picture

another important property of

another important property of String which you can mention here is Strings are immutable in java and you can not change its values after creation which sometime leads too much string garbage if your program is doing lot of manipulation on Strings. its also worth to know Why String are immutable in java
Anonymous's picture

Strings are one of the

Strings are one of the overused feature of Java. Always handle strings properly in your code. I blogged about String usage at Strings are overused in Java

Post new comment