String in java
String in java
In Java, you can create a string object using either string literals or the new keyword. While
both methods create String objects, there are some important differences between them:
1. String Literals:
When you create a string using a string literal (enclosed in double quotes), Java checks
the string pool to see if an identical string already exists. If it does, the existing reference
is returned; otherwise, a new String object is created in the pool. This is known as
"string interning."
Since string literals are automatically interned, they save memory and can improve
performance when comparing strings.
When you create a String using the new keyword, a new String object is always created
in the heap memory, regardless of whether the string content is the same as an existing
string.
String str1 = new String("Hello"); // Always creates a new object in the heap
String str2 = new String("Hello"); // Always creates another new object in
the heap
Using the new keyword is less memory-efficient compared to using string literals, as it
creates separate objects even if the content is the same.
4. Case Conversion:
String original = "Java Programming";
String lowerCase = original.toLowerCase(); // "java programming"
String upperCase = original.toUpperCase(); // "JAVA PROGRAMMING"