Java Strings: Memory, Types, and Concatenation

You've used String in Java hundreds of times. But do you actually know what happens in memory when you write one? 🤔 Most developers don't. Let's fix that. 🧵 --- 🔷 WHAT IS A STRING? A String is a sequence of characters enclosed within double quotes " ". A character uses single quotes ' ' — you cannot store multiple characters in single quotes. 'LUFFY' ❌ → error "LUFFY" ✅ → valid String --- 🔷 TWO TYPES OF STRINGS IN JAVA: 🔒 IMMUTABLE STRINGS (String class) → Value cannot be changed once created → Examples: Name of a person, Date of birth, Gender → Created using: String s = "JAVA"; or String s = new String("JAVA"); 🔓 MUTABLE STRINGS (StringBuffer / StringBuilder) → Value CAN be changed after creation → Examples: Password, Email ID, Months in a year → Created using: StringBuffer st = new StringBuffer(); --- 🔷 THREE WAYS TO CREATE A STRING: 1. String s = new String("JAVA"); 2. String s = "JAVA"; 3. char[] c = {'J','A','V','A'}; String s = new String(c); --- 🔷 WHERE ARE STRINGS STORED IN MEMORY? Strings live in the Heap Segment of the JRE, inside a special area called the String Pool. The String Pool has 2 partitions: 📦 CONSTANT POOL: → Strings created WITHOUT the new keyword → No duplicates allowed → Concatenation using both literals → goes here 📦 NON-CONSTANT POOL: → Strings created WITH the new keyword → Duplicates ARE allowed → Concatenation using references or one reference → goes here --- 🔑 KEY RULE — Where does concatenation go? "JAVA" + "PYTHON"  → Constant Pool (both literals) s1 + s2       → Non-Constant Pool (both references) s1 + "PYTHON"    → Non-Constant Pool (one reference involved) s1.concat("PYTHON") → Non-Constant Pool (always) --- 🔷 == vs equals() — The classic trap: String s1 = "JAVA"; String s2 = "JAVA"; s1 == s2 → true ✅ (same address in Constant Pool) String s1 = new String("JAVA"); String s2 = new String("JAVA"); s1 == s2 → false ❌ (different addresses in Non-Constant Pool) s1.equals(s2) → true ✅ (same value) Save this. Part 2 covers String Comparison in depth. 🔖 #Java #Strings #Programming #LearnToCode #JavaDeveloper #StringPool #ComputerScience

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories