String is a built-in class in java. String declaring formation is String str1 = "Java Learning";
.String
is a class name, str1
is the variable name, also known as reference, and "Java Learning"
I mean, anything with double quote is the string object as well as a string literal.
Heap and Pool
Heap : The heap in Java is a region of memory used for dynamic memory allocation. When Java applications run, objects are created on the heap, and the memory for these objects is managed by the Java Virtual Machine (JVM)
Pool : To save memory and improve performance by reusing immutable string objects, there is a special area in the Java heap called the String Pool to stores string literals.
Literals also occupies a space.
String objects
Methods that are used to create objects is called Constructor. String objects can be created with three types of constructors.
String(char[] )
It takes an array of characters.
char c[] = {'a', 'b', 'c', 'd'}; String str1 = new String(c)
(str coming out of char array)
String (byte[])
byte b[] = {65,66,67,68,69}; String str2 = new String(b);
(str coming out of byte array)
String(string)
When you create a string using
new
, two objects are created: one in the heap and one in the string pool.String str = new String("Java");
Heap: A new
String
object is created in the heap.String Pool: The literal
"Java"
is stored in the string pool if it doesn't already exist.
This means two objects are created: one in the heap (the new String
object) and one in the string pool (the "Java"
literal). However, the heap object will reference the pooled string. The string literal in the pool does not have a direct reference in your code but is used by the heap object.
Let's dig deeper :
str1
will reference to Java
. str2
won't allocate another unnecessary space for the same string, rather it will be referring to the pre existedJava
string. For str3
, a space in the heap will be created for the object but, as in pool there already exists
the same string, no space will be created in pool.
So, when you use new
, it might create two objects: one in the heap and one in the pool. However, if the string already exists in the pool, only the heap object will be created.
Creating String objects
public class StringPractice
{
public static void main(String[] args)
{
String str1 = "Java Program";
System.out.println(str1);
}
}
This will display Java Program
. Java Program
is a string literal, hence it will be created in pool with str1
referring to it.
public class StringPractice
{
public static void main(String[] args)
{
String str1 = "Java Program";
String str2 = new String("JAVA");
System.out.println(str2);
}
}
Here JAVA
will be displayed. The difference between these two object is, Java Program
will be is string pool with str1
as its reference area and JAVA
will be in heap having str2
as its reference and it will be created in pool too.
public class StringPractice
{
public static void main(String[] args)
{
String str1 = "Java Program";
String str2 = new String("JAVA");
char c[] = {'H', 'e', 'l','l','o'};
String str3 = new String(c);
byte b[] = {65,66,67,68};
String str4 = new String(b);
System.out.println(str3);
System.out.println(str4);
}
}
When you will print str3
, you will get Hello
and for str4,
you will get ABCD
We can perform slicing too. Look, if we write String str4 = new String(b,1,2);
instead of String str4 = new String(b);
then it will start printing from the 1st index and will be printing 2 letters. But you must provide two parameters otherwise it will strike off, means invalid.
This is the right way to do -
public class StringPractice
{
public static void main(String[] args)
{
char c[] = {'H', 'e', 'l','l','o'};
String str3 = new String(c,1);
byte b[] = {65,66,67,68};
String str4 = new String(b,1,3);
System.out.println(str3);
System.out.println(str4);
}
}
The output for str4 will be BCD
. It is applicable for char
too. You have to provide two parameter if you want to slice. Otherwise a red underline will appear like this,
And this is the right way,
And if you print str3, you will get ello
.
Tips : To see al the methods of String, got to command prompt and write javap java.lang.String
and hit enter, it will show you all the methods available for Java.Let me show you an example,
The marked ones are familiar to you, no? So yeah, this is it. You can look for more methods on the command prompt.
Remember I discussed about the heap and pool and how there's a possibility for an object to be created twice and all? Let's see them now.
public class StringPractice
{
public static void main(String[] args)
{
String str5 = "Java";
String str6 = "Java";
System.out.println(str5 == str6);
}
}
I have taken same string. So, is the program forming two different string or a single string? To check whether these two strings are same or not, I should compare their references. If these two references are holding the same object, then they will be equal(True). If not, they won't be equal (False). And after running the code, i got the result True
, that means they are the same object. So, Java is maintaining one single object here.
Now, what if i declare a string through new
and compare them? Will i get a true? I mean, will the two references will be referring to the same object?
public class StringPractice
{
public static void main(String[] args)
{
String str5 = "Java";
String str6 = "Java";
String str7 = new String("Java");
System.out.println(str5 == str7);
}
}
No they won't. Because str5's object is in the pool area whereas, str7's object is located in heap area, then it will exist in the pool separately only because of being a string literal.
String methods #1
String str = "Java";
int l = str.length()
: It will return the length of a string.str = str.toLowerCase
: It will change the string to lower case. ( String is immutable, this method will basically create e new object and return it. And If you writestr = str.toLowerCse
, str won't be pointing to the previous object, it will be pointing to the newly modified object + the new object will be created in the heap )str = str.toUpperCase
: Same
String str = " Welcome ";
str.trim()
: This will create a new object with removed spaces.Welcome
->Welcome
substring(starting index)
:String sub = str.substring(3);
substring(starting index, ending index
:String sub = str.substring(3,6);
Ending index is excluded.
str.replace(old letter, new letter)
: It replaces a letter with another letter in a string. Again, this does not change the original string.
Practicing String methods #1
public class StringPractice1
{
public static void main(String[] args)
{
String str1 = new String("Laptop");
System.out.println(str1.length()); //6
System.out.println(str1.toUpperCase()); //LAPTOP
System.out.println(str1.toLowerCase()); //laptop
//or,
String str2 = str1.toUpperCase();
System.out.println(str2); //LAPTOP
String str3 = new String(" Laptop ");
System.out.println(str3.trim()); //Laptop
System.out.println(str1.substring(2)); //ptop
System.out.println(str1.substring(2,4)); //pt
System.out.println(str1.replace('p','q')); //Laqtoq
}
}
Outputs:
String methods #2
Boolean
startsWith(String s)
: Suppose we have a website name. Now, how do we check if it's a website name? If we could somehow check if it starts with "www" or not, we could easily detect it. For this, we have a method that will do the checking and matching work.Boolean
endsWith(String s)
: Samechar
charAt(int index)
: It will return the character at the given index. You can use minus indexing tooint
indexOf(String/char s, starting point)
: It works like the opposite ofcharAt()
method. It returns the index of the provided string/character. Here, also you can provide a starting point from where you want to search.int
lastIndexOf(String s)
: It's the same but it will do a reverse search, like, from right to left.
Practicing String methods #2
public class StringPractice
{
public static void main(String[] args)
{
String str1 = "Mr. Cat";
System.out.println(str1.startsWith("Mr"));
System.out.println(str1.startsWith("mr"));
System.out.println(str1.startsWith("C"));
System.out.println(str1.startsWith("C",4));
System.out.println(str1.endsWith("t"));
System.out.println(str1.endsWith("T"));
System.out.println(str1.charAt(0));
String str2 = "www.cat.org";
System.out.println(str2.indexOf('.'));
System.out.println(str2.indexOf('.', 5));
System.out.println(str2.lastIndexOf('.'));
}
}
Outputs:
String methods #3
String str1 = "JAVA";
String str2 = "java";
String str3 = "python" ;
String str4 = "python" ;
Boolean
equals(String s)
: It will check if the objects are same or not.Note: Case sensitive
Boolean
equalsIgnoreCase(String s)
: It will check if the objects are same or not.Note: Not case sensitive
int
compareTo(String s)
: It returns-1
,0
,1
in basis of comparing 1st letter of the strings, checking in the dictionary order.-1
= if the first string comes first than the compared string0
= if both are same+1
= if the first string comes later than the compared stringNote: If the first letter of the string is uppercase, then it's considered smaller.
String
valueOf(int i)
: We can turn any kind of data type into integer using this method.
Extra: equals()
method VS ==
:
==
is used to compare references. equals()
is used to compare contents.
Practicing String methods #3
public class StringPractice3
{
public static void main(String[] args)
{
String str1 = "Pyramid";
String str2 = "Pyramid";
System.out.println(str1.equals(str2)); //true
String str3 = "pyramid";
System.out.println(str2.equals(str3)); //false
System.out.println(str2.equalsIgnoreCase(str3)); //true
System.out.println(str1 == str2); //true, references
System.out.println(str1 == str3); //false, references
String str4 = new String("Pyramid");
System.out.println(str1 == str4); //false, reference
System.out.println(str4.equals(str1)); //true, contents
System.out.println(str1.compareTo(str2)); //0
System.out.println(str1.compareTo(str3)); // -1, first letter's asci code is lower
System.out.println(str3.compareTo(str1)); // +1, first letter's asci code is greater
String str5 = "china";
System.out.println(str3.compareTo(str5)); // p comes before c, so the result is +ve
System.out.println(str5.compareTo(str3)); // c comes before p, so the result is -ve
String str6 = "I love Java";
System.out.println(str6.contains("love")); //true
}
}
Outputs :
-32
, 32
,13
,-13
these are the summation and subtraction of their asci values.
Homework
Find if the email id is on Gmail. Find username and domain from email.
String str = "programmer@gmail.com"
Previous Homework Answer
Write a code that will calculate the area of a triangle.
Formula: 1/2*base*height.
Formula : s = 1/2(a+b+c), area = √s(s-a)(s-b)(s-c)
That's it for today and be sure to try them out.
In the next blog, i will talk about Conditional Statements. In the meantime, don't forget to stay hydrated! Happy learning!
Reminder : Don't forget about your homework. I will attach the answer in the next blog.