A string is a sequence of symbols. Java provides you with String class in java.lang package, which does not require an import statement. That means Strings are available to use anywhere. String class provides many operations for manipulating strings.

  • Constructors
  • Utility
  • Comparisons
  • Conversions

An object of the String class represents a string of characters.

String Basics-Declaration and Creation

There is no single way to create a string in java. Following are some of the different ways to create strings in java:

String str = "niit";
String name=str;
String stringName= new String ("string value");
String city=  new String ("Islamabad");

In Java, we traditionally declare a String with initial value of null. If we declare a String variable without initialization e.g String myString; what would happen? We have to initialize String variable with special null value, if you really don’t want to initialize it with useful value at the start.

String myString = null; 

We can define an empty string as given below:

String str = new String( );

We can define a string with initial value as:

String str = new String("Java Strings");

(Note!  String str = “Java Strings”; produces the same result)


Characters in Strings can not be changed after the Strings are created. Once created, a string cannot be changed. None of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely. There is no danger of changing an object through one reference without the others being aware of the change.

Immutable strings are efficient because it uses less memory. Following figure might explain the difference between mutable and immutable strings.

String Objects

String objects are immutable — they cannot be changed once they have been created.  References to string objects may be changed.

String str1 = new String("I like dogs.");
String str2 = new String("I prefer cats.");
str1 = str2; //reassign reference

String Operations in Java

String Classes:
Following are some useful classes that Java provides for String operations.

  • String Class
  • StringBuffer Class
  • StringTokenizer Class
String Operations:
  • int length()
  • char charAt(int index)
  • indexOf( ) & lastIndexOf( )
    • indexOf(char ch)          // first position of ‘ch’
    • indexOf(String str)       // first position of ‘str’
    • lastIndexOf(char ch)    // last position of ‘ch’
    • lastIndexOf(String str) // last position of ‘str’
  • String Substring (int) & String Substring (int startindex, int lastindex)
  • public String toLowerCase() & public String toUpperCase()
  • startsWith(String prefix)   &  endsWith(String suffix )
  • public String trim() – Returns a copy of the string, with leading and trailing whitespace omitted.
  • public String replace(char oldChar, char newChar) – Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
  • Concatenation  (+) returns  a string

Concatenation Example

Declare and construct two strings, then concatenate str2 to the end of str1.

String str1 = new String("This is the winter");
String str2 = new String("of our discontent");
str1 = str1.concat(str2); //concatenate str1 with str2

Note! The same result occurs for str1 = str1 + str2;

toCharArray( )

String string1 = "Hello How are you";
char[] array = string1.toCharArray(); 

copyValueOf( )

Static method
String string2;
string2 = String.copyValueOf(array); //copyValueOf(array,6,3);

String Comparison

Following are different ways to compare strings in Java.

  • Shallow comparison  = =
  • Deep comparison     equals( );
  • Deep comparison     compareTo( );

Shallow comparison using ==

The == will check whether the two String variables refer to the same string. If strings reference two separate strings, you will get false regardless of whether or not the strings happen to be identical. It does not compare the strings themselves, it compares the references to the strings, hence called shallow comparison.

Deep Comparison using equals()

Equals( ) is used to decide whether the strings referred by two String variables are equal or not. This method does a case sensitive comparison. Two strings are equal if they are the same length and each character in one string is identical to the corresponding character in the other. Use equalsIgnoreCase( ) method to check for equality between two strings ignoring the case of the string characters.

String s1 = new String ("I am a string");
String s2 = " a string";
String s3 = s1.substring(0,4);
String s4 = " a string";
String s5 = s3 + s2;
if (s5 == s1) {  }
if (s1.equals(s5))  {  }
if (s2 == s4)  {  }
if (s5.equals(s3+s4))  {  }

Deep Comparison using compareTo()

compareTo( ) is used to decide whether the string object from which it is called is less than , equal to or greater than the string passed as argument to it. Returns an integer which is negative if the String object is less than the argument String. Returns positive integer if the String object is greater than the argument String. It returns zero if both are equal.

System.out.println("hello".compareTo("hell"));  // returns 1

StringBuffer objects can be altered directly. A String object is always a fixed string. How to create StringBuffer objects?

StringBuffer string1 = "Hello How are you";//not allowed
StringBuffer string1 = new StringBuffer("Hello How are you");

StringBuffer contains a block of memory called buffer which may or may not contain a string and if it does, the string need not occupy all of the buffer.

append( );

string1.append(string2,3,3); //appending substrings
string1.append(x);//where x is an int

insert( );

string1.insert(4," how");//4 is the index position

insert also has many versions like append

Other Useful methods of StringBuffer Class

You can produce a String object from a StringBuffer object by using the toString( ) method of the StringBuffer class

String string2 = string1.toString( );

How does the compiler handles the string concatenation of String objects? Append( ) and toString( ) methods are used

String message = "hello" + "How are you";
String message = new StringBuffer( ).append("Hello").append("how are you").toString( );
Tagged with: ClassesJAVAObject Oriented

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.