2. String class in Java
String is a sequence of characters.
In Java, strings are treated as objects of String class.
The String class is part of the java.lang package and provides
various methods to manipulate and process strings.
In Java, objects of the String class are immutable which means
they cannot be changed once created.
3. String class in Java
There are two ways to create strings:
1. Using String Literal: The simplest way to create a string is by using a
string literal.This involves assigning a sequence of characters enclosed in
double quotes directly to a string variable.
Example: String Str = “Hello”;
2. Using New Keyword: Strings can be explicitly created as new objects
using the new keyword.
Example : String str = new String(“Hello”);
4. Memory Allocation of Java Strings
Heap Memory: Heap memory is a runtime memory area in Java
where objects and class instances are stored dynamically. It is
managed by the JVM (Java Virtual Machine) and is used for
memory allocation during program execution.
When we create a string using new keyword, it is stored in Heap
memory.
String Constant pool: The String Constant Pool (SCP) is a special
memory region inside the heap where string literals are stored.
When we create a string using String literal, it is stored in String constant
pool of Heap memory.
5. Memory Allocation of Strings
Creating String using new keyword creates a string in non-pool heap area.
String str1 = new String("Hello World!");
String str2 = new String("Hello World!");
In this example, two objects will be created and two references to those objects
will be created.
6. Memory Allocation of Java Strings
Creating Strings using String Literal
String s1="Welcome";
String s2="Welcome";
System.out.println(s1+" "+s2);
7. String Constant Pool
When a new string literal is
created, Java checks the Pool
for a matching string.
If found, the new variable
references the pooled string. If
not, the new string is added to
the Pool.
8. Heap and String Constant pool
Declare String using string literal: String
str1 = “Hello";
String str2= “Hello";
Declare String using new keyword:
String str3 = new String(“Hello");
String str4 = new String(“Hello");
Two objects are created having same
strings.
9. Creating Strings using string literals and using new keyword
Both methods store strings in memory differently, affecting performance, memory
usage, and reference behavior.
Creating a String using a String Literal:
Stored in: String Constant Pool (SCP) (inside Heap Memory)
Memory Efficiency: More efficient (Reuses existing strings)
Duplicates Allowed? No (Same literals share the same reference).
Example:
String s1 = "Hello"; // Stored in SCP
String s2 = "Hello"; // Reuses the same reference in SCP
System.out.println(s1 == s2); // true (Both point to the same object in SCP)
10. Creating Strings using string literals and using new keyword
Creating a String Using new Keyword:
Stored in: Heap Memory (Outside SCP)
Memory Efficiency: Less efficient (Creates a new object every time)
Duplicates Allowed? Yes (Each new String() creates a separate object)
Example:
String s3 = new String("Hello"); // New object in Heap
String s4 = new String("Hello"); // Another new object in Heap
System.out.println(s3 == s4); // false (Different objects in heap)
System.out.println(s3.equals(s4)); // true (Same content)
11. String Immutability in Java
What Does Immutable Mean?
An immutable object is an object whose state
cannot be modified after it is created. In Java, this
concept applies to strings, which means that once
a string object is created, its content cannot be
changed. If we try to change a string, a new
string object is created instead.
How are Strings Immutable in Java?
Strings in Java that are specified as
immutable, as the content shared storage in
a single pool to minimize creating a copy of
the same value.
Example:
String s = “sachin";
s.concat(" Tendulkar"); // s still points to
“sachin”
12. String Immutability in Java
Another Example:
A string is created using string
literal.
Str points to “ab” and when we
try to change the content of the
string pointed by str by
concatenating a new string “cd”.
A new object will be created
instead containing
concatenated string “abcd”.
And Str still points to the string
“ab”.
13. String Immutability in Java
More Examples
String str = "Hello World";
strnew= str.replace("World", "Java");
System.out.println(strnew); // Output: Hello World (unchanged)
replace() does not modify the original string.
A new string "Hello Java" is created but not assigned to str. Since str still refers to "Hello
World", the original value remains unchanged.
14. String Class Constructors
Java provides several constructors in the String class to create
String objects in different ways. These constructors allow us to
create a String from various sources like character arrays, byte
arrays, another string, or part of another string.
1. String():
String s = new String();
S=“Java”;
2. String(String str):
String s2 = new String("Hello Java");
3. String(char chars[ ]):
char chars[] = { 'a', 'b', 'c', 'd' };
String s3 = new String(chars);
15. String Class Constructors
4. String(char chars[ ], int startIndex, int count):
char chars[] = { 'w', 'i', 'n', 'd', 'o', 'w',
's' }; String str = new String(chars, 2, 3);
5. String(byte byteArr[ ]):
byte b[] = { 97, 98, 99, 100 };
String s = new String(b); //output- abcd
6. String(byte byteArr[ ], int startIndex, int count):
byte b[] = { 65, 66, 67, 68, 69, 70 };
String s = new String(b, 2, 4); //output-CDEF
16. String Methods
length() - Get the String Length
String str = "Hello, Java!";
System.out.println(str.length()); // Output: 12
toUpperCase() and toLowerCase()
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
17. String Methods
charAt(index) - Get Character at Specific Index
String str = "Java";
System.out.println(str.charAt(2)); // Output: v
substring(beginIndex, endIndex) - Extract a Substring
String str1 = "java is fun";
// extract substring from index 0 to 3
System.out.println(str1.substring(0, 4)); // Output: java
Extracts characters from beginIndex to endIndex - 1.
18. String Methods
startsWith() and endsWith() method:
The method startsWith() checks whether the String starts with the letters passed as arguments and endsWith()
method checks whether the String ends with the letters passed as arguments.
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
replace() Method (String target, String replacement)
The String class replace() method replaces all occurrence of first sequence of character with second sequence of
character.
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String s2=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"
System.out.println(s2);
Output: Kava is a programming language. Kava is a platform. Kava is an Island.
20. String methods
contains() - Check if a Substring Exists
String str = "Welcome to Java";
System.out.println(str.contains("Java")); // Output: true
split() - Split String into Array of substrings
String str = "apple banana orange";
String[] fruits = str.split(“ ");
for (String fruit : fruits) {
System.out.println(fruit); // apple, banana, orange
21. String methods
split() Parameters: split(String regex, int limit);
The string split() method can also take two parameters:
regex - the string is divided at this regex (can be strings)
limit (optional) - controls the number of resulting substrings
If the limit parameter is not passed, split() returns all possible substrings.
split() ReturnValue
returns an array of substrings.
String s1 = "alpha beta gama delta sigma";
String[] words = s1.split(" ", 3);
//using java loop to print elements of string array
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
Output:
alpha
beta
gama delta sigma
22. String methods
compareTo()
The compareTo() method compares two strings lexicographically (in the dictionary order).The comparison is based on the Unicode value of each character in the strings.
String str1 = "Learn Java";
String str2 = "Learn Java";
String str3 = "Learn Kolin";
int result;
// comparing str1 with str2
result = str1.compareTo(str2);
System.out.println(result); // 0
// comparing str1 with str3
result = str1.compareTo(str3);
System.out.println(result); // -1
// comparing str3 with str1
result = str3.compareTo(str1);
System.out.println(result); // 1
compareTo() Return Value
•returns 0 if the strings are equal
•returns a negative integer if the string comes before the str argument in the
dictionary order
•returns a positive integer if the string comes after the str argument in the
dictionary order
23. String methods
concat()
String str1 = "Hello";
String str2 = "World";
String result [] = str1.concat(str2);
System.out.println(result); // Output: HelloWorld
For more string methods:
https://www.programiz.com/java-programming/library/string