String In Java with Example

String—a class for working with fixed-string data—that is unchanging data composed of multiple characters, strings that are immutable.String contain sequences of 16-bit Unicode characters. The String class contains an immutable string. Once an instance is created, the string it contains cannot be changed. Every string literal is represented internally by an instance of String. Java classes may have a pool of such strings.

With the constructor:

String s1 = new String(“immutable”); //causes extra memory allocation for no obvious advantage.

Without the constructor:
String s1 = “immutable”;  //better
Comparing String Values:

  • The String class provides methods for comparing strings
  • In the example above the == sign is comparing memory addresses, not the actual strings.
  • The String class equals() method evaluates the contents of two String objects to determine if they are equivalent. 
Contains rich methods to manipulate String
  • Operations that create new strings: concat, repalce, substring, toLowerCase, toUpperCase and trim
  • Search operations: endsWith, startsWith, indexOf, and lastIndexof
  • Comparisons: equals, equalsIgnoreCase and compareTo
  • Others: charAt and length

public class StringExample {

 public static void main(String[] args) {
 // Creating a String using Constructor
 String str = new String("");
 // Creating a String without Constructor
 String st = "";
 //Comparing Using equals method
 // Comparing using == 
 System.out.println(str == st);
 char[] charArray ={'J','A','V','A'}; 
 char c = 'J';
 // Converting char to String
 int i = 25;
 // Converting int to String
 System.out.println("Option 1: "+Integer.toString(i));
 System.out.println("Option 2: "+String.valueOf(i));



Recent Posts