String Operations

String

public final class String
extends Object
implements Serializable, Comparable, CharSequence

The String class represents character strings. All string literals in Java programs, such as,”abc” are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

Example

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};
String str = new String(data);

Example

class StringExample {
	public static void main(String[] args) {
		int n, c, d, swap;
		Scanner in = new Scanner(System.in);
		System.out.println("enter numbers:");
		n = in.nextInt();
		int num[] = new int[n];
		System.out.println("Enter " + n + " integers");
		for (c = 0; c < n; c++)
			num = in.nextInt();
		for (c = 0; c < (n - 1); c++) {
			for (d = 0; d < n - c - 1; d++) { if (num[d] > num[d + 1]) {
					swap = num[d];
					num[d] = num[d + 1];
					num[d + 1] = swap;
				}
			}
		}
		System.out.println("Sorted list of numbers");
		for (c = 0; c < n; c++)
			System.out.println(num);
	}
}
    • The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase.
    • Case mapping is based on the Unicode Standard version specified by the Character class.
    • The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
    • String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
    • String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

Note: String is a class in java and is immutable

StringBuffer

public final class StringBuffer 
extends Object 
implements Serializable, CharSequence
  • A thread-safe, mutable sequence of characters. A string buffer is like a String but can be modified. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls
  • String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved
  • The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer
  • The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point

Let us look at this example indication different usage of string and StringBuffer:

String str = new String("abc");
str += "def";

If you were to use StringBuffer to concatenate your code need to look like this:

StringBuffer str = new StringBuffer("abc");
str.append("def");

StringBuilder

public final class StringBuilder 
extends Object
implements Serializable, CharSequence
  • The java.lang.StringBuilder class should be used when you have to make a lot of modifications to strings of characters. Objects of type StringBuilder can be modified over and over again without leaving behind a great effluence of discarded String objects. StringBuilder
  • Objects are the ideal way to handle a block of data, pass it on, and then reuse the same memory to handle the next block of data
  • This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
  • This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
  • The StringBuilder class was added in Java 5. It has exactly the same API as the StringBuffer class, except StringBuilder is not thread-safe i.e its methods are not synchronized.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

Let’s see an example explaining the above concept:

String x = "abc";
x.concat("def");
System.out.println("x = "+x);              // output is "x = abc"

It is because no new assignments are made. Now, when we use StringBuilder as:

StringBuilder sb = new StringBuilder("abc");
sb.append("def");
System.out.println("sb = "+sb);           // output is "sb = abcdef"

So here we are not creating any extra objects, each one needs only a single StringBuffer object to execute.

Most Frequently asked questions on “String” operation in Java?

It is not suggested or advised to do so because equality operator is used to comparing primitives and equals() method should be used to compare objects.
As we know that String object created by new() operator is not added in String pool by default as opposed to String literal. The intern() method allows putting a String object into a pool.
No, String is not a keyword but it is a final class in java.lang package which is used to represent the set of characters.
The objects of String class are immutable in nature. If you try to modify them, a new object will be created with modified content. This may cause memory and performance issues if you are performing lots of string modifications in your code. To overcome these issues, StringBuffer and StringBuilder classes are introduced in Java.
In C and C++, strings are terminated with the null character. But in Java, Strings are treated as objects.