STRING IN JAVA

 STRING


In Java string is basically an object that represents sequence of char values. An arrays of characters works same as Java string. For example.

Char [] ch = {"a","v"};

String srr = new string (ch);

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.


There are two ways to create String object:

  1. By string literal
  2. By new keyword
 In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.

Whenever you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.

This is what happens when you create string objects using string literal,

When you create a string object using string literal, JVM first checks the content of to be created object. If there exist an object in the pool with the same content, then it returns the reference of that object. It doesn’t create new object. If the content is different from the existing objects then only it creates new object.”

public class StringExamples { public static void main(String[] args) { //Creating string objects using literals String s1 = "ab"; String s2 = "ab"; System.out.println(s1 == s2); //Output : true //Creating string objects using new operator String s3 = new String("ab"); String s4 = new String("ab"); System.out.println(s3 == s4); //Output : false } }





In simple words, there can not be two string objects with same content in the string constant pool. But, there can be two string objects with the same content in the heap memory.



IMMUTABLE STRING 


One more interesting thing about String objects in java is that they are immutable. That means once you create a string object, you cannot modify the contents of that object. If you try to modify the contents of string object, a new string object is created with modified content

public class StringExamples { public static void main(String[] args) { String s1 = new String("JAVA"); System.out.println(s1); //Output : JAVA s1.concat("php"); System.out.println(s1); //Output : JAVA } }

string vs string buffer vs string builder



String


1) string is immutable.

2) string is thread-safe.



StringBuffer -


1) StringBuffer is mutable means it can be change.

2) it is thread-safe 

3) it is slow in performance as compared to Stringbuilder 


Stringbuilder


1) Stringbuilder is mutable .

2) it is not thread safe.

3) because there is no synchronisation method , this approach is faster than StringBuffer and string.














Comments

Popular posts from this blog

OBJECT ORIENTED CONCEPTS

Arrays programms