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:
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.