New Delhi, India
minigranth@gmail.com

Strings In Java

Created with Sketch.

Core Java Tutorial

Java Programs » Tutorials Library »
[fblike]

Strings In Java : Introduction

  • Generally strings are sequence of characters. Strings in java are objects. Java provide with a String class which contains method to handle strings.
  • Apart from String class, Java also provides StringBuffer and StringBuilder class for string handling. All three classes have some differences.
  • The String, StringBuilder and StringBuffer classes are defined in java.lang. All of them implements CharSequence interface.

 

String Class :  Strings created using  String object are immutable, i.e. cannot be changed.

 

Creating Strings In Java

1) String Literal

  • We can create a string using string literal. We can use string literal to initialize a string object.

For example

String s = “Hello”;   // autoboxing

String s1 = “Hello”;    // s1 refers where s refers

  • Strings created using string literal are stored in Java’s string pool. String pool is a special memory area inside heap memory.
  • While creating strings using string literal, JVM will check in string pool for the string. If it exists it will not create it again but it will just create a reference to existing string.

 

2) Using "new" Keyword

  • We can also create a string using new keyword. When we use new keyword String object is create in heap memory and not in String pool.

For example

String s = new String(“hello”);

  • To create an empty string we will write String s = new String();

 

Strings In Java : Character Array to String Conversion

  • Suppose we have a character array as :

char ch[] = {‘h’,’e’,’l’,’l’,’o’};

String s = new String(ch); // to convert into String

 

This image describes the basics of strings in java.

Example

 

Output

Output

 

Concatenating Strings In Java

1) Using + operator :  Concatenation means combining two strings. We can use "+" operator to concatenate strings.

 

2) Using concat() method : Concatenation can also be done using concat() method of String class.

 

Example

 

Example

 

Output

 

Output

 

Comparing Strings In Java

  • Comparing two strings in java is quiet possible. This can be done using any one of the three best known methods. The one being equals() method or by using “==” operator or by using compareTo() method. Both of these are discussed below.

 

1) Using equals() method

  • public boolean equals(Object anObject) , compares string to the specified object. It returns true if Object is not null and String matches with the characters of passed arguments.

Note : public Boolean equalsIgnoreCase(String anotherString) , compares one string to another string , without considering the case of characters ( upper case and lower case).

For example : If we compare “HELLo” and “hello” , then equalsIgnoreCase() will return true.

 

2) Using == Operator

  • ==” compares references not the string. Hence it will return true if both string object refers to the same instance.

Note-1 : “==” work well with null reference , but equals() will throw NullPointerException.

Note-2 : Prefer to use equals() than == to compare Strings for equality,since == compares object references not the content of string.

 

3) Using compareTo() method

  • Above mentioned ways compares strings only for equality, but compareTo() method compares strings for less than , greater than or equal to another string i.e. compares two strings lexicographic-ally.
  • It returns an integer value based on comparison . It returns a positive number if String is greater than argument string, negative number if less and 0 if equal.
  • We will take an example to demonstrate above 3 ways to compare strings.

 

Example

 

Output

 

Output

 

String In Java : Class Methods

  • There are a number of class methods under strings in java which can be categorized into three categories i.e. category-1, category-2 and category-3. All of these are explained below along with thier examples.

Category-1

Method Description
1) length() This method return an integer value which is the length of the String.
2) charAt(int index) This method return a char value which is the character at specified index.
3)indexOf(char ch) This method returns the index of the first occurrence of specified character.
3a) indexOf(char ch, int startIndex) Will return the index of first occurrence of character from the specified startIndex.
3b) indexOf(String str) Will return the index of first character of the substring specified.
3c)indexOf(String str, int startIndex) Will return the index of first character of the substring specified from the specified index.
4)substring(int startIndex) Returns a substring from the specified index to the end of the string.
4a) substring(int startIndex, int endIndex) Returns a substring from the startIndex to lastindex-1.
5) replace(char oldChar, char newChar) Return a string with replaced characters as specified.

 

Example

  • Let us demonstrate above 5 methods with an example.

 

Example

 

Output

 

Output

 

Category-2

Method Description
6)toLowerCase() Converts string into lower case.
7)toUpperCase() Converts string into upper case.
8)toCharArray() Converts the string into character array.
9) isEmpty() Returns true if string length is 0 else returns false.
10) valueOf() This method returns string representation of passed argument. In simple terms this method is used to convert primitive types into String.
11) trim() Returns a string with leading and trailing white spaces removed.

 

Example

  • Let us demonstrate above six methods with an example.

 

Example

 

Output

 

Output

 

Category-3

Method Description
12) lastIndexOf() This method returns the index of the last occurrence of a character or a substring.
12a) lastIndexOf(char ch)  To search for the last occurrence of a character and get the index.
12b) lastIndexOf(char ch, int startIndex) To search for the last occurrence of a character and get the index from the specified startIndex to 0.
12c) lastIndexOf(String str)  It  searches  for the last occurrence of the substring.
12d) lastIndexof(String str, int startIndex) Searches for the last occurrence of the substring from the specified startIndex to 0.
13) startsWith(String str) Returns true if string starts with specified string else return false.
13a) startsWith(String str, int startIndex) Returns true if string from the specified index starts with specified string else returns false.
14) endsWith(String str) Returns true if string ends with specified string else returns false.
15) getBytes() This method converts the characters in the string to bytes and hence it returns a byte array. Byte array is the ASCII equivalent of each character in string returned as a byte array.

 

Example

  • Let us demonstrate above methods with an example.

 

Example

 

Output

 

Output

 

  • The above explained methods are the most common methods, but there are other methods too for which one can refer to official String class documentation by Oracle.

 

Strings In Java : StringBuffer Class

  • StringBuffer class under strings in java is used to create mutable and thread-safe (multiple threads can’t access it simultaneously) string object.
  • Strings in java are created using StringBuffer can be changed unlike String class objects.
  • Use StringBuffer when you want to make modifications in strings and want your object to be thread-safe.

 

Constructors of StringBuffer Class

1) StringBuffer( )

  • This constructor constructs a string buffer with no characters in it and an initial capacity of 16 characters.

 

2) StringBuffer(String str)

  • This constructor constructs a string buffer initialized to the contents of the specified string with room for additional 16 characters.

 

3) StringBuffer(int capacity)

  • This constructor constructs a string buffer with no characters in it and the specified initial capacity.

 

4) StringBuffer(CharSequence chs)

  • This constructor constructs a string buffer that contains the same characters as the specified CharSequence.

 

Common Methods of StringBuffer Class

1) length() 

  • This method returns the length of the StringBuffer .

 

2) capacity()

  • This method return the total capacity of StringBuffer i.e. length of StringBuffer+ length of extra room for characters.

 

3) ensureCapacity(int capacity)

  • This method is used to increase or decrease the capacity of StringBuffer.

 

4) append(String str)

  • This method appends specified string at the end of string. Apart from string , it can also append all primitive types, objects and CharSequence. Every time this method is called for a particular parameter an implicit call to valueOf() method is made to convert it into string representation.

 

5) setCharAt(int index, char ch)

  • This method sets the value of a character at specified index.
  • charAt() can be used to get the character at specified index as discussed before.

 

6) insert()

  • This method is used to insert one string into another string at specified index. Apart from string we can insert any primitive types, Object type and CharSequence. Like append() method this method also calls valueOf() method to obtain string representation of parameter.

 

Example

  • Let us take an example using above discussed methods.

 

Example

 

Output

 

Output

 

7) reverse()

  • This method reverse the characters in StringBuffer object.

 

8) substring()

  • This method extract a portion of string(substring)  specified from the StringBuffer string.
  • Syntax : It accepts parameters i.e. a start index or it can also accept start index and end index.

 

9) replace()

  • This method replace this StringBuffer string with specified string from specified startindex to endIndex-1 .
  • Syntax : replace(int startIndex, int endIndex, String repStr)

 

10) delete()

  • This method deletes the characters of StringBuffer object from specified startIndex to endIndex-1.
  • Syntax : delete(int startIndex, int endIndex);

 

11) deleteCharAt()

  • This method deletes a character of StringBuffer object from a specified index.
  • Syntax : delete(int index);

 

Example

  • Let us take an example showing the use of above methods.

 

Example

 

Output

 

Output

 

  • There are other function defined for which you can refer to official documentation of StringBuffer class by Oracle.

 

Strings In Java : StringBuilder Class

  • StringBuilder class under strings in java create mutable string objects. This class is similar to StringBuffer class except that StringBuilder class is not thread safe, hence no guarantee of synchronization. Also StringBuilder is faster in performance.
  • The methods of StringBuilder are same as that of StringBuffer , only difference is that methods in StringBuffer are synchronized whereas that of StringBuilder are not.
Java Programs » Tutorials Library »