Java Strings: Understanding Immutable and Mutable Strings

🚀 Day 12 – Strings in Java | My Learning Journey Today I learned about one of the most important concepts in Java: Strings. Strings are widely used in almost every Java application because they help us store and manipulate textual data. 🔹 What is a String? A String is a sequence of characters such as letters, numbers, or symbols. In Java, a String is not a primitive data type; it is an object of the String class. Example: String name = "Java"; 🔹Types of Strings in Java There are mainly two types of strings: 1️⃣ Immutable Strings Once created, the value of the string cannot be changed. Any modification will create a new string object. Example: String s = "Hello"; s.concat(" World"); The original string "Hello" remains unchanged. 2️⃣ Mutable Strings Mutable strings allow modification of the content without creating a new object. Examples include: StringBuffer StringBuilder 🔹 Different Ways to Create Immutable Strings 1️⃣ Using String Literal String s1 = "Java"; 2️⃣ Using the new Keyword String s2 = new String("Java"); 3️⃣ Using Character Array char ch[] = {'J','a','v','a'}; String s3 = new String(ch); 🔹 Different Ways to Compare Strings 1️⃣ Using == Operator Compares memory references. String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); 2️⃣ Using equals() Method Compares actual string values. String s1 = "Java"; String s2 = "Java"; System.out.println(s1.equals(s2)); 3️⃣ Using compareTo() Method Used for lexicographical comparison of strings. 🔹 Where Are Strings Created in Memory? In Java, strings are stored in two memory areas: 📌 String Pool (inside Heap Memory) Stores string literals. If the same literal already exists, Java reuses the existing object. 📌 Heap Memory Strings created using the new keyword are stored in the heap memory. Example: String s1 = "Java"; // Stored in String Pool String s2 = new String("Java"); // Stored in Heap Understanding strings helps in writing efficient and optimized Java programs, especially when dealing with text processing, user input, and data manipulation. Learning about string creation, comparison, immutability, and memory management gave me a deeper understanding of how Java internally manages text data. #Java #StringsInJava #LearningJourney #Programming #JavaDeveloper #Coding

  • graphical user interface

To view or add a comment, sign in

Explore content categories