Introduction to Strings
0% completed
Introduction to Strings
StringBuffer and StringBuilder
Character Array to String
String References
String Comparison
Character at an Index
Character at an Index II
String Concatenation
String Comparison II
Mutable Character Sequences
Multithreading
Basics Of Java
Introduction to Strings

 

Introduction to Strings

footer line

Strings in Java

 

Strings are a sequence of characters, and in the Java programming language, they are considered objects. The String class is provided by the Java platform for creating and manipulating the strings.

 

We can directly create a string by writing:

 

String str = "Hello world";

 

In the above example, "Hello world!" is a string literal—a sequence of characters enclosed in double quotations. The compiler generates a String object with its value—in this case, Hello world!, whenever it finds a string literal in code.

 

Note: Strings in Java are immutable that implies we cannot modify their value. Whenever required, StringBuffer and StringBuilder classes can be used to create mutable strings.

 

In Java, there are two ways to create a string:

  1. By assigning a string literal directly to a String reference -­ just like a primitive, or
  2. As for every other type, the "new" operator and constructor are used (like arrays and scanners). This, however, is not widely used and is not recommended.

 

Example:

 

// Implicit construction
String str1 = "Learning Java";

// Explicit construction
String str2 = new String("Java is Interesting!");

 

In the above code, str1 is declared as a String reference and initialized with the string literal "Learning Java" in the first statement. The second statement declares str2 as a String reference and uses the “new” operator to initialize it with "Java is Interesting!"

 

String literals are stored in a common pool called String pool, where the strings with the same contents share the same space (resources). This helps to save and utilize the space efficiently.

String objects created using new operators, on the other hand, are stored in the heap memory. No storage sharing is possible in the heap memory, and every object, thus created, has its own allocated space.

 

 

Char Arrays and Strings

 

An array of characters behaves in the same manner as a Java string. Let us see an example to understand this.

 

Example:

 

public class StringsExample {

    public static void main(String args[]) {
        char[] str = {'C', 'o', 'd', 'i', 'n', 'g', ' ', 'N', 'i', 'n', 'j', 'a', 's'};
        System.out.println(str);
    }
    
}

 

Output:

 

Coding Ninjas

 


String Literal v/s String Object
 

As previously stated, there are two methods for constructing a string: implicitly, by assigning a string literal or explicitly, by creating a String object using the new operator and constructor.

 

Java has a specialized feature for storing String literals -­ in what is known as a string common pool. If the contents of two string literals are the same, they will share the same storage space within the common pool. This strategy is used to save storage space for commonly used strings. String objects created with the new operator and constructor, on the other hand, are stored in heap memory. Each String object in a heap, like every other object, has its storage, and even if two String objects have the same contents, their storage spaces are unique and distinct in the heap.


String is Immutable
 

Since String literals having the same contents share storage in the same pool, Java's String is intended to be immutable. In other words, once a String is created, its contents cannot be changed. Otherwise, the modification would affect all other String references that use the same storage space, which can be uncertain and undesirable. Methods like toLowerCase() and toUpperCase() might appear to change the contents of a String object. But actually, a completely new String object is created and returned to the caller. Once there are no further references to the original String object, it will be deallocated and garbage collected.

 

Since String is immutable, it is inefficient to use it if we constantly need to change the String because that would create many new Strings occupying new storage areas, resulting in complete wastage of space.

 

 

String Concatenation

 

Concatenation is the joining of two strings to form a single string. There are several methods for concatenating strings, which are as follows:

  • ‘+’ operator
  • concat() method

 

i)+’ operator

 

The ‘+' operator joins the two input strings and returns a new string containing the concatenated string.

 

Syntax:

 

String newString = string1 + string2;

 

Example:

 

public class ConcatenationExample{

    public static void main(String args[]) {
        String str1 = "Coding";
        String str2 = " Ninjas!";
        str1 = str1 + str2;

        System.out.println("Concatenated String: " + str1);
    }
    
}

 

Output:

 

Concatenated String: Coding Ninjas!

 

 

ii) concat() method

 

The String concat() appends the specified string to the end of the current string.

 

Syntax:

 

string1.concat(string2);

 

Example:

 

public class ConcatenationExample{

    public static void main(String args[]) {
        String str1 = "Coding";
        String str2 = " Ninjas!";
        str1 = str1.concat(str2);

        System.out.println("Concatenated String: " + str1);
    }
    
}

 

Output:

 

Concatenated String: Coding Ninjas!

 

Note: The concat() method is better than the '+' operator since it produces a new object only when the length of the String to be appended is greater than zero, while the '+' operator always creates a new string regardless of the length of the String. 

 

 

String Comparison

 

String comparison is performed to determine whether or not the two strings are equal. Strings in Java can be compared using the following methods:

  • equals() method
  • == method
  • compareTo() method

 

i) equals() method

 

The String equals() method compares the string's original content. It compares the string values for equality. For this purpose, the String class has two methods:

  • public boolean equals(Object anObject): Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
  • public boolean equalsIgnoreCase(String another): Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.

 

Example:

 

public class ComparisonExample{

    public static void main(String args[]) {
        String str1 = "Coding";
        String str2 = " Ninjas!";
        String str3 = "Coding";
        String str4 = "coding";

        System.out.println(str1.equals(str2));
        System.out.println(str1.equalsIgnoreCase(str3));
        System.out.println(str1.equalsIgnoreCase(str4));
    }
    
}

 

Output:

 

false
true
true

 

 

ii) == method

 

The == operator compares references rather than values.

 

Example:

 

public class ComparisonExample{

    public static void main(String args[]) {
        String str1 = "Coding Ninjas";
        String str2 = "Coding Ninjas";
        String str3 = new String("Coding Ninjas");
        System.out.println(str1 == str2); //true (as both str1 and str2 refer to same instance)  
        System.out.println(str1 == str3); //false(because str3 refers to instance created in heap)  
    }
    
}

 

Output:

 

true
false

 

 

iii) compareTo() Method

 

The String compareTo() method compares two strings lexicographically. It returns an integer indicating whether the first String is greater than, equal to, or less than the second String.

 

If str1 and str2 are two string variables, then 

  • Result = 0 for str1 == str2
  • Result > 0 for str1 > str2
  • Result < 0 for str1 < str2

 

If we don't want the result to be case sensitive, we can use the compareToIgnoreCase() method.

 

Example:

 

public class ComparisonExample{

    public static void main(String args[]) {    
        String str1 = "Coding";
        String str2 = " Ninjas!";
        String str3 = "Coding";
        String str4 = "coding";
        
        System.out.println(str1.compareTo(str2));
        System.out.println(str1.compareTo(str3));
        System.out.println(str1.compareToIgnoreCase(str4));
    }
    
}

 

Output:

 

35
0
0