How to write string functions in Java?
Answers
Bookmark
Email Post
According to TIOBE index, Java stands at 1st place and this makes java course the most engrossed. In our previous blogs – Java tutorial and object-oriented programming, we have discussed the various fundamental concepts of Java and have built a strong foundation in Java. In this blog, we will be discussing about a new concept, Java String. String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.
There are two ways to create a String object:
1 By string literal : Java String literal is created by using double quotes.
2 For Example: String s=“Welcome”;
3 By new keyword : Java String is created by using a keyword “new”.
4 For example: String s=new String(“Welcome”);
5 It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.
Now, let us understand the concept of Java String pool.
Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. Refer to the diagrammatic representation for better understanding:

In the above image, two Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created with the value “Apple”, instead of creating a new object, the already present object reference is returned. That’s the reason Java String pool came into the picture.
Before we go ahead, One key point I would like to add that unlike other data types in Java, Strings are immutable. By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared. For example:
String str =”abc”;
is equivalent to:
char data[] = {‘a’, ‘b’, ‘c’};
String str = new String(data);
Answer: by using string literal and string keywords
Explanation: