Tuesday, 28 August 2012

Java String Examples



The String class implements immutable character strings, which are read-only once the string object has been created and initialized. All string literals in Java programs, are implemented as instances of String class.

The easiest way to create a Java String object is using a string literal:
String str1 = "I can't be changed once created!";

A Java string literal is a reference to a String object. Since a 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".length();

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 strings 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 Equal when executed.
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 Constructors
String class provides various types of constructors to create String objects. Some of them are,

String()
Creates a new String object whose content is empty i.e. "".

String(String s)
Creates a new String object whose content is same as the String object passed as an argument.

Note: Invoking String constructor creates a new string object, means it does not intern the String. Interned String object reference can be obtained by using intern() method of the String class.

String also provides constructors that take byte and char array as an argument and returns String object.

String equality - Compare Java String
String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value accordingly.

2 comments:

  1. perfect explanation about java programming .its very useful.thanks for your valuable information.best java institute in chennai | best java training in velachery

    ReplyDelete
  2. Very much useful article. Kindly keep blogging
    Visit us: Java Online Training Hyderabad
    Visit us: Core Java Online Course
    Visit us: java course

    ReplyDelete