String in java
String is nothing but a sequence of characters. For example, “Book” is a string which is having sequence of 4 characters. There is a lot of importance of String and its usage in any programming language.
In java, there can be many operation performed on String using methods like length, replace, compareTo, intern, substring,concat, equals, split etc. We will study about them in details one by one.
You might question, why String as an object but not primitive data type like int,char,float,double etc?
There is an interesting fact about that. Look at the excerpt from a James Gosling interview:
James Gosling: Totally an efficiency thing. There are all kinds of people who have built systems where ints and that are all objects. There are a variety of ways to do that, and all of them have some pretty serious problems. Some of them are just slow, because they allocate memory for everything. Some of them try to do objects where sometimes they are objects, sometimes they are not (which is what the standard LISP system did), and then things get really weird. It kind of works, but it’s strange. Just making it such that there are primitive and objects, and they’re just different. You solve a whole lot of problems.
In short, we can say primitive data types can be considered as memory efficient because all have a fixed length in memory. e.g. a int have 4 bytes etc., String will occupy memory as per its content used i.e. String can have different length.
There are 2 ways to create String in java.
- String literal
- Using new Keyword
Let’s understand them one by one with the help of examples.
1. String Literal:
In java, String can be created by assigning some value enclosed with double quotes which points to string reference variable as shown below.
String val1 = "Java Book"; String val2 = "Java Book"; // for this new instance will not be created
There is an important concept that we need to know is , String created will be placed in a memory area called a ‘String Constant Pool’. When a string is created,JVM checks in the String constant pool that is there any other string holding the same value. If it finds other string with the same value, then for a newly created string , a new object will not be created. Rather this will make a reference to already present String which in some way we can say made it for memory efficiency.
Let’s understand with a figure below.
2. Using new Keyword:
To over come the above approach, we can create String Object with a new keyword. By using new keyword, object will be created in Heap memory area, not in String constant pool. Let’s see how.
String val1 = new String("Java Book"); String val2 = new String("Java Book");
In next post , we will have a detailed view of String methods which are used to perform different operations on Strings.