Java Strings

Strings in Java

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.

Creating a Strings

  • Using String Literals

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.

Example
String firstName = "John";
String lastName = "Doe";
String fullName = "John Doe";
  • Using the new Keyword

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.

Example
String str1 = new String("Hello");
String str2 = new String("Hello");

System.out.println(str1 == str2); // false, because they are separate instances

Converting Other Data Types to Strings

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.

Example
int num = 42;
String strNum = String.valueOf(num);
  • Using toString(): Many objects in Java have a toString() method that returns a string representation of the object.
Example
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.

Contact Us

Name
Email
Mobile No:
subject:
Message: