Skip to main content

All about String in Java

String : Immutable, String Pool, String Buffer,  String Builder, String Methods

String:  it is basically an Object which represents a sequence of characters
The Java platform provides the String class to create and manipulate strings. An array of characters works same as java string.
For ex:
char [] c = {'j','a','v','a'};

String s = new String(s);

or simply : 

String s = "java";


Unlike C and C++ , String does not terminate with null character.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
String is immutable i.e. it can not be changed once created, on changing new instance is created.
To overcome this two more classes are there in java : StringBuffer and StringBuilder. All these are in the same package: java.lang

Creating String : We can create string in two ways: 1) String literal 2) Using new keyword

String literal :
 Java String literal is created by using double quotes. For Example: String str = "Hello";

Every time  a string literal is created, first of all JVM checks the string constant pool . If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

String s1="Hello";  

String s2="Hello";  // previous object reference will be returned. New object will not be created.

 Using new keyword:  it is like creating any object in java. For example :  String str=new String("Hello");

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool).

Some useful String methods with description :

No.MethodDescription
1char charAt(int index)returns char value for the particular index
2int length()returns string length
3static String format(String format, Object... args)returns formatted string
4static String format(Locale l, String format, Object... args)returns formatted string with given locale
5String substring(int beginIndex)returns substring for given begin index
6String substring(int beginIndex, int endIndex)returns substring for given begin index and end index
7boolean contains(CharSequence s)returns true or false after matching the sequence of char value
8static String join(CharSequence delimiter, CharSequence... elements)returns a joined string
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)returns a joined string
10String concat(String str)checks the equality of string with object
11boolean isEmpty()checks if string is empty
12boolean equals(Object another)concatinates specified string
13String replace(char old, char new)replaces all occurrences of specified char value
14String replace(CharSequence old, CharSequence new)replaces all occurrences of specified CharSequence
15String trim()returns trimmed string omitting leading and trailing spaces
16String split(String regex)returns splitted string matching regex
17String split(String regex, int limit)returns splitted string matching regex and limit
18String intern()returns interned string
19int indexOf(int ch)returns specified char value index
20int indexOf(int ch, int fromIndex)returns specified char value index starting with given index
21int indexOf(String substring)returns specified substring index
22int indexOf(String substring, int fromIndex)returns specified substring index starting with given index
23String toLowerCase()returns string in lowercase.
24String toLowerCase(Locale l)returns string in lowercase using specified locale.
25String toUpperCase()returns string in uppercase.
26String toUpperCase(Locale l)returns string in uppercase using specified locale.


What is String POOL:
String Pool is a pool of Strings stored in Java Heap Memory.
Because String objects are immutable, it's safe for multiple references to "share" the same String object . Whenever a new instance of an already known Strings is needed, then already existing object reference is returned.
This way it helps to manage the memory efficiently.
Example :
String s1 = "test";

String s2 = new String("test");  // "new String" guarantees a different object

String s3 = "test";




System.out.println(s1 == s2);  // prints false as both object does not points to same refrence

System.out.println(s1 == s3);  // prints true , because string pool return the same reference  


* String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.
You can add a string to the pool by calling String.intern(), which will give you back the pooled version of the string . So , you can also put a string object created using new keyword into String pool by using intern as shown below

s2 = s2.intern();

System.out.println(s1 == s2);  // should print true



What are StringBuilder and StringBuffer


These two classes are almost the same (they have the same API). The difference between them is that StringBuilder  is NOT thread safe  and it is faster.
Both classes are defined because they implement in a more efficient manner (memory) processing of string values. One reason is that their values are not stored in String Constant Pool and they behave like normal object – when the object is not references is destroyed by GC and it will not remain in String Constant Pool.
The idea behind StringBuilder and StringBuffer is to provide the means for efficient I/O operations with large streams.
StringBuilder and StringBuffer instances are created using only new operator and NOT with = like Strings:

Example :
StringBuilder sbuild = new StringBuilder("Hello");

StringBuffer sbuf = new StringBuffer("Hello Java !");

 
If you want to modify the value of a StringBuilder or StringBuffer you can use the methods from this classes. Most used methods are:
Method Description
append() adds the argument to the end of the current object
delete() deletes chars between a start and end index
insert() inserts a value at a given offset
reverse() reverse the value of the current object
toString() returns the value of the StringBuilder or StringBuffer object

Another fact about StringBuilder or StringBuffer is that you can call multiple methods  – chained methods on the same object.  Chained methods affect the calling object and they are executed from left to right.

Comments

Popular posts from this blog

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Java Priority Queue sort using lambda expression

Priority Queue :     In Java  Priority Queue  is a  queue  which keeps its elements sorted as per their natural order( example in ascending orders for Integer, alphabetical a-z for alphabets) or using a custom Comparator at the time of creation you can custom sort it. It has most method  similar to a queue  add, clear, poll, peek As priority queue have to compare elements to keep in order so elements must be comparable otherwise, it will throw ClassCastException .  As null can not be compared so you are not allowed to insert null too A program to sort priority queue using Lambda function in Java           c lass   PriorityQueueLambdaJava { public List<Integer> KFrequent( int [] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for ( int j: nums) { map .put(j, map .getOrDefault(j, 0 ) + 1 ); } PriorityQueue<Map.Entry<Integ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...