Skip to main content

String - A story of very special class in java

String is most used java class in any java project. Java treated String as special class. Lets see, what so special in String.

String Basics

  • String is group of characters.
    
    char[] chrs = {'i',' ','a','m',' ','h','e','r','o','.'};
    String str = new String(chrs);
    System.out.println(str);
    /*
    Output: 
    i am hero.
    */
    
  • String is an immutable class.
    Immutable class: A java class which object can not be modified if once created.
    Because String class is immutable, String is final in nature, its mean you can not modify string object once you created.
  • Default value of string is null.
Simplest way to initialize String is

//object created in String Literal Pool 
String str = "hello world";
Above example known as String literal, All string literals in Java programs, such as "hello world", are object of String class.
Another way to create String object is

//object created in Heap memory  
String str = new String("hello world");
For now just remember Heap memory and String Literal pool are two different memory space where string object can live and mostly 1st way use to initialize string.

Check default value of String:

public class StringTest{

  //instance variable
  String str1;

  public static void main(String[] args){
    StringTest test = new StringTest();
    System.out.println(test.str1); 
  }

}
/*
Output: 
null
*/

Compare two string

Use equals method to compare two string value rather than == operator.

public class StringTest{

  public static void main(String[] args){
    String str="hello";
 //comparing two String
 boolean b1 = str.equals("hello");
 if(b1){
    System.out.println("true");
 }
  }
}
/*
Output: 
true
*/
If you perform any operation on null it will give you null pointer exception.

public class StringTest{

  //print name if name == "tony"
  public void printName(String name){
    //null pointer exception can occurred if name value is null
   // in case of null, you perform equals operation on null
   // any operation on null gives null pointer exception 
    if(name.equals("tony")){
     System.out.println(name); 
 }
  }

  public static void main(String[] args){
    StringTest test = new StringTest();
    test.printName(null);
  }

}
/*
Output: 
Exception in thread "main" java.lang.NullPointerException
*/

String Literal Pool 

 We have two way to define String object.

//String literal Object
String str1 = "Hello i am String Object";

//New String object
String str2 = new String("Hello i am String object");

System.out.println(str1);
System.out.println(str2);
output:
Hello i am String Object
Hello i am String Object

Both returns same value. 1st String object created in String Literal Pool and 2nd String object created in Heap Memory.

How JVM handle String objects?

Usually a java project contains lot of String object. for memory optimization JVM provides particular memory container where only String literal object will store, known as String Literal Pool.

What the benefit of String Literal Pool and Sting as Immutable class?

String is an Immutable class. Immutable class object can not change once it get initialized.

Lets go with a small program

String str1 = "Hello";
String str2 = "Hello";
String str3 = "Hello";
String str4 = "Hello";

System.out.println(str1);
System.out.println(str2);
Memory Optimization:
All 4 reference have same value "Hello". JVM not going to create 4 "Hello" in memory instead JVM creates only one "Hello" in String Literal Pool and other new initialization with same value like "Hello", point same memory location in String Literal Pool.

Question: You can add string in to another string. How String is Immutable?

//here added two string
String str1 = "Hello";
str1 =  str1 + " World";
System.out.println(str1);
Output:
Hello World

It seems, you have changed string value. But str1 string reference point new string value "Hello World". In String literal pool, first two String literal object created 1st "Hello" 2nd " World" and by adding these two you have created 3rd object "Hello World". str1 reference point this 3rd Object. You can't change string object because it's immutable, but by adding different string literal object you can create a new string literal object.

String Useful Methods

Get String Length

public int length()
Modifier: public
Return type:
int
Method name: length
Description: Returns total number of character in a string.

//Example:
String str = "mytutorialbox";
int length = str.length();
System.out.println(length);
/*
Output: 
13
*/

charAt method

public char charAt(int index)
Modifier: public
Return type:
char
Method name: charAt
Args: int
Description: Returns the char value at the specified index.

//Example:
String str = "mytutorialbox";
char c = str.charAt(2);
System.out.println(c);

System.out.println(str.charAt(0));
System.out.println(str.charAt(1));
/*
Output: 
t
m
y
*/

concate method

public String concate(String str)
Modifier: public
Return type:
String
Method name: concat
Args: String
Description: Add the specified string to the end of this string.

//Example:
String str1 = "mytutorialbox";
String str2 = ".com";
String str3 = str1.concat(str2);
System.out.println(str3);
/*
Output: 
mytutorialbox.com
*/

trim method

public String trim()
Modifier: public
Return type:
String
Method name: trim
Description: Remove left/right whitespace.

//Example:
String str1 = "  mytutorialbox  ";
String str2 = str1.trim();
System.out.println(str1);
System.out.println(str2);
/*
Output: 
  mytutorialbox  
mytutorialbox
*/

valueOf method

public String valueOf(boolean b)
public String valueOf(char c)
public String valueOf(char[] data)
public String valueOf(double d)
public String valueOf(float f)
public String valueOf(int i)
public String valueOf(loang l)
Modifier: public
Return type:
String
Method name: valueOf
Args: boolean/char/char[]/double/float/int/long
Description: valueOf static method of String class work as utility, it converts given arg into String.

//Example:
int i = 10000;
String convertString = String.valueOf(i);
System.out.println(convertString);
System.out.println(convertString.concat(" int"));

boolean bool = false;
convertString = String.valueOf(bool);
System.out.println(convertString);
System.out.println(convertString.concat(" boolean"));

float f = 1.0f;
convertString = String.valueOf(f);
System.out.println(convertString);
System.out.println(convertString.concat(" float"));
/*
Output: 
10000
10000 int
false
false boolean
1.0
1.0 float
*/


StringBuffer And StringBuilder

Whenever you make any changes in String object, JVM created a new String Object.
In case, you need to make many changes in String object then you may face memory related issues. In these cases, It's good to use StringBuffer or StringBuilder.

//StringBuffer Example
public class StringBufferTest { 
 public static void main(String[] args) {
  StringBuffer message = new StringBuffer("hello.");
  message.append(" How are u?");
  message.append(" After long time");
  message.append(" good to see you");
  
  System.out.println(message);
 }
/*
 output:
 hello. How are u? After long time good to see you
 */ 
}

//StringBuilder Example
public class StringBuilderTest { 
 public static void main(String[] args) {
  StringBuilder message = new StringBuilder("hello.");
  message.append(" How are u?");
  message.append(" After long time");
  message.append(" good to see you");
  
  System.out.println(message);
 }
/*
 output:
 hello. How are u? After long time good to see you
 */ 
}

What the difference between StringBuffer and StringBuilder?

StringBuffer functions are Thread safe, StringBuilder functions not. Besides, both class have same functionalities.
StringBuffer: StringBuffer should use in multi-threaded program structure.
StringBuilder: StringBuilder is faster than StringBuffer. This should use in single threaded program.
Both classes give some new function that you can apply on string that can't be possible in String class directly.

Some important functions:


public class StringBuilderTest {
 
 public static void main(String[] args) {
  StringBuilder message = new StringBuilder("hello.");
  
  //You can append String, Gives batter performance than String concate method
  message.append(" How are u?");
  System.out.println(message);
  /*
   output:
      hello. How are u? 
  */
  
  
  //you can reverse whole string charecter by charecter
  message.reverse();
  System.out.println(message);
  message.reverse();
  /*
   output:
      ?u era woH .olleh
  */
  
  //you can insert String,any primitive or boolean 
  message.insert(6, "..JON..");
  System.out.println(message);
  /*
   output:
      hello...JON.. How are u?
  */
  
 
  
 }
/*
 output:
 hello. How are u?
 ?u era woH .olleh
 hello...JON.. How are u?
 */
}

Comments

Popular posts from this blog

Java Array, Multi Dimensional Array, Anonymous Array and Arrays Util Class

Array An array is a index based container object. The length of an array fixed at time of array creation. An Array holds a fixed number of values of a single type . One Dimensional Array Array can be created by two ways. Syntex: //1st way arraytype[] name = new arraytype[length]; //2nd way arraytype name[] = new arraytype[length]; 1st way is more readable. Examples: //charecyter Array Example: //creating Array of char, length 5 char[] charArray = new char[5]; //Initialize array elements charArray[0] = 'H'; charArray[1] = 'E'; charArray[2] = 'L'; charArray[3] = 'L'; charArray[4] = 'O'; //creating Array of int, length 4 int[] intArray = new int[4]; //Initialize array elements intArray[0] = 2; intArray[1] = 0; intArray[2] = 1; intArray[3] = 5; //creating Array of string, length 7 String[] weeks = new String[7]; //Initialize array elements weeks[0] = "mon"; weeks[1] = "tue"; weeks[2] = "wed"; w