Java String Introduction

20 January 2012 By Nithya Vasudevan 1,471 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • String represents combinations of character literals that are enclosed in double quotes, i.e.) any character(s) inside double quotess
  • Each character in a string is a 16-bit Unicode character, to provide a rich, international set of characters.
  • The String class is immutable, so that once it is created a String object cannot be changed.
  • String class is from java.lang package.
    • It is a final class.
  • String index is zero based.
  • In Java, strings can be represented using:
    1. Array of characters
    2. The String class

A String object is different from an array of characters

There are two things to understand about Strings:

Strings are Objects in Java

  • In Java, Strings are objects and not a primitive type. Even string constants are actually String objects.
  • For example,
  • System.out.println ("Welcome to Java World");
  • The string “Welcome to Java World” is a String constant or String literal or String object.
  • Whenever it encounters a string literal/object in your code, the compiler creates a String object with its value—in this case “Welcome to Java World”.

String Objects are immutable

  • Strings are immutable; once a String object is created, its contents cannot be altered. While this may seem like a serious restriction, it is not, for two reasons:
    • If you need to change a string, you can always create a new one that contains the modifications.
    • Java defines a peer classes of String, called StringBuffer and StringBuilder, which allows strings to be altered.
  • String object is immutable; its reference variable is not.

NOTE:
This is explained in detail here.

Tags: , , ,