Home Java SCJP SCWCD Servlet Submit News Contact Us Site Map


Over 500 magazines for free (including Oracle Magazine)!

Yes all of them are FREE. You can subscribe to ALL of them.
Click here to apply today!

Home > Java > Java Articles

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 >>

 

Home Java SCJP SCWCD Servlet Site map