Java Tutorial: Introduction to Strings
- A string is a sequence of characters.
- Strings are objects that represent a char array. For example :
is same as :
- Strings are immutable and cannot be changed.
- java.lang.String class is used to create a String object.
- The string is a class but can be used as a data type.
Syntax of strings in Java :
Example :
In the above example, str is a reference, and “CodeWithHemant” is an object.
Different ways to create a string in Java :
In Java, strings can be created in two ways :
- By using string literal
- By using the new
Creating String using String literal :
We use double quotes("") to create string using string literal. Before creating a new string instance, JVM verifies if the same string is already present in the string pool or not. If it is already present, then JVM returns a reference to the pooled instance otherwise, a new string instance is created.
"Hemant" is already present in the string pool, which is pointed by the str1. When we try to create the same string object using str2, JVM finds that string object with the value "Hemant" is already present in the string pool; therefore, instead of creating a new object, a reference to the same object is returned.
Creating String using new :
When we create a string using "new", a new object is always created in the heap memory.
Although the value of both string objects is the same, i.e., "Hemant" still two different objects are created, and they are referred by two different reference variables, i.e., str1 and str2.
See the examples given below to get a better understanding of String literal and String object :
Output :
Returns true because str1 and str2 are referencing the same object present in the string constant pool. Now, let's see the case of the String object :
Output :
Although the value of both the string object is the same, still false is displayed as output because str1 and str2 are two different string objects created in the heap. That's why it is not considered a good practice two compare two strings using the == operator. Always use the equals() method to compare two strings in Java.
Different ways to print in Java :
We can use the following ways to print in Java:
- System.out.print() // No newline at the end
- System.out.println() // Prints a new line at the end
- System.out.printf()
- System.out.format()
- %d for int
- %f for float
- %c for char
- %s for string
Code as written in the video
Handwritten Notes: Click To Download
Ultimate Java Cheatsheet: Click To Download