Thursday, November 16, 2023

Strings

 Strings

strings are sequence of characters  often used for representing text normally.  But in Java, string is an object that represents a sequence of characters.It is covered by " " in each side object.

example:- "kumar", "leela"

Strings Immutabality

Generally strings immutable in nature means when we want change the original string value directly  then it will not change instead it will return  original  value.

Once String object is created then  its data or state can't be changed but a new String object is created

example1:-

Class Immutable{

public  static void main(String[] args){

String str1="rahul";

//we are directly try to change the originalvalueusing conact//

str1.concat("dravid");

System.out.println(str1);

}

}

output:- rahul

example2:-

Class Immutable{

public  static void main(String[] args){

String str1="rahul";

//we are assigning a  object reference variable here and then concat//

str1=str1.concat("dravid");

System.out.println(str1);

}

}

output:-rahuldravid


Strings Mutable Versions

StringBuffer:-

Because of string high usabelity  oracle introduced one of the mutable version called

stringbuffer .

Intraduced in JDK 1.0 version

It is synchronized and threadsafe means two threads can call the method simultaneously.

Suitable for scenarios where multiple threads may access the same instance concurrently.

It is less efficient.

example
StringBuffer stringBuffer = new StringBuffer("Hello");
stringBuffer.append(" World");
String result = stringBuffer.toString();
System.out.println(result);

output:-HelloWorld

StringBuilder:-
Because less efficiency of StringBuffer oracle introduced StringBuilder in JDK version 5.0

It is  not synchronized and threadsafe means two threads cannot  call the method simultaneously.

Preferred when the class will only be accessed by a single thread.

It is more efficient.

example
StringBuilder stringBuilder = new StringBuilder("Hello");
stringBuilder.append(" World"); 
String result = stringBuilder.toString(); 
System.out.println(result);

output;- HelloWorld

No comments:

Post a Comment