Strings in Java are sequences of characters enclosed within double quotes. They are widely used for storing and manipulating textual data. One crucial thing to note is that strings in Java are immutable, meaning they cannot be changed after creation.
Definition and Usage: String literals are the most common way to create strings in Java. A string literal is a sequence of characters enclosed within double quotes.
String firstName = "John"; String lastName = "Doe"; String fullName = "John Doe";
Strings created with the new keyword are not interned, which means that they may occupy more memory than their literal counterparts. Additionally, using new can create distinct string objects even if their content is the same.
When to Use new: You might use the new keyword when you want to create a string object that should not be interned or when you need to explicitly create a new string instance.
String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1 == str2); // false, because they are separate instances
You can convert other data types, such as numbers or objects, into strings: Using String.valueOf(): This method converts various data types to their string representation.
int num = 42; String strNum = String.valueOf(num);
Date date = new Date(); String strDate = date.toString();
Converting data types to strings is essential when you need to display or manipulate them as text.